Skip to content

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

feat(notice): 新增下载进度弹窗,剪贴板和配对请求改用弹窗询问 #960 #1089

XiaoYouChR8a8e54f0c640
diff --git a/GLOSSARY.md b/GLOSSARY.md
index 98322b66..f7724798 100644
--- a/GLOSSARY.md
+++ b/GLOSSARY.md
@@ -175,12 +175,24 @@ _Avoid_: worker、thread、chunk
_Avoid_: message、alert、event
**Popup**:
-在屏幕右下角堆叠显示 Notice 的置顶窗口,不抢焦点,到时自动关闭。
+在屏幕右下角堆叠显示的置顶卡片,不抢焦点。承载 Notice、Request 或 Task Popup;同一件事在屏幕上只有一张。
_Avoid_: dialog、toast、alert
+**Request**:
+等待用户决定的询问,用户决定后消解。同类 Request 同时只有零或一个。
+_Avoid_: 与 Notice 混淆(Notice 发出即完成,Request 会被消解)
+
**Pair Request**:
-待决的浏览器配对请求,有始有终——用户批准或拒绝后消解。同时只有零或一个。
-_Avoid_: 与 Notice 混淆(Notice 发出即完成,Pair Request 会被消解)
+待决的浏览器配对请求,用户批准或拒绝后消解。
+_Avoid_: 配对弹窗
+
+**Clipboard Request**:
+剪贴板监听识别到链接后,询问用户是否接管的 Request。新识别的链接替换未决的旧请求。
+_Avoid_: 剪贴板弹窗
+
+**Task Popup**:
+新建任务第一次开始下载时弹出、显示其进度的 Popup,拥有自己的任务栏按钮,可最小化。任务完成或失败时,由不自动关闭的结果提示原地取代。从弹出到用户关闭 Task Popup 或结果提示之前,该任务是被跟踪的任务,它完成时不另发 Notice。
+_Avoid_: 进度窗口、progress dialog、下载弹窗
**Pair Token**:
Browser Service 与浏览器扩展共享的连接凭证,Pairing 的产物。
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.py
index a3689983..3820b55b 100644
--- a/Ghost-Downloader-3.py
+++ b/Ghost-Downloader-3.py
@@ -11,7 +11,7 @@ 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.models.task import Task, TaskError, TaskOptions
from app.platform.application import Application
from app.platform.instance import PrimaryInstance
from app.services.browser_service import PairRequest
@@ -217,14 +217,11 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilen
if sys.platform != "darwin":
signalBus.activationRequested.connect(show)
signalBus.exceptionCaught.connect(lambda msg: show().onExceptionCaught(msg))
- browserService.pairRequestChanged.connect(lambda request: request and show().onPairRequested(request))
engine.browserListener.stateChanged.connect(
lambda state: state.status == ListenStatus.FAILED and show().onBrowserListenFailed(state.error))
engine.aria2RpcListener.stateChanged.connect(
lambda state: state.status == ListenStatus.FAILED and show().onAria2ListenFailed(state.error))
- application.clipboardListener.urlsDetected.connect(lambda urls: show().addUrls(urls))
-
if sys.platform == "darwin":
from app.view.shell.mac_status_item import MacStatusItem
from app.view.shell.dock import setupDock
@@ -246,27 +243,83 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilen
taskService.tasksAllCompleted.connect(release)
from app.platform.desktop_notification import (
- PopupNotifier, SystemNotifier, buildDiskSpaceInsufficient, buildParseFailed, buildTaskCompleted,
- createPresence, toFileIcon,
+ NotificationPopup, PopupNotifier, PopupStack, SystemNotifier, buildClipboardRequest,
+ buildDiskSpaceInsufficient, buildPairRequest, buildParseFailed, buildTaskCompleted, buildTaskFailed, createPresence,
+ toFileIcon,
)
systemNotifier = SystemNotifier(coroutineRunner.submit)
sendTo = {NoticeStyle.SYSTEM: systemNotifier.send, NoticeStyle.OFF: lambda _: None}
+ popupStack: PopupStack | None = None
if NoticeStyle.POPUP in cfg.noticeStyle.options:
presence = createPresence()
- popupNotifier = PopupNotifier(presence)
- sendTo[NoticeStyle.POPUP] = popupNotifier.send
+ popupStack = PopupStack(presence)
+ sendTo[NoticeStyle.POPUP] = PopupNotifier(popupStack).send
# 先于 onAboutToQuit 连接,engine.stop() 期间再来的 Notice 会被忽略
application.aboutToQuit.connect(presence.close)
- application.aboutToQuit.connect(popupNotifier.clear)
+ application.aboutToQuit.connect(popupStack.clear)
+
+ def canShowRequestPopup() -> bool:
+ return popupStack is not None and (window is None or not window.isVisible() or window.isMinimized())
+
+ clipboardPopup: NotificationPopup | None = None
+ pairPopup: NotificationPopup | None = None
+
+ def onUrlsDetected(urls: list[str]) -> None:
+ nonlocal clipboardPopup
+ if not canShowRequestPopup():
+ show().addUrls(urls)
+ return
+ if not presence.canInterrupt():
+ return
+ popup = NotificationPopup(buildClipboardRequest(urls, lambda: show().addUrls(urls)))
+ popupStack.add(popup, replacing=clipboardPopup)
+ clipboardPopup = popup
+
+ def onPairRequestChanged(request: PairRequest | None) -> None:
+ nonlocal pairPopup
+ if pairPopup is not None:
+ pairPopup.exit(isDismissed=False)
+ pairPopup = None
+ if request is None:
+ return
+ if not canShowRequestPopup():
+ show().onPairRequested(request)
+ return
+ pairPopup = NotificationPopup(buildPairRequest(
+ request, lambda: browserService.approvePair(request.requestId),
+ lambda: browserService.rejectPair(request.requestId)))
+ popupStack.add(pairPopup)
+
+ application.clipboardListener.urlsDetected.connect(onUrlsDetected)
+ browserService.pairRequestChanged.connect(onPairRequestChanged)
activate = signalBus.activationRequested.emit
+ def toNotice(notification: Notification) -> Notification:
+ return notification if cfg.isNoticeSoundEnabled.value else replace(notification, sound=None)
+
def sendNotice(notification: Notification) -> None:
- if not cfg.isNoticeSoundEnabled.value:
- notification = replace(notification, sound=None)
- sendTo[cfg.noticeStyle.value](notification)
+ sendTo[cfg.noticeStyle.value](toNotice(notification))
+
+ from app.models.task import TaskStatus
+
+ def buildTaskResult(task: Task) -> Notification:
+ if task.status == TaskStatus.COMPLETED:
+ return toNotice(replace(buildTaskCompleted(task, toFileIcon(task.outputPath)), timeout=0))
+ return buildTaskFailed(task, activate)
+
+ taskTracker = None
+ if popupStack is not None:
+ from app.view.shell.task_popup import TaskTracker
+ taskTracker = TaskTracker(
+ taskService, popupStack,
+ lambda: cfg.noticeStyle.value == NoticeStyle.POPUP and cfg.isTaskPopupEnabled.value, buildTaskResult)
+ application.taskTracker = taskTracker
+
+ def onTaskCompleted(task: Task) -> None:
+ if taskTracker is None or not taskTracker.isTracking(task.taskId):
+ sendNotice(buildTaskCompleted(task, toFileIcon(task.outputPath)))
- taskService.taskCompleted.connect(
- lambda task: sendNotice(buildTaskCompleted(task, toFileIcon(task.outputPath))))
+ taskService.taskCompleted.connect(onTaskCompleted)
taskService.diskSpaceInsufficient.connect(
lambda free, needed: sendNotice(buildDiskSpaceInsufficient(free, needed, activate)))
engine.aria2RpcService.parseFailed.connect(lambda url, error: sendNotice(buildParseFailed(url, error, activate)))
diff --git a/app/config/cfg.py b/app/config/cfg.py
index 4d4be12c..39d49e9c 100644
--- a/app/config/cfg.py
+++ b/app/config/cfg.py
@@ -395,6 +395,7 @@ class Config(QConfig):
EnumSerializer(NoticeStyle),
)
isNoticeSoundEnabled = ConfigItem("Notice", "SoundEnabled", True, BoolValidator())
+ isTaskPopupEnabled = ConfigItem("Notice", "TaskPopupEnabled", False, BoolValidator())
clipboardIgnoredPacks: ConfigItem[list[str]] = ConfigItem("Software", "ClipboardIgnoredPacks", [], StringListValidator())
geometry = ConfigItem(
"Software", "Geometry", (0, 0, 0, 0), serializer=GeometrySerializer(),
diff --git a/app/platform/application.py b/app/platform/application.py
index a89e4462..df646a5e 100644
--- a/app/platform/application.py
+++ b/app/platform/application.py
@@ -17,6 +17,7 @@ if TYPE_CHECKING:
from app.view.dialogs.name_conflict import NameConflictPrompt
from app.view.shell.clipboard_listener import ClipboardListener
from app.view.shell.mac_status_item import MacStatusItem
+ from app.view.shell.task_popup import TaskTracker
class Application(QApplication):
@@ -33,6 +34,7 @@ class Application(QApplication):
self.clipboardListener: ClipboardListener | None = None
self.nameConflictPrompt: NameConflictPrompt | None = None
self.statusItem: MacStatusItem | None = None
+ self.taskTracker: TaskTracker | None = None
signal(SIGINT, self._onInterrupt)
def event(self, e: QEvent) -> bool:
diff --git a/app/platform/desktop_notification.py b/app/platform/desktop_notification.py
index b8521014..4843b4d0 100644
--- a/app/platform/desktop_notification.py
+++ b/app/platform/desktop_notification.py
@@ -13,10 +13,10 @@ from typing import TYPE_CHECKING
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,
+ QCoreApplication, QEasingCurve, QEvent, QFileInfo, QPoint, QPointF, QPropertyAnimation, QRectF,
QResource, QStandardPaths, Qt, QTimer, Signal as QtSignal,
)
-from PySide6.QtGui import QColor, QGuiApplication, QPainter, QPixmap, QScreen
+from PySide6.QtGui import QColor, QCursor, QGuiApplication, QPainter, QPixmap, QScreen
from PySide6.QtWidgets import QFileIconProvider, QHBoxLayout, QLabel, QSizePolicy, QVBoxLayout, QWidget
from qfluentwidgets import (
BodyLabel, CaptionLabel, FluentIcon, IconWidget, InfoBarIcon, PushButton, StrongBodyLabel,
@@ -24,6 +24,7 @@ from qfluentwidgets import (
)
from app.platform.desktop import openFile, revealInFolder
+from app.platform.taskbar import addTaskbarButton
from app.platform.windows import isGreaterEqualWin11
from app.signal import Signal
@@ -31,6 +32,7 @@ if TYPE_CHECKING:
from collections.abc import Coroutine
from app.models.task import Task, TaskError
+ from app.services.browser_service import PairRequest
APP_NAME = "Ghost Downloader"
LOGO_RESOURCE = ":/image/logo.png"
@@ -43,6 +45,7 @@ SCREEN_MARGIN = 12
SPACING = 8
ICON_SPACING = 12
FILE_ICON_SIZE = 48
+TEXT_WIDTH = WIDTH - 2 * PADDING - FILE_ICON_SIZE - ICON_SPACING
STATUS_ICON_SIZE = 32
CORNER_RADIUS = 8
DEFAULT_DURATION = 5
@@ -122,6 +125,50 @@ def buildParseFailed(url: str, error: TaskError, activate: Callable[[], None]) -
)
+def buildTaskFailed(task: Task, activate: Callable[[], None]) -> Notification:
+ from app.i18n import toLocalizedError
+
+ error = toLocalizedError(task.lastError) if task.lastError else ""
+ return Notification(
+ title=QCoreApplication.translate("Notifications", "下载失败"),
+ message=f"{task.name}\n{error}",
+ urgency=Urgency.Critical,
+ on_clicked=activate,
+ timeout=0,
+ )
+
+
+def buildClipboardRequest(urls: list[str], accept: Callable[[], None]) -> Notification:
+ message = urls[0]
+ if len(urls) > 1:
+ message += "\n" + QCoreApplication.translate("Notifications", "等 {0} 个链接").format(len(urls))
+ return Notification(
+ title=QCoreApplication.translate("Notifications", "检测到下载链接"),
+ message=message,
+ buttons=(Button(title=QCoreApplication.translate("Notifications", "下载"), on_pressed=accept),),
+ on_clicked=accept,
+ )
+
+
+def buildPairRequest(request: PairRequest, approve: Callable[[], None], reject: Callable[[], None]) -> Notification:
+ client = request.clientKind or QCoreApplication.translate("Notifications", "浏览器扩展")
+ version = request.extensionVersion or QCoreApplication.translate("Notifications", "未知")
+ return Notification(
+ title=QCoreApplication.translate("Notifications", "浏览器扩展配对请求"),
+ message="\n".join((
+ QCoreApplication.translate("Notifications", "{0} {1} 请求连接").format(client, version),
+ QCoreApplication.translate("Notifications", "来源: {0}").format(request.peerAddress),
+ QCoreApplication.translate("Notifications", "仅在你刚刚点击扩展里的\"自动配对\"时允许"),
+ )),
+ buttons=(
+ Button(title=QCoreApplication.translate("Notifications", "允许配对"), on_pressed=approve),
+ Button(title=QCoreApplication.translate("Notifications", "拒绝"), on_pressed=reject),
+ ),
+ on_dismissed=reject,
+ timeout=0,
+ )
+
+
class SystemNotifier:
def __init__(self, submit: Callable[[Coroutine], object]):
self._submit = submit
@@ -282,26 +329,28 @@ def createPresence() -> Presence:
class Popup(QWidget):
exited = QtSignal()
+ dismissed = QtSignal()
+ clicked = QtSignal()
+ layoutChanged = QtSignal()
+ hasTaskbarButton = False
- def __init__(self, notification: Notification):
+ def __init__(self):
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.duration = 0
+ self.hasSound = False
self.isExiting = False
self._isHovered = False
self._targetPos = QPoint()
self._pressX: float | None = None
- self._initWidget()
- self._initLayout()
- self._bind()
+
+ @property
+ def isLongLived(self) -> bool:
+ return self.duration == 0
def _initWidget(self) -> None:
- self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Tool
- | Qt.WindowType.WindowStaysOnTopHint | Qt.WindowType.WindowDoesNotAcceptFocus)
+ flags = (Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint
+ | Qt.WindowType.WindowDoesNotAcceptFocus)
+ self.setWindowFlags(flags if self.hasTaskbarButton else flags | Qt.WindowType.Tool)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setAttribute(Qt.WidgetAttribute.WA_X11DoNotAcceptFocus)
self._isAcrylic = isGreaterEqualWin11()
@@ -311,6 +360,8 @@ class Popup(QWidget):
self.windowEffect = None
if sys.platform == "win32":
from qframelesswindow import WindowEffect
+ if self.hasTaskbarButton:
+ addTaskbarButton(int(self.winId()))
self.windowEffect = WindowEffect(self)
if self._isAcrylic:
self._applyAcrylic()
@@ -323,94 +374,44 @@ class Popup(QWidget):
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.closeButton = self._createHeaderButton(FluentIcon.CLOSE)
+ self.headerButtons = [self.closeButton]
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()
+ self.headerLayout = QHBoxLayout()
+ self.headerLayout.setContentsMargins(0, 0, 0, 0)
+ self.headerLayout.setSpacing(SPACING)
+ self.headerLayout.addWidget(self.logoLabel)
+ self.headerLayout.addWidget(self.appNameLabel)
+ self.headerLayout.addStretch(1)
+ for button in self.headerButtons:
+ self.headerLayout.addWidget(button)
+
+ self.vBoxLayout = QVBoxLayout(self)
+ self.vBoxLayout.setContentsMargins(PADDING, PADDING // 2, PADDING // 2, PADDING)
+ self.vBoxLayout.setSpacing(SPACING)
+ self.vBoxLayout.addLayout(self.headerLayout)
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 _createHeaderButton(self, icon: FluentIcon) -> TransparentToolButton:
+ button = TransparentToolButton(icon, self)
+ button.setFixedSize(32, 32)
+ button.setIconSize(button.iconSize() * 0.75)
+ policy = button.sizePolicy()
+ policy.setRetainSizeWhenHidden(True)
+ button.setSizePolicy(policy)
+ button.hide()
+ return button
+
def _toPixmap(self, pixmap: QPixmap, size: int) -> QPixmap:
ratio = self.devicePixelRatioF()
scaled = pixmap.scaled(round(size * ratio), round(size * ratio),
@@ -430,27 +431,34 @@ class Popup(QWidget):
elif isMoved and self._pressX is None:
self._animate(pos, MOVE_DURATION, MOVE_CURVE)
+ def showAt(self, pos: QPoint) -> None:
+ self._targetPos = pos
+ self.move(pos)
+ self.show()
+ self._setHovered(self.geometry().contains(QCursor.pos()))
+ self._restartTimer()
+
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()
+ if isDismissed:
+ self.dismissed.emit()
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":
+ isAnimated = not self.isMinimized()
+ if isAnimated and 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)
+ QTimer.singleShot(0, self, self._onMoveAnimationFinished)
return
self.moveAnimation.setDuration(duration)
self.moveAnimation.setEasingCurve(curve)
@@ -459,13 +467,8 @@ class Popup(QWidget):
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)
+ if self.duration > 0 and not self._isHovered and not self.isExiting:
+ self.closeTimer.start(self.duration * 1000)
def _onMoveAnimationFinished(self) -> None:
if self.isExiting:
@@ -479,7 +482,16 @@ class Popup(QWidget):
if self._isAcrylic:
self.windowEffect.setAcrylicEffect(self.winId(), "20202030" if isDarkTheme() else "FFFFFF30")
+ def changeEvent(self, event) -> None:
+ if event.type() == QEvent.Type.WindowStateChange:
+ self.layoutChanged.emit()
+ super().changeEvent(event)
+
def closeEvent(self, event) -> None:
+ if event.spontaneous():
+ event.ignore()
+ self.exit(isDismissed=True)
+ return
self.closeTimer.stop()
self.moveAnimation.stop()
super().closeEvent(event)
@@ -501,18 +513,22 @@ class Popup(QWidget):
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()
+ def _setHovered(self, isHovered: bool) -> None:
+ self._isHovered = isHovered
+ for button in self.headerButtons:
+ button.setVisible(isHovered)
self.update()
+ if isHovered:
+ self.closeTimer.stop()
+ else:
+ self._restartTimer()
+
+ def enterEvent(self, event) -> None:
+ self._setHovered(True)
super().enterEvent(event)
def leaveEvent(self, event) -> None:
- self._isHovered = False
- self.closeButton.hide()
- self.update()
- self._restartTimer()
+ self._setHovered(False)
super().leaveEvent(event)
def mousePressEvent(self, event) -> None:
@@ -528,27 +544,113 @@ class Popup(QWidget):
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event) -> None:
+ super().mouseReleaseEvent(event)
if event.button() != Qt.MouseButton.LeftButton or self._pressX is None:
- return super().mouseReleaseEvent(event)
+ return
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)
+ else:
+ self.clicked.emit()
-class PopupNotifier:
+class NotificationPopup(Popup):
+ 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.hasSound = notification.sound is not None
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+
+ def _initWidget(self) -> None:
+ super()._initWidget()
+ 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))
+
+ 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, TEXT_WIDTH))
+ 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, TEXT_WIDTH))
+ 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))
+
+ def _initLayout(self) -> None:
+ super()._initLayout()
+ 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)
+ self.vBoxLayout.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)
+ self.vBoxLayout.addLayout(buttons)
+ self.adjustSize()
+
+ def _bind(self) -> None:
+ super()._bind()
+ for pushButton, button in self.buttons:
+ pushButton.clicked.connect(lambda _=False, b=button: self._onActivated(b.on_pressed))
+ if onClicked := self._notification.on_clicked:
+ self.clicked.connect(lambda: self._onActivated(onClicked))
+ if onDismissed := self._notification.on_dismissed:
+ self.dismissed.connect(lambda: QTimer.singleShot(0, onDismissed))
+
+ def _onActivated(self, callback: Callable[[], None] | None) -> None:
+ self.exit(isDismissed=False)
+ if callback:
+ QTimer.singleShot(0, callback)
+
+
+class PopupStack:
"""只能在 Qt 主线程调用。"""
def __init__(self, presence: Presence):
self._presence = presence
self._popups: list[Popup] = [] # 最早的在前;没有 parent 的窗口靠这里的引用存活
- self._pending: deque[Notification] = deque()
+ self._pending: deque[Popup] = deque()
self._lastSoundAt = float("-inf")
self._isClosed = False
presence.changed.connect(self._showPending)
@@ -558,35 +660,48 @@ class PopupNotifier:
for screen in application.screens():
self._onScreenAdded(screen)
- def send(self, notification: Notification) -> None:
+ def add(self, popup: Popup, replacing: Popup | None = None) -> None:
if self._isClosed:
+ popup.deleteLater()
+ return
+ popup.exited.connect(lambda: self._remove(popup))
+ popup.layoutChanged.connect(self._arrange)
+ if replacing in self._pending:
+ self._pending[self._pending.index(replacing)] = popup
+ self._close(replacing)
return
- self._pending.append(notification)
+ if replacing in self._popups and not replacing.isExiting:
+ self._popups[self._popups.index(replacing)] = popup
+ if replacing.isVisible() and not replacing.isMinimized():
+ popup.showAt(replacing.pos())
+ self._close(replacing)
+ self._playSound(popup)
+ self._arrange()
+ return
+ self._pending.append(popup)
self._showPending()
def clear(self) -> None:
- """立即关闭全部 Popup,不触发 on_dismissed;之后的 send 一律忽略。"""
+ """立即关闭全部 Popup,不触发 on_dismissed;之后的 add 一律忽略。"""
self._isClosed = True
+ for popup in [*self._pending, *self._popups]:
+ self._close(popup)
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))
+ popup = self._pending.popleft()
self._popups.append(popup)
- if notification.sound and time.monotonic() - self._lastSoundAt >= SOUND_INTERVAL:
- self._lastSoundAt = time.monotonic()
- self._playSound()
+ self._playSound(popup)
self._arrange()
- def _playSound(self) -> None:
+ def _playSound(self, popup: Popup) -> None:
+ if not popup.hasSound or time.monotonic() - self._lastSoundAt < SOUND_INTERVAL:
+ return
+ self._lastSoundAt = time.monotonic()
path = str(extractResource(SOUND_RESOURCE))
if sys.platform == "win32":
import winsound
@@ -608,10 +723,12 @@ class PopupNotifier:
right = area.x() + area.width() - SCREEN_MARGIN
bottom = area.y() + area.height() - SCREEN_MARGIN
top = area.y() + SCREEN_MARGIN
+ shown = [p for p in self._popups if not p.isExiting and not p.isMinimized()]
isFull = False
- for popup in reversed([p for p in self._popups if not p.isExiting]):
+ for popup in [*reversed([p for p in shown if p.isLongLived]),
+ *reversed([p for p in shown if not p.isLongLived])]:
y = bottom - popup.height()
- if isFull or y < top:
+ if not popup.isLongLived and (isFull or y < top):
isFull = True
popup.exit(isDismissed=True)
continue
@@ -622,9 +739,13 @@ class PopupNotifier:
if popup not in self._popups:
return
self._popups.remove(popup)
+ self._close(popup)
+ self._arrange()
+
+ def _close(self, popup: Popup) -> None:
+ popup.isExiting = True
popup.close()
popup.deleteLater()
- self._arrange()
def _onScreenAdded(self, screen: QScreen) -> None:
# 每块屏只在加入时连一次,副屏变化时多排一次无害
@@ -633,3 +754,11 @@ class PopupNotifier:
def _onPrimaryScreenChanged(self, _screen: QScreen | None) -> None:
self._arrange()
self._showPending()
+
+
+class PopupNotifier:
+ def __init__(self, stack: PopupStack):
+ self._stack = stack
+
+ def send(self, notification: Notification) -> None:
+ self._stack.add(NotificationPopup(notification))
diff --git a/app/platform/taskbar.py b/app/platform/taskbar.py
index 131356d1..78a342d6 100644
--- a/app/platform/taskbar.py
+++ b/app/platform/taskbar.py
@@ -1,20 +1,38 @@
from __future__ import annotations
from functools import cache, partial
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+ from app.models.task import TaskStatus
+
+
+def setWindowsProgress(hwnd: int, status: TaskStatus | None, progress: float | None) -> None:
+ from app.models.task import TaskStatus
-def setWindowsProgress(hwnd: int, isRunning: bool, progress: float | None) -> None:
taskbarList = createTaskbarList()
if taskbarList is None:
return
setState, setValue = taskbarList
- if not isRunning:
- setState(hwnd, 0) # TBPF_NOPROGRESS
- elif progress is None:
- setState(hwnd, 1) # TBPF_INDETERMINATE
+ TBPF_NOPROGRESS, TBPF_INDETERMINATE, TBPF_NORMAL, TBPF_ERROR, TBPF_PAUSED = 0, 1, 2, 4, 8
+ colors = {TaskStatus.PAUSED: TBPF_PAUSED, TaskStatus.FAILED: TBPF_ERROR}
+ if status is None or status == TaskStatus.COMPLETED:
+ setState(hwnd, TBPF_NOPROGRESS)
+ elif progress is None and status not in colors:
+ setState(hwnd, TBPF_INDETERMINATE)
else:
- setState(hwnd, 2) # TBPF_NORMAL
- setValue(hwnd, round(progress * 10), 1000)
+ setState(hwnd, colors.get(status, TBPF_NORMAL))
+ setValue(hwnd, round((100 if progress is None else progress) * 10), 1000)
+
+
+def addTaskbarButton(hwnd: int) -> None:
+ import ctypes
+
+ GWL_STYLE, GWL_EXSTYLE = -16, -20
+ WS_MINIMIZEBOX, WS_SYSMENU, WS_EX_APPWINDOW = 0x00020000, 0x00080000, 0x00040000
+ user32 = ctypes.windll.user32
+ user32.SetWindowLongPtrW(hwnd, GWL_EXSTYLE, user32.GetWindowLongPtrW(hwnd, GWL_EXSTYLE) | WS_EX_APPWINDOW)
+ user32.SetWindowLongPtrW(hwnd, GWL_STYLE, user32.GetWindowLongPtrW(hwnd, GWL_STYLE) | WS_MINIMIZEBOX | WS_SYSMENU)
@cache
diff --git a/app/view/pages/setting_page.py b/app/view/pages/setting_page.py
index 922988df..880f0278 100644
--- a/app/view/pages/setting_page.py
+++ b/app/view/pages/setting_page.py
@@ -312,6 +312,13 @@ class SettingPage(QWidget):
self.tr("当前为用户模式,数据保存在: {0}").format(APP_DATA_DIR),
)
+ self.taskPopupCard = SwitchSettingCard(
+ FluentIcon.SPEED_HIGH, self.tr("新建任务时显示下载进度"),
+ self.tr("在屏幕右下角显示进度,可最小化到任务栏;需要通知方式为弹窗"),
+ cfg.isTaskPopupEnabled,
+ )
+ self.taskPopupCard.setEnabled(cfg.noticeStyle.value == NoticeStyle.POPUP)
+
self.commandLineToolCard = PushSettingCard(
"", FluentIcon.COMMAND_PROMPT, self.tr("命令行工具"),
self.tr("安装后可在终端中使用 ghd 命令添加和管理任务"),
@@ -334,6 +341,7 @@ class SettingPage(QWidget):
),
SwitchSettingCard(FluentIcon.VOLUME, self.tr("通知提示音"),
self.tr("下载完成时播放提示音"), cfg.isNoticeSoundEnabled),
+ *([self.taskPopupCard] if NoticeStyle.POPUP in cfg.noticeStyle.options else []),
ClipboardSettingCard(self._featureService.packs),
]
if sys.platform != "darwin":
@@ -399,6 +407,7 @@ class SettingPage(QWidget):
self._aria2RpcListener.stateChanged.connect(self._refreshAria2Status, owner=self)
if sys.platform == "darwin":
cfg.shouldShowDockIcon.valueChanged.connect(self.showDockSpeedCard.setEnabled)
+ cfg.noticeStyle.valueChanged.connect(lambda style: self.taskPopupCard.setEnabled(style == NoticeStyle.POPUP))
self.downloadFolderPicker.pathChanged.connect(self._onDownloadFolderChanged)
cfg.downloadFolder.valueChanged.connect(self.downloadFolderPicker.setPath)
diff --git a/app/view/shell/task_popup.py b/app/view/shell/task_popup.py
new file mode 100644
index 00000000..e45e2b1c
--- /dev/null
+++ b/app/view/shell/task_popup.py
@@ -0,0 +1,194 @@
+from __future__ import annotations
+
+import sys
+from collections.abc import Callable
+from typing import TYPE_CHECKING
+
+from PySide6.QtCore import QFileInfo, Qt, QTimer
+from PySide6.QtGui import QColor
+from PySide6.QtWidgets import QFileIconProvider, QHBoxLayout, QLabel, QSizePolicy, QVBoxLayout
+from qfluentwidgets import (
+ BodyLabel, CaptionLabel, FluentIcon, IndeterminateProgressBar, ProgressBar, PushButton, StrongBodyLabel,
+)
+
+from app.format import toReadableSize
+from app.models.task import SpecialFileSize, TaskStatus
+from app.platform.desktop_notification import (
+ FILE_ICON_SIZE, ICON_SPACING, PADDING, SPACING, TEXT_WIDTH, NotificationPopup, Popup, PopupStack,
+)
+from app.view.cards.task_cards import toEtaText, toSizeText
+
+if TYPE_CHECKING:
+ from desktop_notifier.common import Notification
+
+ from app.models.task import Task
+ from app.services.task_service import TaskService
+
+MAX_TASK_POPUPS = 3
+
+
+class TaskPopup(Popup):
+ hasTaskbarButton = True
+
+ def __init__(self, task: Task, start: Callable[[Task], None], pause: Callable[[Task], None],
+ delete: Callable[[Task], None]):
+ super().__init__()
+ self._task = task
+ self._start = start
+ self._pause = pause
+ self._delete = delete
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+ self.refresh()
+ self.refreshTimer.start()
+
+ def _initWidget(self) -> None:
+ super()._initWidget()
+ self.setWindowTitle(self._task.name)
+ self.minimizeButton = self._createHeaderButton(FluentIcon.MINIMIZE)
+ self.headerButtons.insert(0, self.minimizeButton)
+
+ self.iconLabel = QLabel(self)
+ self.iconLabel.setPixmap(self._toPixmap(
+ QFileIconProvider().icon(QFileInfo(self._task.outputPath)).pixmap(FILE_ICON_SIZE, FILE_ICON_SIZE),
+ FILE_ICON_SIZE))
+ self.nameLabel = StrongBodyLabel(self)
+ self.nameLabel.setText(self.nameLabel.fontMetrics().elidedText(
+ self._task.name, Qt.TextElideMode.ElideMiddle, TEXT_WIDTH))
+ self.nameLabel.setToolTip(self._task.name)
+ self.statusLabel = BodyLabel(self)
+ self.sizeLabel = CaptionLabel(self)
+ self.sizeLabel.setTextColor(QColor(0, 0, 0, 155), QColor(255, 255, 255, 155))
+ if self._task.fileSize in {SpecialFileSize.UNKNOWN, SpecialFileSize.NOT_SUPPORTED}:
+ self.progressBar = IndeterminateProgressBar(self)
+ else:
+ self.progressBar = ProgressBar(self)
+ self.toggleButton = PushButton(self)
+ self.cancelButton = PushButton(self.tr("取消"), self)
+ for button in (self.toggleButton, self.cancelButton):
+ button.setFixedHeight(32)
+ button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
+
+ self.refreshTimer = QTimer(self)
+ self.refreshTimer.setInterval(1000)
+
+ def _initLayout(self) -> None:
+ super()._initLayout()
+ texts = QVBoxLayout()
+ texts.setContentsMargins(0, 0, 0, 0)
+ texts.setSpacing(2)
+ texts.addWidget(self.nameLabel)
+ texts.addWidget(self.statusLabel)
+ texts.addWidget(self.sizeLabel)
+
+ content = QHBoxLayout()
+ content.setContentsMargins(0, 0, PADDING // 2, 0)
+ content.setSpacing(ICON_SPACING)
+ content.addWidget(self.iconLabel, 0, Qt.AlignmentFlag.AlignTop)
+ content.addLayout(texts, 1)
+ self.vBoxLayout.addLayout(content)
+
+ bottom = QVBoxLayout()
+ bottom.setContentsMargins(0, SPACING, PADDING // 2, 0)
+ bottom.setSpacing(SPACING * 2)
+ bottom.addWidget(self.progressBar)
+ buttons = QHBoxLayout()
+ buttons.setContentsMargins(0, 0, 0, 0)
+ buttons.setSpacing(SPACING)
+ buttons.addWidget(self.toggleButton)
+ buttons.addWidget(self.cancelButton)
+ bottom.addLayout(buttons)
+ self.vBoxLayout.addLayout(bottom)
+ self.adjustSize()
+
+ def _bind(self) -> None:
+ super()._bind()
+ self.minimizeButton.clicked.connect(self.showMinimized)
+ self.toggleButton.clicked.connect(self._onToggleClicked)
+ self.cancelButton.clicked.connect(lambda: self._delete(self._task))
+ self.refreshTimer.timeout.connect(self.refresh)
+
+ def refresh(self) -> None:
+ task = self._task
+ progress, speed, received = task.currentSnapshot()
+ if task.status == TaskStatus.RUNNING:
+ self.statusLabel.setText(f"{toReadableSize(speed)}/s · {toEtaText(task, speed, received)}")
+ elif task.status == TaskStatus.PAUSED:
+ self.statusLabel.setText(self.tr("任务已经暂停"))
+ else:
+ self.statusLabel.setText(self.tr("任务正在等待"))
+ self.sizeLabel.setText(toSizeText(task, speed, received) or "")
+
+ isPaused = task.status == TaskStatus.PAUSED
+ if isinstance(self.progressBar, ProgressBar):
+ self.progressBar.setValue(int(progress))
+ if isPaused:
+ self.progressBar.pause()
+ else:
+ self.progressBar.resume()
+ self.toggleButton.setText(self.tr("继续") if isPaused else self.tr("暂停"))
+ self.toggleButton.setEnabled(isPaused or task.canPause)
+
+ if sys.platform == "win32":
+ from app.platform.taskbar import setWindowsProgress
+ isKnown = isinstance(self.progressBar, ProgressBar)
+ setWindowsProgress(int(self.winId()), task.status, progress if isKnown else None)
+
+ def _onToggleClicked(self) -> None:
+ if self._task.status == TaskStatus.PAUSED:
+ self._start(self._task)
+ else:
+ self._pause(self._task)
+ self.refresh()
+
+
+class TaskTracker:
+ """在 TaskService.resumeSaved 之后创建,使 Saved Tasks 不显示 Task Popup。"""
+
+ def __init__(self, taskService: TaskService, stack: PopupStack, isEnabled: Callable[[], bool],
+ buildResult: Callable[[Task], Notification]):
+ self._taskService = taskService
+ self._stack = stack
+ self._isEnabled = isEnabled
+ self._buildResult = buildResult
+ self._candidateIds: set[str] = set()
+ self._popups: dict[str, Popup] = {}
+ taskService.taskAdded.connect(self._onTaskAdded)
+ taskService.taskStarted.connect(self._onTaskStarted)
+ taskService.taskCompleted.connect(self._onTaskEnded)
+ taskService.taskFailed.connect(self._onTaskEnded)
+ taskService.taskRemoved.connect(self._onTaskRemoved)
+
+ def isTracking(self, taskId: str) -> bool:
+ return taskId in self._popups
+
+ def _track(self, taskId: str, popup: Popup, replacing: Popup | None = None) -> None:
+ self._popups[taskId] = popup
+ popup.exited.connect(lambda: self._untrack(taskId, popup))
+ self._stack.add(popup, replacing)
+
+ def _untrack(self, taskId: str, popup: Popup) -> None:
+ if self._popups.get(taskId) is popup:
+ del self._popups[taskId]
+
+ def _onTaskAdded(self, task: Task) -> None:
+ self._candidateIds.add(task.taskId)
+
+ def _onTaskStarted(self, task: Task) -> None:
+ if task.taskId not in self._candidateIds:
+ return
+ self._candidateIds.discard(task.taskId)
+ if self._isEnabled() and len(self._popups) < MAX_TASK_POPUPS:
+ self._track(task.taskId, TaskPopup(
+ task, self._taskService.start, self._taskService.pause,
+ lambda t: self._taskService.delete(t, shouldDeleteFiles=True)))
+
+ def _onTaskEnded(self, task: Task) -> None:
+ if (popup := self._popups.get(task.taskId)) is not None:
+ self._track(task.taskId, NotificationPopup(self._buildResult(task)), replacing=popup)
+
+ def _onTaskRemoved(self, taskId: str) -> None:
+ self._candidateIds.discard(taskId)
+ if (popup := self._popups.pop(taskId, None)) is not None:
+ popup.exit(isDismissed=False)
diff --git a/app/view/windows/main_window.py b/app/view/windows/main_window.py
index 21d053e9..5fa5cabd 100644
--- a/app/view/windows/main_window.py
+++ b/app/view/windows/main_window.py
@@ -22,7 +22,7 @@ from app.config.paths import APP_DATA_DIR
from app.platform.desktop import raiseWindow, revealInFolder
from app.services.task_draft import TaskDraft
from app.i18n import toLocalizedError
-from app.models.task import TaskError, TaskOptions
+from app.models.task import TaskError, TaskOptions, TaskStatus
from app.services.port_listener import PortListener
from app.signal_bus import signalBus
from app.services.update_service import UpdateState
@@ -461,8 +461,8 @@ class MainWindow(MSFluentWindow):
def _onSpeedChanged(self, _speed: int) -> None:
from app.platform.taskbar import setWindowsProgress
- setWindowsProgress(int(self.winId()), self._taskService.runningCount() > 0,
- self._taskService.overallProgress())
+ status = TaskStatus.RUNNING if self._taskService.runningCount() > 0 else None
+ setWindowsProgress(int(self.winId()), status, self._taskService.overallProgress())
def _onCloseClicked(self) -> None:
for dialog in self.findChildren(MaskDialogBase):
diff --git a/docs/adr/0032-task-popup-owns-taskbar-button.md b/docs/adr/0032-task-popup-owns-taskbar-button.md
new file mode 100644
index 00000000..0d2b4e0d
--- /dev/null
+++ b/docs/adr/0032-task-popup-owns-taskbar-button.md
@@ -0,0 +1,20 @@
+# Task Popup 拥有自己的任务栏按钮
+
+用户要在任务栏上看到下载进度,并能把进度卡片最小化(#960、#1089);主窗口在后台运行时被隐藏,任务栏上没有按钮可画进度。所以 Task Popup 不用 Notice 卡片的 `Qt.Tool`,在 Windows 上显式加 `WS_EX_APPWINDOW` 和 `WS_MINIMIZEBOX`,用 `ITaskbarList3` 在自己的按钮上画本任务进度。Notice 和 Request 仍是 `Tool` 窗口,不占任务栏。
+
+实测(Win11 26200,任务栏分开显示):只去掉 `Tool` 不出按钮,因为 `WindowDoesNotAcceptFocus` 对应的 `WS_EX_NOACTIVATE` 会隐藏按钮;加 `WS_EX_APPWINDOW` 后按钮出现、进度正常,显示时不抢焦点;有 `WS_MINIMIZEBOX` 时点按钮可以最小化和还原。
+
+## Considered Options
+
+- **独立进度窗口**(IDM 式):与 Popup 形成两套外观,且普通窗口弹出会抢走浏览器里的焦点。
+- **下载期间主窗口最小化代替隐藏**:改变"关闭即消失"的既有行为,且只能显示汇总进度。
+- **托盘图标画进度环**:Win11 默认把托盘图标收进溢出区,多数用户看不到。
+
+## Consequences
+
+- Task Popup 出现在 Alt+Tab 中。
+- 从任务栏关闭(右键菜单、缩略图 ×)等同于点卡片上的关闭。
+- 最小化的 Task Popup 退出右下角堆叠,还原时重新插入。
+- 任务结束后 Task Popup 被普通 Popup 形式的结果提示取代,任务栏按钮随之消失;最小化中的任务完成时,结果提示直接出现在右下角,不闪烁任务栏按钮。
+- Linux 只有应用级的 LauncherEntry 进度,Task Popup 有按钮但无单任务进度;macOS 和 Wayland 不显示 Popup。
+- 任务栏"合并"显示时合并按钮显示谁的进度、Win10 上的表现,均未实测。
diff --git a/tests/test_android.py b/tests/test_android.py
index f4af3294..fcfd5b4a 100644
--- a/tests/test_android.py
+++ b/tests/test_android.py
@@ -27,6 +27,7 @@ DESKTOP_ONLY = {
("GeneralDownload", "RecentFolders"),
("Notice", "SoundEnabled"),
("Notice", "Style"),
+ ("Notice", "TaskPopupEnabled"),
("Personalization", "BackgroundEffect"),
("Personalization", "DpiScale"),
("Personalization", "Language"),
diff --git a/tests/test_notice.py b/tests/test_notice.py
index 72617cc3..5f133566 100644
--- a/tests/test_notice.py
+++ b/tests/test_notice.py
@@ -7,14 +7,14 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import pytest
from desktop_notifier.common import Button, Notification, Urgency
-from PySide6.QtCore import Qt
+from PySide6.QtCore import QEventLoop, Qt, QTimer
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,
+ SCREEN_MARGIN, SPACING, NotificationPopup, Popup, PopupNotifier, PopupStack, Presence,
+ buildDiskSpaceInsufficient, buildParseFailed, buildTaskCompleted,
)
@@ -26,15 +26,20 @@ 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:
+def buildNotice(title: str = "下载完成", timeout: int = 60, **kwargs) -> Notification:
return Notification(title=title, message="ubuntu.iso\n5.00 GB · /tmp", timeout=timeout, **kwargs)
@pytest.fixture
-def popupNotifier(qapp):
- notifier = PopupNotifier(Presence())
- yield notifier
- notifier.clear()
+def popupStack(qapp):
+ stack = PopupStack(Presence())
+ yield stack
+ stack.clear()
+
+
+def popupNotifier(popupStack):
+ return PopupNotifier(popupStack)
def test_build_task_completed_opens_output(monkeypatch, tmp_path):
@@ -88,7 +93,7 @@ def test_send_beyond_screen_dismisses_oldest(qtbot, popupNotifier):
popupNotifier.send(buildNotice(str(index), on_dismissed=lambda i=index: dismissed.append(i)))
area = QApplication.primaryScreen().availableGeometry()
- qtbot.waitUntil(lambda: dismissed and isSettled())
+ qtbot.waitUntil(lambda: bool(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))
@@ -114,17 +119,78 @@ def test_press_button_runs_action_without_dismissing(qtbot, popupNotifier):
pushButton, _ = shownPopups()[0].buttons[0]
qtbot.mouseClick(pushButton, Qt.MouseButton.LeftButton)
- qtbot.waitUntil(lambda: not shownPopups())
- assert events == ["pressed"]
+ qtbot.waitUntil(lambda: not shownPopups() and events == ["pressed"])
-def test_clear_closes_silently_and_ignores_later_send(qtbot, popupNotifier):
+def test_clear_closes_silently_and_ignores_later_send(qtbot, popupStack, popupNotifier):
dismissed = []
popupNotifier.send(buildNotice(on_dismissed=lambda: dismissed.append(True)))
qtbot.waitUntil(lambda: len(shownPopups()) == 1)
- popupNotifier.clear()
+ popupStack.clear()
popupNotifier.send(buildNotice())
assert not shownPopups()
assert dismissed == []
+
+
+def test_send_beyond_screen_keeps_long_lived_at_bottom(qtbot, popupNotifier):
+ dismissed = []
+ popupNotifier.send(buildNotice("长驻", timeout=0, on_dismissed=lambda: dismissed.append("长驻")))
+ for index in range(12):
+ popupNotifier.send(buildNotice(str(index), on_dismissed=lambda i=index: dismissed.append(i)))
+
+ qtbot.waitUntil(lambda: bool(dismissed) and isSettled())
+ area = QApplication.primaryScreen().availableGeometry()
+ bottom = max(shownPopups(), key=lambda p: p.y())
+ assert bottom.titleLabel.text() == "长驻"
+ assert bottom.geometry().bottom() == area.bottom() - SCREEN_MARGIN
+ assert "长驻" not in dismissed
+
+
+def test_add_replacing_takes_position_without_dismissing(qtbot, popupStack):
+ dismissed = []
+ old = NotificationPopup(buildNotice("进度", timeout=0, on_dismissed=lambda: dismissed.append(True)))
+ popupStack.add(old)
+ popupStack.add(NotificationPopup(buildNotice("其他")))
+ qtbot.waitUntil(lambda: len(shownPopups()) == 2 and isSettled())
+ position = old.pos()
+
+ new = NotificationPopup(buildNotice("完成", timeout=0))
+ popupStack.add(new, replacing=old)
+
+ qtbot.waitUntil(lambda: len(shownPopups()) == 2 and isSettled())
+ assert new.pos() == position
+ assert sorted(p.titleLabel.text() for p in shownPopups()) == ["其他", "完成"]
+ assert dismissed == []
+
+
+def test_minimize_frees_position_until_restored(qtbot, popupStack):
+ lower = NotificationPopup(buildNotice("下", timeout=0))
+ upper = NotificationPopup(buildNotice("上", timeout=0))
+ popupStack.add(upper)
+ popupStack.add(lower)
+ qtbot.waitUntil(lambda: len(shownPopups()) == 2 and isSettled())
+ bottomY = lower.y()
+
+ lower.showMinimized()
+ qtbot.waitUntil(lambda: upper.y() == bottomY and isSettled())
+
+ lower.showNormal()
+ qtbot.waitUntil(lambda: lower.y() == bottomY and upper.y() < bottomY and isSettled())
+
+
+def test_click_with_nested_event_loop_closes_without_error(qtbot, popupNotifier):
+ def openDialog():
+ loop = QEventLoop()
+ QTimer.singleShot(500, loop.quit)
+ loop.exec()
+ events.append("opened")
+
+ events = []
+ popupNotifier.send(buildNotice(on_clicked=openDialog))
+ qtbot.waitUntil(lambda: len(shownPopups()) == 1 and isSettled())
+
+ qtbot.mouseClick(shownPopups()[0], Qt.MouseButton.LeftButton)
+
+ qtbot.waitUntil(lambda: events == ["opened"] and not shownPopups(), timeout=3000)