Skip to content

The only downloader you need. 下载器的集大成者。

feat(notice): 下载完成等提示可用右下角弹窗显示

XiaoYouChR2e10ce9df993
diff --git a/GLOSSARY.md b/GLOSSARY.md
index c333f009..98322b66 100644
--- a/GLOSSARY.md
+++ b/GLOSSARY.md
@@ -171,9 +171,13 @@ _Avoid_: worker、thread、chunk
### 用户告知
**Notice**:
-一次性的、需要告知用户的事件。发出即完成,不可撤回也不需要消解。
+一次性的、需要告知用户的事件。发出即完成,不可撤回也不需要消解。经由 Popup 或系统通知送达,用户在设置里二选一,也可以关闭。
_Avoid_: message、alert、event
+**Popup**:
+在屏幕右下角堆叠显示 Notice 的置顶窗口,不抢焦点,到时自动关闭。
+_Avoid_: dialog、toast、alert
+
**Pair Request**:
待决的浏览器配对请求,有始有终——用户批准或拒绝后消解。同时只有零或一个。
_Avoid_: 与 Notice 混淆(Notice 发出即完成,Pair Request 会被消解)
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.py
index bcd7a15f..b137b09c 100644
--- a/Ghost-Downloader-3.py
+++ b/Ghost-Downloader-3.py
@@ -3,12 +3,14 @@ from __future__ import annotations
import os
import sys
import traceback
+from dataclasses import replace
from typing import TYPE_CHECKING
from app.config.paths import APP_DATA_DIR
if TYPE_CHECKING:
from types import TracebackType
+ from desktop_notifier.common import Notification
from app.models.task import TaskError, TaskOptions
from app.platform.application import Application
from app.platform.instance import PrimaryInstance
@@ -67,7 +69,7 @@ def setupEnvironment() -> None:
def startApp(application: Application, primaryInstance: PrimaryInstance, isSilent: bool = False) -> None:
from PySide6.QtGui import QIcon
- from app.config.cfg import cfg
+ from app.config.cfg import NoticeStyle, cfg
from app.view.dialogs.name_conflict import NameConflictPrompt
from app.view.shell.clipboard_listener import ClipboardListener
from app.signal_bus import signalBus
@@ -244,11 +246,31 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilen
taskService.taskStarted.connect(lambda _: hold())
taskService.tasksAllCompleted.connect(release)
- from app.platform.desktop_notification import init, notifyTaskCompleted, notifyDiskSpaceInsufficient, notifyParseFailed
- coroutineRunner.submit(init(coroutineRunner.submit, signalBus.activationRequested.emit))
- taskService.taskCompleted.connect(notifyTaskCompleted)
- taskService.diskSpaceInsufficient.connect(notifyDiskSpaceInsufficient)
- engine.aria2RpcService.parseFailed.connect(notifyParseFailed)
+ from app.platform.desktop_notification import (
+ PopupNotifier, SystemNotifier, buildDiskSpaceInsufficient, buildParseFailed, buildTaskCompleted,
+ createPresence, toFileIcon,
+ )
+ systemNotifier = SystemNotifier(coroutineRunner.submit)
+ sendTo = {NoticeStyle.SYSTEM: systemNotifier.send, NoticeStyle.OFF: lambda _: None}
+ if NoticeStyle.POPUP in cfg.noticeStyle.options:
+ presence = createPresence()
+ popupNotifier = PopupNotifier(presence)
+ sendTo[NoticeStyle.POPUP] = popupNotifier.send
+ # 先于 onAboutToQuit 连接,engine.stop() 期间再来的 Notice 会被忽略
+ application.aboutToQuit.connect(presence.close)
+ application.aboutToQuit.connect(popupNotifier.clear)
+ activate = signalBus.activationRequested.emit
+
+ def sendNotice(notification: Notification) -> None:
+ if not cfg.isNoticeSoundEnabled.value:
+ notification = replace(notification, sound=None)
+ sendTo[cfg.noticeStyle.value](notification)
+
+ taskService.taskCompleted.connect(
+ lambda task: sendNotice(buildTaskCompleted(task, toFileIcon(task.outputPath))))
+ taskService.diskSpaceInsufficient.connect(
+ lambda free, needed: sendNotice(buildDiskSpaceInsufficient(free, needed, activate)))
+ engine.aria2RpcService.parseFailed.connect(lambda url, error: sendNotice(buildParseFailed(url, error, activate)))
taskService.tasksAllCompleted.connect(emptyWorkingSetIfIdle)
diff --git a/app/config/cfg.py b/app/config/cfg.py
index 6aa851f4..4d4be12c 100644
--- a/app/config/cfg.py
+++ b/app/config/cfg.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import os
import sys
from enum import Enum
from re import compile
@@ -122,6 +123,18 @@ class CloseMode(Enum):
QUIT = "Quit"
+class NoticeStyle(Enum):
+ POPUP = "Popup"
+ SYSTEM = "System"
+ OFF = "Off"
+
+
+def canShowPopup() -> bool:
+ # Wayland 不许客户端定位窗口;XWayland 在鼠标移到 Wayland 原生窗口时不发离开事件,Popup 会一直不关
+ return (sys.platform != "darwin" and os.environ.get("XDG_SESSION_TYPE") != "wayland"
+ and not os.environ.get("WAYLAND_DISPLAY"))
+
+
class ProxyValidator(ConfigValidator):
PATTERN = compile(
r"^"
@@ -376,6 +389,12 @@ class Config(QConfig):
OptionsValidator(CloseMode), EnumSerializer(CloseMode),
)
isClipboardListenerEnabled = ConfigItem("Software", "ClipboardListener", True, BoolValidator())
+ noticeStyle = OptionsConfigItem(
+ "Notice", "Style", NoticeStyle.POPUP if canShowPopup() else NoticeStyle.SYSTEM,
+ OptionsValidator([s for s in NoticeStyle if s != NoticeStyle.POPUP or canShowPopup()]),
+ EnumSerializer(NoticeStyle),
+ )
+ isNoticeSoundEnabled = ConfigItem("Notice", "SoundEnabled", True, BoolValidator())
clipboardIgnoredPacks: ConfigItem[list[str]] = ConfigItem("Software", "ClipboardIgnoredPacks", [], StringListValidator())
geometry = ConfigItem(
"Software", "Geometry", (0, 0, 0, 0), serializer=GeometrySerializer(),
diff --git a/app/platform/desktop_notification.py b/app/platform/desktop_notification.py
index d112dc57..2425d3d5 100644
--- a/app/platform/desktop_notification.py
+++ b/app/platform/desktop_notification.py
@@ -1,94 +1,631 @@
from __future__ import annotations
+import shutil
+import subprocess
+import sys
+import time
+from collections import deque
from collections.abc import Callable
+from dataclasses import replace
from pathlib import Path
from typing import TYPE_CHECKING
-from PySide6.QtCore import QCoreApplication, QFileInfo, QStandardPaths, Qt
-from PySide6.QtWidgets import QFileIconProvider
+from desktop_notifier.common import DEFAULT_SOUND, Button, Icon, Notification, Sound, Urgency
from loguru import logger
+from PySide6.QtCore import (
+ QCoreApplication, QEasingCurve, QFileInfo, QPoint, QPointF, QPropertyAnimation, QRectF,
+ QResource, QStandardPaths, Qt, QTimer, Signal as QtSignal,
+)
+from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPixmap, QScreen
+from PySide6.QtWidgets import QFileIconProvider, QHBoxLayout, QLabel, QSizePolicy, QVBoxLayout, QWidget
+from qfluentwidgets import (
+ BodyLabel, CaptionLabel, FluentIcon, IconWidget, InfoBarIcon, PushButton, StrongBodyLabel,
+ TransparentToolButton, isDarkTheme, qconfig,
+)
from app.platform.desktop import openFile, revealInFolder
+from app.platform.windows import isGreaterEqualWin11
+from app.signal import Signal
if TYPE_CHECKING:
+ from collections.abc import Coroutine
+
from app.models.task import Task, TaskError
- from desktop_notifier import DesktopNotifier
-notifier: DesktopNotifier | None = None
-_submit = None
+APP_NAME = "Ghost Downloader"
+LOGO_RESOURCE = ":/image/logo.png"
+SOUND_RESOURCE = ":/res/completed_task.wav"
+COMPLETE_SOUND = Sound(name="complete")
+
+WIDTH = 364
+PADDING = 16
+SCREEN_MARGIN = 12
+SPACING = 8
+ICON_SPACING = 12
+FILE_ICON_SIZE = 48
+STATUS_ICON_SIZE = 32
+CORNER_RADIUS = 8
+DEFAULT_DURATION = 5
+SOUND_INTERVAL = 1.0
+ENTER_DURATION, EXIT_DURATION, MOVE_DURATION = 333, 167, 250
+
+
+def toEasingCurve(x1: float, y1: float, x2: float, y2: float) -> QEasingCurve:
+ curve = QEasingCurve(QEasingCurve.Type.BezierSpline)
+ curve.addCubicBezierSegment(QPointF(x1, y1), QPointF(x2, y2), QPointF(1, 1))
+ return curve
+
+ENTER_CURVE, EXIT_CURVE, MOVE_CURVE = toEasingCurve(0, 0, 0, 1), toEasingCurve(1, 0, 1, 1), toEasingCurve(0.55, 0.55, 0, 1)
-async def init(submit, activate: Callable[[], None]) -> None:
- """点击没有自带 on_clicked 的通知时调用 activate。"""
- global _submit
- _submit = submit
- from desktop_notifier import DesktopNotifier as DN, Icon
- iconPath = Path(QStandardPaths.writableLocation(
- QStandardPaths.StandardLocation.TempLocation
- )) / "gd3_logo.png"
- if not iconPath.exists():
- from PySide6.QtCore import QResource
- with open(iconPath, "wb") as f:
- f.write(QResource(":/image/logo.png").data())
+def extractResource(resource: str) -> Path:
+ # 临时目录会被系统定期清理,不能只释放一次
+ path = Path(QStandardPaths.writableLocation(QStandardPaths.StandardLocation.TempLocation), f"gd_{Path(resource).name}")
+ data = QResource(resource).data()
+ if not path.exists() or path.stat().st_size != len(data):
+ path.write_bytes(data)
+ return path
+
+
+def toFileIcon(path: str) -> Icon | None:
+ # 系统通知异步读图标,固定文件名会被下一个任务覆盖
+ suffix = Path(path).suffix.lstrip(".").lower() or "folder"
+ iconPath = Path(QStandardPaths.writableLocation(QStandardPaths.StandardLocation.TempLocation), f"gd_icon_{suffix}.png")
+ pixmap = QFileIconProvider().icon(QFileInfo(path)).pixmap(48, 48).scaled(
+ 128, 128, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
+ if pixmap.isNull() or not pixmap.save(str(iconPath), "PNG"):
+ logger.debug("提取文件图标失败: {}", path)
+ return None
+ return Icon(path=iconPath)
+
+
+def buildTaskCompleted(task: Task, icon: Icon | None) -> Notification:
+ from app.format import toReadableSize
- global notifier
- notifier = DN(app_name="Ghost Downloader", app_icon=Icon(path=iconPath))
- notifier.on_clicked = lambda _identifier: activate()
+ outputPath = task.outputPath
+ return Notification(
+ title=QCoreApplication.translate("Notifications", "下载完成"),
+ message=f"{task.name}\n{toReadableSize(task.fileSize)} · {task.outputFolder}",
+ icon=icon,
+ buttons=(
+ Button(title=QCoreApplication.translate("Notifications", "打开文件"),
+ on_pressed=lambda: openFile(outputPath)),
+ Button(title=QCoreApplication.translate("Notifications", "打开文件夹"),
+ on_pressed=lambda: revealInFolder(outputPath)),
+ ),
+ on_clicked=lambda: openFile(outputPath),
+ sound=COMPLETE_SOUND,
+ )
-def notifyDiskSpaceInsufficient(free: int, needed: int) -> None:
- if notifier is None:
- return
+def buildDiskSpaceInsufficient(free: int, needed: int, activate: Callable[[], None]) -> Notification:
from app.format import toReadableSize
- _submit(notifier.send(
+
+ return Notification(
title=QCoreApplication.translate("Notifications", "磁盘空间不足"),
- message=QCoreApplication.translate("Notifications", "剩余 {0},需要 {1},任务未自动开始").format(
+ message=QCoreApplication.translate("Notifications", "任务未自动开始\n剩余 {0},需要 {1}").format(
toReadableSize(free), toReadableSize(needed)),
- ))
+ urgency=Urgency.Critical,
+ on_clicked=activate,
+ )
-def notifyParseFailed(url: str, error: TaskError) -> None:
- if notifier is None:
- return
+def buildParseFailed(url: str, error: TaskError, activate: Callable[[], None]) -> Notification:
from app.i18n import toLocalizedError
- displayUrl = url if len(url) <= 48 else f"{url[:45]}..."
- _submit(notifier.send(
+
+ return Notification(
title=QCoreApplication.translate("Notifications", "链接解析失败"),
- message=f"{displayUrl}\n{toLocalizedError(error)}",
- ))
+ message=f"{url}\n{toLocalizedError(error)}",
+ urgency=Urgency.Critical,
+ on_clicked=activate,
+ )
-def notifyTaskCompleted(task: Task) -> None:
- if notifier is None:
- return
+class SystemNotifier:
+ def __init__(self, submit: Callable[[Coroutine], object]):
+ self._submit = submit
+ self._notifier = None
- outputPath = task.outputPath
- if not outputPath:
- return
+ def send(self, notification: Notification) -> None:
+ # Windows 未打包的应用和 macOS 只能用系统默认提示音
+ if notification.sound and sys.platform != "linux":
+ notification = replace(notification, sound=DEFAULT_SOUND)
+ self._submit(self._send(notification, extractResource(LOGO_RESOURCE)))
- iconPath = Path(QStandardPaths.writableLocation(
- QStandardPaths.StandardLocation.TempLocation
- )) / "gd_finished_icon.png"
+ async def _send(self, notification: Notification, logoPath: Path) -> None:
+ # WinRT 后端要在 running loop 里构造
+ if self._notifier is None:
+ from desktop_notifier import DesktopNotifier
+ self._notifier = DesktopNotifier(app_name=APP_NAME, app_icon=Icon(path=logoPath))
+ await self._notifier.send_notification(notification)
- try:
- QFileIconProvider().icon(QFileInfo(outputPath)).pixmap(48, 48).scaled(
- 128, 128,
- aspectMode=Qt.AspectRatioMode.KeepAspectRatio,
- mode=Qt.TransformationMode.SmoothTransformation,
- ).save(str(iconPath), "PNG")
- except Exception as e:
- logger.debug("提取文件图标失败: {}", e)
- from desktop_notifier import Icon, Button
+class Presence:
+ """能否打扰用户,见 ADR 0029。changed 只表示状态可能变了,要用 canInterrupt 重新查询。"""
- _submit(notifier.send(
- title=QCoreApplication.translate("Notifications", "下载完成"),
- message=task.name,
- buttons=[
- Button(title=QCoreApplication.translate("Notifications", "打开文件"), on_pressed=lambda: openFile(outputPath)),
- Button(title=QCoreApplication.translate("Notifications", "打开文件夹"), on_pressed=lambda: revealInFolder(outputPath)),
- ],
- on_clicked=lambda: openFile(outputPath),
- icon=Icon(path=iconPath) if iconPath.exists() else None,
- ))
+ changed = Signal()
+
+ def canInterrupt(self) -> bool:
+ return True
+
+ def close(self) -> None:
+ pass
+
+
+if sys.platform == "win32":
+ import ctypes
+ from ctypes import wintypes
+
+ from PySide6.QtCore import QAbstractNativeEventFilter
+ from PySide6.QtGui import QWindow
+
+ user32 = ctypes.windll.user32
+ shell32 = ctypes.windll.shell32
+ wtsapi32 = ctypes.windll.wtsapi32
+ wtsapi32.WTSQuerySessionInformationW.argtypes = [
+ wintypes.HANDLE, wintypes.DWORD, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wintypes.DWORD)]
+ wtsapi32.WTSFreeMemory.argtypes = [ctypes.c_void_p]
+
+ WM_APP = 0x8000
+ WM_APPBAR = WM_APP + 1
+ WM_WTSSESSION_CHANGE = 0x02B1
+ WM_TASKBARCREATED = user32.RegisterWindowMessageW("TaskbarCreated")
+ ABM_NEW, ABM_REMOVE, ABN_FULLSCREENAPP = 0, 1, 2
+ WTS_SESSION_LOCK, WTS_SESSION_UNLOCK = 7, 8
+ WTS_CURRENT_SESSION, WTS_SESSION_INFO_EX, WTS_SESSIONSTATE_LOCK = 0xFFFFFFFF, 25, 0
+ QUNS_BUSY, QUNS_RUNNING_D3D_FULL_SCREEN, QUNS_PRESENTATION_MODE = 2, 3, 4
+ SPI_GETCLIENTAREAANIMATION, SPI_GETMESSAGEDURATION = 0x1042, 0x2016
+
+ class APPBARDATA(ctypes.Structure):
+ _fields_ = [("cbSize", wintypes.DWORD), ("hWnd", wintypes.HWND), ("uCallbackMessage", wintypes.UINT),
+ ("uEdge", wintypes.UINT), ("rc", wintypes.RECT), ("lParam", wintypes.LPARAM)]
+
+ class WindowsPresence(QAbstractNativeEventFilter, Presence):
+ def __init__(self):
+ super().__init__()
+ self._window = QWindow()
+ self._window.create()
+ self._hwnd = int(self._window.winId())
+ QCoreApplication.instance().installNativeEventFilter(self)
+ shell32.SHAppBarMessage(ABM_NEW, ctypes.byref(self._appbarData()))
+ if not wtsapi32.WTSRegisterSessionNotification(self._hwnd, 0):
+ logger.warning("注册会话通知失败: {}", ctypes.GetLastError())
+
+ def canInterrupt(self) -> bool:
+ buffer, size = ctypes.c_void_p(), wintypes.DWORD()
+ if wtsapi32.WTSQuerySessionInformationW(
+ None, WTS_CURRENT_SESSION, WTS_SESSION_INFO_EX, ctypes.byref(buffer), ctypes.byref(size)):
+ # WTSINFOEXW.Data.WTSInfoExLevel1.SessionFlags
+ isLocked = ctypes.c_int32.from_address(buffer.value + 16).value == WTS_SESSIONSTATE_LOCK
+ wtsapi32.WTSFreeMemory(buffer)
+ if isLocked:
+ return False
+ state = ctypes.c_int()
+ if shell32.SHQueryUserNotificationState(ctypes.byref(state)) != 0:
+ return True
+ return state.value not in (QUNS_BUSY, QUNS_RUNNING_D3D_FULL_SCREEN, QUNS_PRESENTATION_MODE)
+
+ def close(self) -> None:
+ shell32.SHAppBarMessage(ABM_REMOVE, ctypes.byref(self._appbarData()))
+ wtsapi32.WTSUnRegisterSessionNotification(self._hwnd)
+ QCoreApplication.instance().removeNativeEventFilter(self)
+ self._window.destroy()
+
+ def _appbarData(self) -> APPBARDATA:
+ data = APPBARDATA()
+ data.cbSize = ctypes.sizeof(APPBARDATA)
+ data.hWnd = self._hwnd
+ data.uCallbackMessage = WM_APPBAR
+ return data
+
+ def nativeEventFilter(self, eventType, message):
+ if bytes(eventType) != b"windows_generic_MSG":
+ return False, 0
+ msg = wintypes.MSG.from_address(int(message))
+ if msg.hWnd != self._hwnd:
+ return False, 0
+ if msg.message == WM_APPBAR and msg.wParam == ABN_FULLSCREENAPP:
+ self.changed.emit()
+ elif msg.message == WM_WTSSESSION_CHANGE and msg.wParam in (WTS_SESSION_LOCK, WTS_SESSION_UNLOCK):
+ self.changed.emit()
+ elif msg.message == WM_TASKBARCREATED:
+ shell32.SHAppBarMessage(ABM_NEW, ctypes.byref(self._appbarData()))
+ return False, 0
+
+
+if sys.platform == "linux":
+ from PySide6.QtCore import SLOT, QObject, Slot
+ from PySide6.QtDBus import QDBusConnection, QDBusMessage
+
+ LOGIND = "org.freedesktop.login1"
+ PROPERTIES = "org.freedesktop.DBus.Properties"
+ PROPERTIES_CHANGED_SLOT = SLOT("onPropertiesChanged(QString,QVariantMap,QStringList)")
+
+ class LinuxPresence(QObject, Presence):
+ def __init__(self, path: str):
+ super().__init__()
+ self._path = path
+ QDBusConnection.systemBus().connect(
+ LOGIND, path, PROPERTIES, "PropertiesChanged", self, PROPERTIES_CHANGED_SLOT)
+
+ def canInterrupt(self) -> bool:
+ message = QDBusMessage.createMethodCall(LOGIND, self._path, PROPERTIES, "Get")
+ message.setArguments([f"{LOGIND}.Session", "LockedHint"])
+ reply = QDBusConnection.systemBus().call(message)
+ if reply.type() == QDBusMessage.MessageType.ErrorMessage:
+ return True
+ return not reply.arguments()[0].variant()
+
+ def close(self) -> None:
+ QDBusConnection.systemBus().disconnect(
+ LOGIND, self._path, PROPERTIES, "PropertiesChanged", self, PROPERTIES_CHANGED_SLOT)
+
+ @Slot(str, "QVariantMap", "QStringList")
+ def onPropertiesChanged(self, interface: str, changed: dict, invalidated: list) -> None:
+ if "LockedHint" in changed or "LockedHint" in invalidated:
+ self.changed.emit()
+
+
+def createPresence() -> Presence:
+ if sys.platform == "win32":
+ return WindowsPresence()
+ if sys.platform == "linux":
+ message = QDBusMessage.createMethodCall(LOGIND, "/org/freedesktop/login1", f"{LOGIND}.Manager", "GetSession")
+ message.setArguments(["auto"])
+ reply = QDBusConnection.systemBus().call(message)
+ if reply.type() != QDBusMessage.MessageType.ErrorMessage:
+ return LinuxPresence(reply.arguments()[0].path())
+ logger.debug("logind 不可用,Popup 不判断锁屏: {}", reply.errorMessage())
+ return Presence()
+
+
+class Popup(QWidget):
+ exited = QtSignal()
+
+ def __init__(self, notification: Notification):
+ super().__init__()
+ self._notification = notification
+ self._duration = DEFAULT_DURATION if notification.timeout == -1 else notification.timeout
+ if notification.timeout == -1 and sys.platform == "win32":
+ seconds = wintypes.ULONG(DEFAULT_DURATION)
+ user32.SystemParametersInfoW(SPI_GETMESSAGEDURATION, 0, ctypes.byref(seconds), 0)
+ self._duration = seconds.value
+ self.isExiting = False
+ self._isHovered = False
+ self._targetPos = QPoint()
+ self._pressX: float | None = None
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+
+ def _initWidget(self) -> None:
+ self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Tool
+ | Qt.WindowType.WindowStaysOnTopHint | Qt.WindowType.WindowDoesNotAcceptFocus)
+ self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
+ self.setAttribute(Qt.WidgetAttribute.WA_X11DoNotAcceptFocus)
+ self._isAcrylic = isGreaterEqualWin11()
+ if sys.platform != "win32" or self._isAcrylic:
+ self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
+ self.setFixedWidth(WIDTH)
+ self.windowEffect = None
+ if sys.platform == "win32":
+ from qframelesswindow import WindowEffect
+ self.windowEffect = WindowEffect(self)
+ if self._isAcrylic:
+ self._applyAcrylic()
+ DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND = 33, 2
+ ctypes.windll.dwmapi.DwmSetWindowAttribute(
+ int(self.winId()), DWMWA_WINDOW_CORNER_PREFERENCE, ctypes.byref(ctypes.c_int(DWMWCP_ROUND)), 4)
+ else:
+ self.windowEffect.addMenuShadowEffect(self.winId())
+
+ self.logoLabel = QLabel(self)
+ self.logoLabel.setPixmap(self._toPixmap(QPixmap(LOGO_RESOURCE), 16))
+ self.appNameLabel = CaptionLabel(APP_NAME, self)
+ self.closeButton = TransparentToolButton(FluentIcon.CLOSE, self)
+ self.closeButton.setFixedSize(32, 32)
+ self.closeButton.setIconSize(self.closeButton.iconSize() * 0.75)
+ policy = self.closeButton.sizePolicy()
+ policy.setRetainSizeWhenHidden(True)
+ self.closeButton.setSizePolicy(policy)
+ self.closeButton.hide()
+
+ icon = self._notification.icon
+ if icon is not None and not (pixmap := QPixmap(str(icon.as_path()))).isNull():
+ self.iconWidget = QLabel(self)
+ self.iconWidget.setPixmap(self._toPixmap(pixmap, FILE_ICON_SIZE))
+ elif self._notification.urgency == Urgency.Critical:
+ self.iconWidget = IconWidget(InfoBarIcon.ERROR, self)
+ self.iconWidget.setFixedSize(STATUS_ICON_SIZE, STATUS_ICON_SIZE)
+ else:
+ self.iconWidget = QLabel(self)
+ self.iconWidget.setPixmap(self._toPixmap(QPixmap(LOGO_RESOURCE), FILE_ICON_SIZE))
+
+ textWidth = WIDTH - 2 * PADDING - FILE_ICON_SIZE - ICON_SPACING
+ lines = self._notification.message.splitlines() or [""]
+ self.titleLabel = StrongBodyLabel(self._notification.title, self)
+ self.bodyLabel = BodyLabel(self)
+ self.bodyLabel.setText(self.bodyLabel.fontMetrics().elidedText(lines[0], Qt.TextElideMode.ElideMiddle, textWidth))
+ self.bodyLabel.setToolTip(lines[0])
+ self.detailLabels = []
+ for line in lines[1:3]:
+ label = CaptionLabel(self)
+ label.setText(label.fontMetrics().elidedText(line, Qt.TextElideMode.ElideRight, textWidth))
+ label.setTextColor(QColor(0, 0, 0, 155), QColor(255, 255, 255, 155))
+ self.detailLabels.append(label)
+
+ self.buttons = []
+ for button in self._notification.buttons:
+ pushButton = PushButton(button.title, self)
+ pushButton.setFixedHeight(32)
+ pushButton.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+ self.buttons.append((pushButton, button))
+
+ self.closeTimer = QTimer(self)
+ self.closeTimer.setSingleShot(True)
+ self.moveAnimation = QPropertyAnimation(self, b"pos", self)
+
+ def _initLayout(self) -> None:
+ header = QHBoxLayout()
+ header.setContentsMargins(0, 0, 0, 0)
+ header.setSpacing(SPACING)
+ header.addWidget(self.logoLabel)
+ header.addWidget(self.appNameLabel)
+ header.addStretch(1)
+ header.addWidget(self.closeButton)
+
+ texts = QVBoxLayout()
+ texts.setContentsMargins(0, 0, 0, 0)
+ texts.setSpacing(2)
+ texts.addWidget(self.titleLabel)
+ texts.addWidget(self.bodyLabel)
+ for label in self.detailLabels:
+ texts.addWidget(label)
+
+ content = QHBoxLayout()
+ content.setContentsMargins(0, 0, PADDING // 2, 0)
+ content.setSpacing(ICON_SPACING)
+ content.addWidget(self.iconWidget, 0, Qt.AlignmentFlag.AlignTop)
+ content.addLayout(texts, 1)
+
+ layout = QVBoxLayout(self)
+ layout.setContentsMargins(PADDING, PADDING // 2, PADDING // 2, PADDING)
+ layout.setSpacing(SPACING)
+ layout.addLayout(header)
+ layout.addLayout(content)
+ if self.buttons:
+ buttons = QHBoxLayout()
+ buttons.setContentsMargins(0, SPACING, PADDING // 2, 0)
+ buttons.setSpacing(SPACING)
+ for pushButton, _ in self.buttons:
+ buttons.addWidget(pushButton)
+ layout.addLayout(buttons)
+ self.adjustSize()
+
+ def _bind(self) -> None:
+ self.moveAnimation.finished.connect(self._onMoveAnimationFinished)
+ self.closeButton.clicked.connect(lambda: self.exit(isDismissed=True))
+ self.closeTimer.timeout.connect(lambda: self.exit(isDismissed=True))
+ for pushButton, button in self.buttons:
+ pushButton.clicked.connect(lambda _=False, b=button: self._onButtonClicked(b))
+ qconfig.themeChanged.connect(self._onThemeChanged)
+
+ def _toPixmap(self, pixmap: QPixmap, size: int) -> QPixmap:
+ ratio = self.devicePixelRatioF()
+ scaled = pixmap.scaled(round(size * ratio), round(size * ratio),
+ Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
+ scaled.setDevicePixelRatio(ratio)
+ return scaled
+
+ def moveTo(self, pos: QPoint) -> None:
+ """第一次从屏幕右侧滑入,之后平移到 pos。"""
+ isMoved = pos != self._targetPos
+ self._targetPos = pos
+ if not self.isVisible():
+ self.move(pos.x() + self.width() + SCREEN_MARGIN, pos.y())
+ self.show()
+ self._animate(pos, ENTER_DURATION, ENTER_CURVE)
+ self._restartTimer()
+ elif isMoved and self._pressX is None:
+ self._animate(pos, MOVE_DURATION, MOVE_CURVE)
+
+ def exit(self, isDismissed: bool) -> None:
+ if self.isExiting:
+ return
+ self.isExiting = True
+ self.closeTimer.stop()
+ self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
+ if isDismissed and self._notification.on_dismissed:
+ self._notification.on_dismissed()
+ self._animate(QPoint(self._targetPos.x() + self.width() + SCREEN_MARGIN, self.y()),
+ EXIT_DURATION, EXIT_CURVE)
+
+ def _animate(self, pos: QPoint, duration: int, curve: QEasingCurve) -> None:
+ self.moveAnimation.stop()
+ isAnimated = True
+ if sys.platform == "win32":
+ value = wintypes.BOOL(True)
+ user32.SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION, 0, ctypes.byref(value), 0)
+ isAnimated = bool(value.value)
+ if not isAnimated:
+ self.move(pos)
+ QTimer.singleShot(0, self._onMoveAnimationFinished)
+ return
+ self.moveAnimation.setDuration(duration)
+ self.moveAnimation.setEasingCurve(curve)
+ self.moveAnimation.setStartValue(self.pos())
+ self.moveAnimation.setEndValue(pos)
+ self.moveAnimation.start()
+
+ def _restartTimer(self) -> None:
+ if self._duration > 0 and not self._isHovered and not self.isExiting:
+ self.closeTimer.start(self._duration * 1000)
+
+ def _onButtonClicked(self, button: Button) -> None:
+ if button.on_pressed:
+ button.on_pressed()
+ self.exit(isDismissed=False)
+
+ def _onMoveAnimationFinished(self) -> None:
+ if self.isExiting:
+ self.exited.emit()
+
+ def _onThemeChanged(self) -> None:
+ self._applyAcrylic()
+ self.update()
+
+ def _applyAcrylic(self) -> None:
+ if self._isAcrylic:
+ self.windowEffect.setAcrylicEffect(self.winId(), "20202030" if isDarkTheme() else "FFFFFF30")
+
+ def closeEvent(self, event) -> None:
+ self.closeTimer.stop()
+ self.moveAnimation.stop()
+ super().closeEvent(event)
+
+ def paintEvent(self, event) -> None:
+ isDark = isDarkTheme()
+ painter = QPainter(self)
+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)
+ radius = 0 if sys.platform == "win32" and not self._isAcrylic else CORNER_RADIUS
+ if self._isAcrylic:
+ # layered 窗口里全透明的像素会让鼠标点穿
+ painter.fillRect(self.rect(), QColor(0, 0, 0, 1))
+ else:
+ painter.setBrush(QColor(44, 44, 44) if isDark else QColor(249, 249, 249))
+ painter.setPen(QColor(255, 255, 255, 20) if isDark else QColor(0, 0, 0, 15))
+ painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), radius, radius)
+ if self._isHovered:
+ painter.setPen(Qt.PenStyle.NoPen)
+ painter.setBrush(QColor(255, 255, 255, 15) if isDark else QColor(0, 0, 0, 10))
+ painter.drawRoundedRect(QRectF(self.rect()), radius, radius)
+
+ def enterEvent(self, event) -> None:
+ self._isHovered = True
+ self.closeTimer.stop()
+ self.closeButton.show()
+ self.update()
+ super().enterEvent(event)
+
+ def leaveEvent(self, event) -> None:
+ self._isHovered = False
+ self.closeButton.hide()
+ self.update()
+ self._restartTimer()
+ super().leaveEvent(event)
+
+ def mousePressEvent(self, event) -> None:
+ if event.button() == Qt.MouseButton.LeftButton:
+ self._pressX = event.globalPosition().x()
+ self.moveAnimation.stop()
+ super().mousePressEvent(event)
+
+ def mouseMoveEvent(self, event) -> None:
+ if self._pressX is not None:
+ offset = max(0, round(event.globalPosition().x() - self._pressX))
+ self.move(self._targetPos.x() + offset, self._targetPos.y())
+ super().mouseMoveEvent(event)
+
+ def mouseReleaseEvent(self, event) -> None:
+ if event.button() != Qt.MouseButton.LeftButton or self._pressX is None:
+ return super().mouseReleaseEvent(event)
+ offset = event.globalPosition().x() - self._pressX
+ self._pressX = None
+ if offset > self.width() / 3:
+ self.exit(isDismissed=True)
+ elif offset > 4:
+ self._animate(self._targetPos, MOVE_DURATION, MOVE_CURVE)
+ elif self._notification.on_clicked:
+ self._notification.on_clicked()
+ self.exit(isDismissed=False)
+ super().mouseReleaseEvent(event)
+
+
+class PopupNotifier:
+ """只能在 Qt 主线程调用。"""
+
+ def __init__(self, presence: Presence):
+ self._presence = presence
+ self._popups: list[Popup] = [] # 最早的在前;没有 parent 的窗口靠这里的引用存活
+ self._pending: deque[Notification] = deque()
+ self._lastSoundAt = float("-inf")
+ self._isClosed = False
+ presence.changed.connect(self._showPending)
+ QGuiApplication.instance().primaryScreenChanged.connect(self._onPrimaryScreenChanged)
+ self._onPrimaryScreenChanged(QGuiApplication.primaryScreen())
+
+ def send(self, notification: Notification) -> None:
+ if self._isClosed:
+ return
+ self._pending.append(notification)
+ self._showPending()
+
+ def clear(self) -> None:
+ """立即关闭全部 Popup,不触发 on_dismissed;之后的 send 一律忽略。"""
+ self._isClosed = True
+ self._pending.clear()
+ for popup in self._popups:
+ popup.close()
+ popup.deleteLater()
+ self._popups.clear()
+
+ def _showPending(self) -> None:
+ if not self._pending or QGuiApplication.primaryScreen() is None or not self._presence.canInterrupt():
+ return
+ while self._pending:
+ notification = self._pending.popleft()
+ popup = Popup(notification)
+ popup.exited.connect(lambda p=popup: self._remove(p))
+ self._popups.append(popup)
+ if notification.sound and time.monotonic() - self._lastSoundAt >= SOUND_INTERVAL:
+ self._lastSoundAt = time.monotonic()
+ self._playSound()
+ self._arrange()
+
+ def _playSound(self) -> None:
+ path = str(extractResource(SOUND_RESOURCE))
+ if sys.platform == "win32":
+ import winsound
+ winsound.PlaySound(path, winsound.SND_FILENAME | winsound.SND_ASYNC | winsound.SND_NODEFAULT)
+ return
+ for command in (("pw-play", "--media-role=Notification"),
+ ("paplay", "--property=media.role=event"),
+ ("canberra-gtk-play", "-f")):
+ if executable := shutil.which(command[0]):
+ subprocess.Popen([executable, *command[1:], path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ return
+ logger.debug("找不到播放器,跳过提示音")
+
+ def _arrange(self) -> None:
+ screen = QGuiApplication.primaryScreen()
+ if screen is None:
+ return
+ area = screen.availableGeometry()
+ right = area.x() + area.width() - SCREEN_MARGIN
+ bottom = area.y() + area.height() - SCREEN_MARGIN
+ top = area.y() + SCREEN_MARGIN
+ isFull = False
+ for popup in reversed([p for p in self._popups if not p.isExiting]):
+ y = bottom - popup.height()
+ if isFull or y < top:
+ isFull = True
+ popup.exit(isDismissed=True)
+ continue
+ popup.moveTo(QPoint(right - popup.width(), y))
+ bottom = y - SPACING
+
+ def _remove(self, popup: Popup) -> None:
+ if popup not in self._popups:
+ return
+ self._popups.remove(popup)
+ popup.close()
+ popup.deleteLater()
+ self._arrange()
+
+ def _onPrimaryScreenChanged(self, screen: QScreen | None) -> None:
+ # 不断开旧屏幕:它被销毁时 Qt 自动断开,还在时多排一次也无害
+ if screen is not None:
+ screen.availableGeometryChanged.connect(self._arrange)
+ self._arrange()
+ self._showPending()
diff --git a/app/view/pages/setting_page.py b/app/view/pages/setting_page.py
index c1e857de..de214ccd 100644
--- a/app/view/pages/setting_page.py
+++ b/app/view/pages/setting_page.py
@@ -13,7 +13,7 @@ from qfluentwidgets import (
from app.view.components.scroll_area import FastScrollArea, PAGE_MARGIN
-from app.config.cfg import cfg, LANGUAGE_TEXTS
+from app.config.cfg import NoticeStyle, cfg, LANGUAGE_TEXTS
from app.i18n import toLocalizedError
from app.models.task import toTaskError
from app.services.port_listener import ListenStatus
@@ -354,6 +354,14 @@ class SettingPage(FastScrollArea):
self.tr("设置关闭主窗口后程序继续在后台运行还是退出"),
texts=[self.tr("关闭时询问"), self.tr("继续在后台运行"), self.tr("退出程序")],
),
+ ComboBoxSettingCard(
+ cfg.noticeStyle, FluentIcon.RINGER, self.tr("通知方式"),
+ self.tr("下载完成、磁盘空间不足等提示的显示方式"),
+ texts=[{NoticeStyle.POPUP: self.tr("弹窗"), NoticeStyle.SYSTEM: self.tr("系统通知"),
+ NoticeStyle.OFF: self.tr("关闭")}[style] for style in cfg.noticeStyle.options],
+ ),
+ SwitchSettingCard(FluentIcon.VOLUME, self.tr("通知提示音"),
+ self.tr("下载完成时播放提示音"), cfg.isNoticeSoundEnabled),
ClipboardSettingCard(self._featureService.packs),
self.migrateCard,
]
diff --git a/docs/adr/0027-notice-uses-desktop-notifier-types.md b/docs/adr/0027-notice-uses-desktop-notifier-types.md
new file mode 100644
index 00000000..f3219280
--- /dev/null
+++ b/docs/adr/0027-notice-uses-desktop-notifier-types.md
@@ -0,0 +1,13 @@
+# Notice 直接使用 desktop-notifier 的类型
+
+Notice 有两个送达渠道:Popup 和系统通知。两者共用同一个接口 `send(notification: Notification)`,参数直接用 desktop-notifier 的 `Notification`、`Button`、`Icon`、`Sound`,不另外定义 Notice 类型。这样系统通知渠道原样转交即可,没有转换代码;Popup 也和系统通知一样,按 desktop-notifier 的字段语义行事(例如 `timeout`:`-1` 跟随系统、`0` 不关闭、正数为秒数,与 freedesktop 规范一致)。
+
+## Considered Options
+
+- **自定义 Notice dataclass,两个 Adapter 各自转换**:字段与 `Notification` 几乎一一对应,多出一层纯转发。
+
+## Consequences
+
+- View 层(Popup)依赖第三方类型。导入只走 `desktop_notifier.common`,不触发后端加载。
+- Popup 忽略 `reply_field`、`attachment`、`thread`。
+- 同一个 `Notification` 可能在 asyncio 线程(系统通知)或 Qt 主线程(Popup)回调,所以回调只能做线程无关的事。
diff --git a/docs/adr/0028-notice-sound-without-qtmultimedia.md b/docs/adr/0028-notice-sound-without-qtmultimedia.md
new file mode 100644
index 00000000..f886b7fb
--- /dev/null
+++ b/docs/adr/0028-notice-sound-without-qtmultimedia.md
@@ -0,0 +1,14 @@
+# 提示音不用 QtMultimedia
+
+Popup 的提示音在 Windows 上用标准库的 `winsound.PlaySound`,在 Linux 上依次尝试 `pw-play`、`paplay`、`canberra-gtk-play`,并给音频流打上事件 role,不用 `QSoundEffect`。这样打包体积不增加,提示音也跟随系统"系统声音"那一路的音量和静音。
+
+## Considered Options
+
+- **`QSoundEffect`**:跨平台,只有一条代码路径。在 PySide6 6.10 上实测,只播放 WAV 不需要 FFmpeg 后端,但仍要多打包 `libQt6Multimedia` 和绑定,约 2.5 MB;而且 Nuitka 默认插件列表一旦把 `multimedia` 族加进去,FFmpeg(约 19 MB)就会被带进来。
+- **libcanberra / GSound**:Linux 上的正统做法,但 PySide 没有绑定,上游也已停止维护。
+- **`aplay`**:直通 ALSA,绕过声音服务器,用户的系统声音设置对它无效。
+
+## Consequences
+
+- Linux 上能否出声取决于用户 PATH 里有没有这几个播放器;都没有时只记 debug 日志,不报错。
+- `winsound` 不支持从内存异步播放,wav 要先从 qrc 释放到临时目录。
diff --git a/docs/adr/0029-presence-via-appbar-wts-and-logind.md b/docs/adr/0029-presence-via-appbar-wts-and-logind.md
new file mode 100644
index 00000000..6aaa7180
--- /dev/null
+++ b/docs/adr/0029-presence-via-appbar-wts-and-logind.md
@@ -0,0 +1,32 @@
+# 用 appbar、WTS 和 logind 判断能否打扰用户
+
+Popup 置顶显示,必须避开全屏、演示和锁屏,否则会打断全屏游戏(独占全屏下出现置顶窗口,游戏可能被最小化),或在锁屏期间到时关闭而无人看见。这类时候 Popup 先暂存,等到可以打扰再显示。判断由 `Presence` 负责:`send` 时同步查询一次,此后只在系统事件唤醒时重新查询,不轮询。
+
+- **Windows**:锁屏以 `WTSQuerySessionInformation` 的 `SessionFlags` 为准,全屏和演示以 `SHQueryUserNotificationState` 为准(`BUSY`、`RUNNING_D3D_FULL_SCREEN`、`PRESENTATION_MODE` 不能打扰)。唤醒事件有三个:
+ - `ABN_FULLSCREENAPP`:用一个隐藏窗口 `ABM_NEW` 注册 appbar,不 `ABM_SETPOS`,所以不占屏幕空间;退出前 `ABM_REMOVE`。
+ - `WM_WTSSESSION_CHANGE`:`WTSRegisterSessionNotification` 注册,锁屏、解锁时送达;退出前注销。
+ - `TaskbarCreated`:Explorer 重启后会广播它,收到后重新注册 appbar。
+
+ 全屏应用的进出系统不会发任何通知,只有 appbar 能收到,这就是注册一个 appbar 的原因。
+- **X11**:读 logind 会话的 `LockedHint`,订阅它的 `PropertiesChanged`。全屏交给窗口管理器处理:按 EWMH 的堆叠顺序,获得焦点的全屏窗口位于 ABOVE 层之上,Popup 盖不住它。
+
+## Considered Options
+
+- **轮询状态**:空耗 CPU。
+- **锁屏也用 `SHQueryUserNotificationState`(`NOT_PRESENT`)**:实测它比会话事件慢半拍到 1 秒,解锁事件到达时仍报告 `NOT_PRESENT`,暂存的 Popup 要等下一条 Notice 才放出来。WTS 在事件到达时已是新状态。
+- **`WM_SETTINGCHANGE`**:实测锁屏、解锁时都不发。
+- **`org.freedesktop.ScreenSaver.ActiveChanged`**:不在 freedesktop 规范里(规范只定义了 `Inhibit` 和 `UnInhibit`),GNOME 把它放在 `org.gnome.ScreenSaver` 上。
+- **用户忙时改走系统通知**:用户回到电脑前看不到 Popup,两个 Adapter 互相依赖,系统通知被用户关掉时 Notice 还会彻底丢失。
+
+## Consequences
+
+- 各项查询失败都按可以打扰处理。
+- 只在 Popup 出现前判断。已经显示的 Popup 不因随后进入全屏或锁屏而收起,留到计时结束;这几秒的打扰换来实现简单。
+- `QUNS_QUIET_TIME` 指新账户首次登录后的一小时,不是勿扰模式,按可以打扰处理;勿扰模式不影响 Popup。
+- 不锁屏的屏保(`NOT_PRESENT`)不拦截 Popup。
+- 演示模式退出时没有唤醒事件。每次 `send` 都会顺带重试暂存队列,漏掉的唤醒由下一条 Notice 补上。
+- `WTSRegisterSessionNotification` 在远程桌面服务就绪前调用会失败。应用在登录后才自启,此时服务早已就绪,所以只注册一次,失败时记日志,不等待 `Global\TermSrvReadyEvent`。
+- appbar 回调和会话事件每次都会先后送达两份,两份的查询结果可能不同,重新查询必须是幂等的。
+- `ABN_FULLSCREENAPP` 是否涵盖副屏尚未验证。
+- X11 上 Popup 可能在全屏窗口后面到时关闭,用户看不见。
+- 没有 logind 的 Linux 一律视为可以打扰。
diff --git a/docs/adr/0031-popup-uses-accent-acrylic.md b/docs/adr/0031-popup-uses-accent-acrylic.md
new file mode 100644
index 00000000..251c37a7
--- /dev/null
+++ b/docs/adr/0031-popup-uses-accent-acrylic.md
@@ -0,0 +1,15 @@
+# Popup 用 accent 亚克力,不用 DWM 系统背景
+
+Win11 上 Popup 的亚克力用未公开的 `SetWindowCompositionAttribute(ACCENT_ENABLE_ACRYLICBLURBEHIND)`(qframelesswindow 的 `WindowEffect.setAcrylicEffect`),配合 `WA_TranslucentBackground` 和 `DWMWCP_ROUND` 圆角。有文档的 `DWMWA_SYSTEMBACKDROP_TYPE`(`DWMSBT_TRANSIENTWINDOW`)实测在 Popup 上不显示:DWM 只给激活的窗口画系统背景,而 Popup 永不激活。
+
+## Considered Options
+
+- **`DWMSBT_TRANSIENTWINDOW` + `ExtendFrame(-1)`**:窗口不是 layered 时客户区可交给 DWM,但非激活窗口不画背景;`WA_TranslucentBackground` 又会让无边框窗口变成 `WS_EX_LAYERED`,DWM 也不画。
+- **再发 `WM_NCACTIVATE(TRUE)` 伪装激活**:实测无效。
+
+## Consequences
+
+- 窗口是 layered 的,客户区要用 alpha=1 的颜色铺满,否则透明处鼠标会点穿。
+- 亚克力的混合色按应用主题取色。系统关闭"透明效果"时,accent 亚克力把混合色当不透明底色画,主题依然正确,不需要读该设置。
+- Win10 上 accent 亚克力在窗口移动时会卡顿,而 Popup 的进入、退出、重排都是移动动画,所以 Win10 用纯色直角。
+- 阴影来自 accent 的阴影标志位,不用 `QGraphicsDropShadowEffect`。
diff --git a/tests/test_notice.py b/tests/test_notice.py
new file mode 100644
index 00000000..72617cc3
--- /dev/null
+++ b/tests/test_notice.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+import os
+
+# Popup 是真窗口,在 offscreen 平台上测,不打扰桌面;须在 QApplication 创建前设置
+os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
+
+import pytest
+from desktop_notifier.common import Button, Notification, Urgency
+from PySide6.QtCore import Qt
+from PySide6.QtWidgets import QApplication
+
+from app.models.task import Task, TaskError
+from app.platform import desktop_notification
+from app.platform.desktop_notification import (
+ SCREEN_MARGIN, SPACING, Popup, PopupNotifier, Presence, buildDiskSpaceInsufficient, buildParseFailed,
+ buildTaskCompleted,
+)
+
+
+def shownPopups() -> list[Popup]:
+ return [w for w in QApplication.topLevelWidgets() if isinstance(w, Popup) and w.isVisible() and not w.isExiting]
+
+
+def isSettled() -> bool:
+ return all(p.moveAnimation.state() == p.moveAnimation.State.Stopped for p in shownPopups())
+
+
+def buildNotice(title: str = "下载完成", timeout: int = 0, **kwargs) -> Notification:
+ return Notification(title=title, message="ubuntu.iso\n5.00 GB · /tmp", timeout=timeout, **kwargs)
+
+
+def popupNotifier(qapp):
+ notifier = PopupNotifier(Presence())
+ yield notifier
+ notifier.clear()
+
+
+def test_build_task_completed_opens_output(monkeypatch, tmp_path):
+ opened = []
+ monkeypatch.setattr(desktop_notification, "openFile", lambda path: opened.append(("open", path)))
+ monkeypatch.setattr(desktop_notification, "revealInFolder", lambda path: opened.append(("reveal", path)))
+ task = Task(name="ubuntu.iso", url="https://example.com/ubuntu.iso", packId="http", outputFolder=tmp_path,
+ fileSize=5 * 1024 ** 3)
+
+ notification = buildTaskCompleted(task, None)
+
+ assert notification.message.splitlines() == ["ubuntu.iso", f"5.00 GB · {tmp_path}"]
+ for button in notification.buttons:
+ button.on_pressed()
+ notification.on_clicked()
+ outputPath = str(tmp_path / "ubuntu.iso")
+ assert opened == [("open", outputPath), ("reveal", outputPath), ("open", outputPath)]
+
+
+def test_build_error_notices_activate_window_on_click():
+ activated = []
+
+ diskSpace = buildDiskSpaceInsufficient(1024, 2048, lambda: activated.append("disk"))
+ parseFailed = buildParseFailed("https://example.com/a", TaskError("UNKNOWN"), lambda: activated.append("parse"))
+
+ assert diskSpace.message.splitlines()[0] == "任务未自动开始"
+ assert parseFailed.message.splitlines()[0] == "https://example.com/a"
+ assert diskSpace.urgency == parseFailed.urgency == Urgency.Critical
+ diskSpace.on_clicked()
+ parseFailed.on_clicked()
+ assert activated == ["disk", "parse"]
+
+
+def test_send_stacks_newest_at_bottom_right(qtbot, popupNotifier):
+ for title in ("一", "二", "三"):
+ popupNotifier.send(buildNotice(title))
+
+ qtbot.waitUntil(lambda: len(shownPopups()) == 3 and isSettled())
+ area = QApplication.primaryScreen().availableGeometry()
+ popups = sorted(shownPopups(), key=lambda p: p.y())
+ assert [p.titleLabel.text() for p in popups] == ["一", "二", "三"]
+ assert popups[-1].geometry().bottom() == area.bottom() - SCREEN_MARGIN
+ assert {p.geometry().right() for p in popups} == {area.right() - SCREEN_MARGIN}
+ for upper, lower in zip(popups, popups[1:]):
+ assert lower.y() - upper.geometry().bottom() - 1 == SPACING
+
+
+def test_send_beyond_screen_dismisses_oldest(qtbot, popupNotifier):
+ dismissed = []
+ for index in range(12):
+ popupNotifier.send(buildNotice(str(index), on_dismissed=lambda i=index: dismissed.append(i)))
+
+ area = QApplication.primaryScreen().availableGeometry()
+ qtbot.waitUntil(lambda: dismissed and isSettled())
+ remaining = sorted(int(p.titleLabel.text()) for p in shownPopups())
+ assert all(p.y() >= area.top() + SCREEN_MARGIN for p in shownPopups())
+ assert remaining == list(range(12 - len(remaining), 12))
+ assert sorted(dismissed) == list(range(12 - len(remaining)))
+
+
+def test_send_with_timeout_dismisses_after_duration(qtbot, popupNotifier):
+ dismissed = []
+ popupNotifier.send(buildNotice(timeout=1, on_dismissed=lambda: dismissed.append(True)))
+
+ qtbot.waitUntil(lambda: len(shownPopups()) == 1)
+ qtbot.waitUntil(lambda: dismissed == [True] and not shownPopups(), timeout=3000)
+
+
+def test_press_button_runs_action_without_dismissing(qtbot, popupNotifier):
+ events = []
+ popupNotifier.send(buildNotice(
+ buttons=(Button(title="打开文件", on_pressed=lambda: events.append("pressed")),),
+ on_dismissed=lambda: events.append("dismissed"),
+ ))
+ qtbot.waitUntil(lambda: len(shownPopups()) == 1)
+
+ pushButton, _ = shownPopups()[0].buttons[0]
+ qtbot.mouseClick(pushButton, Qt.MouseButton.LeftButton)
+
+ qtbot.waitUntil(lambda: not shownPopups())
+ assert events == ["pressed"]
+
+
+def test_clear_closes_silently_and_ignores_later_send(qtbot, popupNotifier):
+ dismissed = []
+ popupNotifier.send(buildNotice(on_dismissed=lambda: dismissed.append(True)))
+ qtbot.waitUntil(lambda: len(shownPopups()) == 1)
+
+ popupNotifier.clear()
+ popupNotifier.send(buildNotice())
+
+ assert not shownPopups()
+ assert dismissed == []