Skip to content

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

feat(notice): 下载进度可只显示在任务栏

XiaoYouChR159dc60dddf2
diff --git a/GLOSSARY.md b/GLOSSARY.md
index 1b86a8de..c30d6879 100644
--- a/GLOSSARY.md
+++ b/GLOSSARY.md
@@ -187,11 +187,11 @@ _Avoid_: 与 Notice 混淆(Notice 发出即完成,Request 会被消解)
_Avoid_: 配对弹窗
**Clipboard Request**:
-剪贴板监听识别到链接后,询问用户是否接管的 Request。新识别的链接替换未决的旧请求。
+剪贴板监听在主窗口不在屏幕上、且用户打开了询问时,询问是否接管链接的 Request。用户关掉询问时不产生此 Request。新识别的链接替换未决的旧请求。
_Avoid_: 剪贴板弹窗
**Task Popup**:
-新建任务第一次开始下载时弹出、显示其进度的 Popup,拥有自己的任务栏按钮,可最小化。任务完成或失败时,由不自动关闭的结果提示原地取代。从弹出到用户关闭 Task Popup 或结果提示之前,该任务是被跟踪的任务,它完成时不另发 Notice。
+新建任务第一次开始下载时显示其进度的 Popup,拥有自己的任务栏按钮,按钮显示该任务的文件图标,可最小化。用户可以让它通过弹窗显示,或只显示于任务栏。任务完成或失败时,由不自动关闭的结果提示原地取代。从弹出到用户关闭 Task Popup 或结果提示之前,该任务是被跟踪的任务,它完成时不另发 Notice。
_Avoid_: 进度窗口、progress dialog、下载弹窗
**Pair Token**:
diff --git a/Ghost-Downloader-3.py b/Ghost-Downloader-3.py
index 3820b55b..24873f55 100644
--- a/Ghost-Downloader-3.py
+++ b/Ghost-Downloader-3.py
@@ -68,7 +68,7 @@ def setupEnvironment() -> None:
def startApp(application: Application, primaryInstance: PrimaryInstance, isSilent: bool = False) -> None:
from PySide6.QtGui import QIcon
- from app.config.cfg import NoticeStyle, cfg
+ from app.config.cfg import NoticeStyle, TaskPopupPlace, cfg
from app.view.dialogs.name_conflict import NameConflictPrompt
from app.view.shell.clipboard_listener import ClipboardListener
from app.signal_bus import signalBus
@@ -243,82 +243,110 @@ def startApp(application: Application, primaryInstance: PrimaryInstance, isSilen
taskService.tasksAllCompleted.connect(release)
from app.platform.desktop_notification import (
- NotificationPopup, PopupNotifier, PopupStack, SystemNotifier, buildClipboardRequest,
- buildDiskSpaceInsufficient, buildPairRequest, buildParseFailed, buildTaskCompleted, buildTaskFailed, createPresence,
- toFileIcon,
+ PopupNotifier, PopupStack, SystemNotifier, buildClipboardRequest,
+ buildDiskSpaceInsufficient, buildPairRequest, buildParseFailed, buildTaskCompleted, buildTaskFailed,
+ createDoNotDisturb, toFileIcon,
)
systemNotifier = SystemNotifier(coroutineRunner.submit)
sendTo = {NoticeStyle.SYSTEM: systemNotifier.send, NoticeStyle.OFF: lambda _: None}
popupStack: PopupStack | None = None
+ popupNotifier: PopupNotifier | None = None
if NoticeStyle.POPUP in cfg.noticeStyle.options:
- presence = createPresence()
- popupStack = PopupStack(presence)
- sendTo[NoticeStyle.POPUP] = PopupNotifier(popupStack).send
+ doNotDisturb = createDoNotDisturb()
+ popupStack = PopupStack(doNotDisturb)
+ popupNotifier = PopupNotifier(popupStack)
+ sendTo[NoticeStyle.POPUP] = popupNotifier.send
# 先于 onAboutToQuit 连接,engine.stop() 期间再来的 Notice 会被忽略
- application.aboutToQuit.connect(presence.close)
+ application.aboutToQuit.connect(doNotDisturb.close)
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 windowIsAway() -> bool:
+ return window is None or not window.isVisible() or window.isMinimized()
def onUrlsDetected(urls: list[str]) -> None:
- nonlocal clipboardPopup
- if not canShowRequestPopup():
+ if not cfg.isClipboardRequestEnabled.value or not windowIsAway() or popupNotifier is None:
show().addUrls(urls)
return
- if not presence.canInterrupt():
- return
- popup = NotificationPopup(buildClipboardRequest(urls, lambda: show().addUrls(urls)))
- popupStack.add(popup, replacing=clipboardPopup)
- clipboardPopup = popup
+ popupNotifier.send(buildClipboardRequest(urls, lambda: show().addUrls(urls)), "clipboard")
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)
+ if request is None or not windowIsAway() or popupNotifier is None:
+ if popupStack is not None:
+ popupStack.close("pair")
+ if request is not None:
+ show().onPairRequested(request)
return
- pairPopup = NotificationPopup(buildPairRequest(
+ popupNotifier.send(buildPairRequest(
request, lambda: browserService.approvePair(request.requestId),
- lambda: browserService.rejectPair(request.requestId)))
- popupStack.add(pairPopup)
+ lambda: browserService.rejectPair(request.requestId)), "pair")
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:
- sendTo[cfg.noticeStyle.value](toNotice(notification))
+ if not cfg.isNoticeSoundEnabled.value:
+ notification = replace(notification, sound=None)
+ sendTo[cfg.noticeStyle.value](notification)
+
+ candidates: set[str] = set()
+
+ def showTaskPopup(task: Task, minimized: bool) -> None:
+ if popupStack is None:
+ return
+ popupId = f"task:{task.taskId}"
+ if (popup := popupStack.popup(popupId)) is not None:
+ if minimized or not popup.isMinimized():
+ return
+ if popupStack.countShown("task:") >= 3:
+ return
+ popup.showNormal()
+ return
+ if not minimized and popupStack.countShown("task:") >= 3:
+ return
+ from app.view.shell.task_popup import TaskPopup
+ popup = TaskPopup(task, taskService, speedMeter.speedChanged)
+ popup.openOnTaskbar = minimized
+ popupStack.add(popup)
- from app.models.task import TaskStatus
+ def onTaskAdded(task: Task) -> None:
+ candidates.add(task.taskId)
- def buildTaskResult(task: Task) -> Notification:
- if task.status == TaskStatus.COMPLETED:
- return toNotice(replace(buildTaskCompleted(task, toFileIcon(task.outputPath)), timeout=0))
- return buildTaskFailed(task, activate)
+ def onTaskStarted(task: Task) -> None:
+ if task.taskId not in candidates:
+ return
+ candidates.discard(task.taskId)
+ if (popupStack is None or cfg.noticeStyle.value != NoticeStyle.POPUP
+ or cfg.taskPopupPlace.value == TaskPopupPlace.OFF):
+ return
+ showTaskPopup(task, minimized=cfg.taskPopupPlace.value == TaskPopupPlace.TASKBAR)
- 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 onTaskRemoved(taskId: str) -> None:
+ candidates.discard(taskId)
+ if popupStack is not None:
+ popupStack.close(f"task:{taskId}")
def onTaskCompleted(task: Task) -> None:
- if taskTracker is None or not taskTracker.isTracking(task.taskId):
- sendNotice(buildTaskCompleted(task, toFileIcon(task.outputPath)))
+ notice = buildTaskCompleted(task, toFileIcon(task.outputPath))
+ popupId = f"task:{task.taskId}"
+ if popupNotifier is not None and popupStack is not None and popupStack.has(popupId):
+ if not cfg.isNoticeSoundEnabled.value:
+ notice = replace(notice, sound=None)
+ popupNotifier.send(replace(notice, timeout=0), popupId)
+ return
+ sendNotice(notice)
+ def onTaskFailed(task: Task) -> None:
+ popupId = f"task:{task.taskId}"
+ if popupNotifier is not None and popupStack is not None and popupStack.has(popupId):
+ popupNotifier.send(buildTaskFailed(task, activate), popupId)
+
+ if popupStack is not None:
+ taskService.taskAdded.connect(onTaskAdded)
+ taskService.taskStarted.connect(onTaskStarted)
+ taskService.taskRemoved.connect(onTaskRemoved)
+ taskService.taskFailed.connect(onTaskFailed)
+ signalBus.taskPopupRequested.connect(lambda task: showTaskPopup(task, minimized=False))
taskService.taskCompleted.connect(onTaskCompleted)
taskService.diskSpaceInsufficient.connect(
lambda free, needed: sendNotice(buildDiskSpaceInsufficient(free, needed, activate)))
diff --git a/app/config/cfg.py b/app/config/cfg.py
index 39d49e9c..432b8966 100644
--- a/app/config/cfg.py
+++ b/app/config/cfg.py
@@ -129,6 +129,12 @@ class NoticeStyle(Enum):
OFF = "Off"
+class TaskPopupPlace(Enum):
+ OFF = "Off"
+ CORNER = "Corner"
+ TASKBAR = "Taskbar"
+
+
def canShowPopup() -> bool:
# Wayland 不许客户端定位窗口;XWayland 在鼠标移到 Wayland 原生窗口时不发离开事件,Popup 会一直不关
return (sys.platform != "darwin" and os.environ.get("XDG_SESSION_TYPE") != "wayland"
@@ -389,13 +395,17 @@ class Config(QConfig):
OptionsValidator(CloseMode), EnumSerializer(CloseMode),
)
isClipboardListenerEnabled = ConfigItem("Software", "ClipboardListener", True, BoolValidator())
+ isClipboardRequestEnabled = ConfigItem("Software", "ClipboardRequest", False, 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())
- isTaskPopupEnabled = ConfigItem("Notice", "TaskPopupEnabled", False, BoolValidator())
+ taskPopupPlace = OptionsConfigItem(
+ "Notice", "TaskPopupPlace", TaskPopupPlace.TASKBAR,
+ OptionsValidator(TaskPopupPlace), EnumSerializer(TaskPopupPlace),
+ )
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 df646a5e..a89e4462 100644
--- a/app/platform/application.py
+++ b/app/platform/application.py
@@ -17,7 +17,6 @@ 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):
@@ -34,7 +33,6 @@ 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 4843b4d0..d170bf25 100644
--- a/app/platform/desktop_notification.py
+++ b/app/platform/desktop_notification.py
@@ -24,7 +24,6 @@ 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
@@ -89,7 +88,8 @@ def buildTaskCompleted(task: Task, icon: Icon | None) -> Notification:
outputPath = task.outputPath
return Notification(
title=QCoreApplication.translate("Notifications", "下载完成"),
- message=f"{task.name}\n{toReadableSize(task.fileSize)} · {task.outputFolder}",
+ message=f"{task.name}\n" + QCoreApplication.translate(
+ "Notifications", "大小 {0},保存于 {1}").format(toReadableSize(task.fileSize), task.outputFolder),
icon=icon,
buttons=(
Button(title=QCoreApplication.translate("Notifications", "打开文件"),
@@ -145,7 +145,10 @@ def buildClipboardRequest(urls: list[str], accept: Callable[[], None]) -> Notifi
return Notification(
title=QCoreApplication.translate("Notifications", "检测到下载链接"),
message=message,
- buttons=(Button(title=QCoreApplication.translate("Notifications", "下载"), on_pressed=accept),),
+ buttons=(
+ Button(title=QCoreApplication.translate("Notifications", "下载"), on_pressed=accept),
+ Button(title=QCoreApplication.translate("Notifications", "忽略"), on_pressed=None),
+ ),
on_clicked=accept,
)
@@ -188,13 +191,11 @@ class SystemNotifier:
await self._notifier.send_notification(notification)
-class Presence:
- """能否打扰用户,见 ADR 0029。changed 只表示状态可能变了,要用 canInterrupt 重新查询。"""
-
+class DoNotDisturb:
changed = Signal()
- def canInterrupt(self) -> bool:
- return True
+ def isOn(self) -> bool:
+ return False
def close(self) -> None:
pass
@@ -228,7 +229,7 @@ if sys.platform == "win32":
_fields_ = [("cbSize", wintypes.DWORD), ("hWnd", wintypes.HWND), ("uCallbackMessage", wintypes.UINT),
("uEdge", wintypes.UINT), ("rc", wintypes.RECT), ("lParam", wintypes.LPARAM)]
- class WindowsPresence(QAbstractNativeEventFilter, Presence):
+ class WindowsDoNotDisturb(QAbstractNativeEventFilter, DoNotDisturb):
def __init__(self):
super().__init__()
self._window = QWindow()
@@ -239,7 +240,7 @@ if sys.platform == "win32":
if not wtsapi32.WTSRegisterSessionNotification(self._hwnd, 0):
logger.warning("注册会话通知失败: {}", ctypes.GetLastError())
- def canInterrupt(self) -> bool:
+ def isOn(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)):
@@ -247,11 +248,11 @@ if sys.platform == "win32":
isLocked = ctypes.c_int32.from_address(buffer.value + 16).value == WTS_SESSIONSTATE_LOCK
wtsapi32.WTSFreeMemory(buffer)
if isLocked:
- return False
+ return True
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)
+ return False
+ return state.value in (QUNS_BUSY, QUNS_RUNNING_D3D_FULL_SCREEN, QUNS_PRESENTATION_MODE)
def close(self) -> None:
shell32.SHAppBarMessage(ABM_REMOVE, ctypes.byref(self._appbarData()))
@@ -289,20 +290,20 @@ if sys.platform == "linux":
PROPERTIES = "org.freedesktop.DBus.Properties"
PROPERTIES_CHANGED_SLOT = SLOT("onPropertiesChanged(QString,QVariantMap,QStringList)")
- class LinuxPresence(QObject, Presence):
+ class LinuxDoNotDisturb(QObject, DoNotDisturb):
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:
+ def isOn(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()
+ return False
+ return bool(reply.arguments()[0].variant())
def close(self) -> None:
QDBusConnection.systemBus().disconnect(
@@ -314,17 +315,17 @@ if sys.platform == "linux":
self.changed.emit()
-def createPresence() -> Presence:
+def createDoNotDisturb() -> DoNotDisturb:
if sys.platform == "win32":
- return WindowsPresence()
+ return WindowsDoNotDisturb()
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())
+ return LinuxDoNotDisturb(reply.arguments()[0].path())
logger.debug("logind 不可用,Popup 不判断锁屏: {}", reply.errorMessage())
- return Presence()
+ return DoNotDisturb()
class Popup(QWidget):
@@ -336,6 +337,8 @@ class Popup(QWidget):
def __init__(self):
super().__init__()
+ self.popupId: str | None = None
+ self.openOnTaskbar = False
self.duration = 0
self.hasSound = False
self.isExiting = False
@@ -360,6 +363,8 @@ class Popup(QWidget):
self.windowEffect = None
if sys.platform == "win32":
from qframelesswindow import WindowEffect
+
+ from app.platform.taskbar import addTaskbarButton
if self.hasTaskbarButton:
addTaskbarButton(int(self.winId()))
self.windowEffect = WindowEffect(self)
@@ -420,10 +425,22 @@ class Popup(QWidget):
return scaled
def moveTo(self, pos: QPoint) -> None:
- """第一次从屏幕右侧滑入,之后平移到 pos。"""
isMoved = pos != self._targetPos
self._targetPos = pos
+ if self.windowState() & Qt.WindowState.WindowMinimized:
+ return
+ if self.openOnTaskbar:
+ self.openOnTaskbar = False
+ self._detachFromActiveWindow()
+ if sys.platform == "win32":
+ from app.platform.taskbar import minimizeWithoutActivating
+ minimizeWithoutActivating(int(self.winId()), pos.x(), pos.y(), self.width(), self.height())
+ return
+ self.move(pos)
+ self.showMinimized()
+ return
if not self.isVisible():
+ self._detachFromActiveWindow()
self.move(pos.x() + self.width() + SCREEN_MARGIN, pos.y())
self.show()
self._animate(pos, ENTER_DURATION, ENTER_CURVE)
@@ -431,6 +448,11 @@ class Popup(QWidget):
elif isMoved and self._pressX is None:
self._animate(pos, MOVE_DURATION, MOVE_CURVE)
+ def _detachFromActiveWindow(self) -> None:
+ self.winId()
+ if handle := self.windowHandle():
+ handle.setTransientParent(None)
+
def showAt(self, pos: QPoint) -> None:
self._targetPos = pos
self.move(pos)
@@ -482,6 +504,12 @@ class Popup(QWidget):
if self._isAcrylic:
self.windowEffect.setAcrylicEffect(self.winId(), "20202030" if isDarkTheme() else "FFFFFF30")
+ def showEvent(self, event) -> None:
+ super().showEvent(event)
+ # 显示前写入的还原坐标还没落到正确屏幕上
+ if event.spontaneous() and not self.isMinimized():
+ self.move(self._targetPos)
+
def changeEvent(self, event) -> None:
if event.type() == QEvent.Type.WindowStateChange:
self.layoutChanged.emit()
@@ -494,6 +522,9 @@ class Popup(QWidget):
return
self.closeTimer.stop()
self.moveAnimation.stop()
+ if self.hasTaskbarButton and sys.platform == "win32":
+ from app.platform.taskbar import setWindowAppId
+ setWindowAppId(int(self.winId()), None)
super().closeEvent(event)
def paintEvent(self, event) -> None:
@@ -645,15 +676,13 @@ class NotificationPopup(Popup):
class PopupStack:
- """只能在 Qt 主线程调用。"""
-
- def __init__(self, presence: Presence):
- self._presence = presence
- self._popups: list[Popup] = [] # 最早的在前;没有 parent 的窗口靠这里的引用存活
+ def __init__(self, doNotDisturb: DoNotDisturb):
+ self._doNotDisturb = doNotDisturb
+ self._popups: list[Popup] = [] # 没有 parent,窗口靠这份列表活着
self._pending: deque[Popup] = deque()
self._lastSoundAt = float("-inf")
self._isClosed = False
- presence.changed.connect(self._showPending)
+ doNotDisturb.changed.connect(self._showPending)
application = QGuiApplication.instance()
application.primaryScreenChanged.connect(self._onPrimaryScreenChanged)
application.screenAdded.connect(self._onScreenAdded)
@@ -664,6 +693,8 @@ class PopupStack:
if self._isClosed:
popup.deleteLater()
return
+ if replacing is None and popup.popupId:
+ replacing = self._byId(popup.popupId)
popup.exited.connect(lambda: self._remove(popup))
popup.layoutChanged.connect(self._arrange)
if replacing in self._pending:
@@ -681,8 +712,38 @@ class PopupStack:
self._pending.append(popup)
self._showPending()
+ def has(self, popupId: str) -> bool:
+ return self._byId(popupId) is not None
+
+ def popup(self, popupId: str) -> Popup | None:
+ return self._byId(popupId)
+
+ def countShown(self, prefix: str) -> int:
+ return sum(1 for popup in self._popups
+ if not popup.isExiting and not popup.isMinimized()
+ and (popup.popupId or "").startswith(prefix))
+
+ def count(self, prefix: str) -> int:
+ return sum(1 for popup in (*self._pending, *self._popups)
+ if not popup.isExiting and (popup.popupId or "").startswith(prefix))
+
+ def close(self, popupId: str) -> None:
+ popup = self._byId(popupId)
+ if popup is None:
+ return
+ if popup in self._pending:
+ self._pending.remove(popup)
+ self._close(popup)
+ return
+ popup.exit(isDismissed=False)
+
+ def _byId(self, popupId: str) -> Popup | None:
+ for popup in (*self._pending, *self._popups):
+ if popup.popupId == popupId and not popup.isExiting:
+ return popup
+ return None
+
def clear(self) -> None:
- """立即关闭全部 Popup,不触发 on_dismissed;之后的 add 一律忽略。"""
self._isClosed = True
for popup in [*self._pending, *self._popups]:
self._close(popup)
@@ -690,7 +751,7 @@ class PopupStack:
self._popups.clear()
def _showPending(self) -> None:
- if not self._pending or QGuiApplication.primaryScreen() is None or not self._presence.canInterrupt():
+ if not self._pending or QGuiApplication.primaryScreen() is None or self._doNotDisturb.isOn():
return
while self._pending:
popup = self._pending.popleft()
@@ -760,5 +821,7 @@ class PopupNotifier:
def __init__(self, stack: PopupStack):
self._stack = stack
- def send(self, notification: Notification) -> None:
- self._stack.add(NotificationPopup(notification))
+ def send(self, notification: Notification, popupId: str | None = None) -> None:
+ popup = NotificationPopup(notification)
+ popup.popupId = popupId
+ self._stack.add(popup)
diff --git a/app/platform/taskbar.py b/app/platform/taskbar.py
index 78a342d6..4dbc4c36 100644
--- a/app/platform/taskbar.py
+++ b/app/platform/taskbar.py
@@ -1,15 +1,17 @@
from __future__ import annotations
+import ctypes
+from ctypes import (
+ POINTER, WINFUNCTYPE, byref, c_byte, c_int, c_short, c_uint64, c_ulong, c_ushort, c_void_p, c_wchar_p,
+)
from functools import cache, partial
-from typing import TYPE_CHECKING
-if TYPE_CHECKING:
- from app.models.task import TaskStatus
+from loguru import logger
+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, status: TaskStatus | None, progress: float | None) -> None:
taskbarList = createTaskbarList()
if taskbarList is None:
return
@@ -25,9 +27,53 @@ def setWindowsProgress(hwnd: int, status: TaskStatus | None, progress: float | N
setValue(hwnd, round((100 if progress is None else progress) * 10), 1000)
-def addTaskbarButton(hwnd: int) -> None:
- import ctypes
+def setWindowAppId(hwnd: int, appId: str | None) -> None:
+ from ctypes import HRESULT, wintypes
+
+ class GUID(ctypes.Structure):
+ _fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD),
+ ("Data3", wintypes.WORD), ("Data4", wintypes.BYTE * 8)]
+
+ class PROPERTYKEY(ctypes.Structure):
+ _fields_ = [("fmtid", GUID), ("pid", wintypes.DWORD)]
+
+ class PROPVARIANT_VALUE(ctypes.Union):
+ _fields_ = [("boolVal", c_short), ("pwszVal", c_wchar_p)]
+
+ class PROPVARIANT(ctypes.Structure):
+ _fields_ = [("vt", c_ushort), ("r1", c_ushort), ("r2", c_ushort), ("r3", c_ushort), ("value", PROPVARIANT_VALUE)]
+
+ VT_EMPTY, VT_BOOL, VT_LPWSTR = 0, 11, 31
+ shell32 = ctypes.windll.shell32
+ shell32.SHGetPropertyStoreForWindow.argtypes = [
+ wintypes.HWND, ctypes.POINTER(GUID), ctypes.POINTER(ctypes.c_void_p)]
+ shell32.SHGetPropertyStoreForWindow.restype = HRESULT
+ store = ctypes.c_void_p()
+ iid = GUID(0x886D8EEB, 0x8CF2, 0x4446, (0x8D, 0x02, 0xCD, 0xBA, 0x1D, 0xBD, 0xCF, 0x99))
+ if shell32.SHGetPropertyStoreForWindow(hwnd, ctypes.byref(iid), ctypes.byref(store)):
+ logger.warning("无法取得窗口属性: {}", ctypes.GetLastError())
+ return
+ vtable = ctypes.POINTER(ctypes.c_void_p).from_address(store.value)
+ setValue = WINFUNCTYPE(HRESULT, c_void_p, ctypes.POINTER(PROPERTYKEY), ctypes.POINTER(PROPVARIANT))(vtable[6])
+ release = WINFUNCTYPE(c_ulong, c_void_p)(vtable[2])
+ fmtid = GUID(0x9F4C2855, 0x9F79, 0x4B39, (0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3))
+
+ def put(pid: int, variant: PROPVARIANT) -> None:
+ key = PROPERTYKEY(fmtid, pid)
+ if setValue(store, ctypes.byref(key), ctypes.byref(variant)):
+ logger.warning("无法设置窗口 AppUserModelID")
+
+ if appId is None:
+ put(9, PROPVARIANT(VT_EMPTY))
+ put(5, PROPVARIANT(VT_EMPTY))
+ else:
+ # 先禁止固定,再写 ID。任务栏只在 ID 变化时重新分组
+ put(9, PROPVARIANT(VT_BOOL, value=PROPVARIANT_VALUE(boolVal=-1)))
+ put(5, PROPVARIANT(VT_LPWSTR, value=PROPVARIANT_VALUE(pwszVal=appId)))
+ release(store)
+
+def addTaskbarButton(hwnd: int) -> None:
GWL_STYLE, GWL_EXSTYLE = -16, -20
WS_MINIMIZEBOX, WS_SYSMENU, WS_EX_APPWINDOW = 0x00020000, 0x00080000, 0x00040000
user32 = ctypes.windll.user32
@@ -35,13 +81,32 @@ def addTaskbarButton(hwnd: int) -> None:
user32.SetWindowLongPtrW(hwnd, GWL_STYLE, user32.GetWindowLongPtrW(hwnd, GWL_STYLE) | WS_MINIMIZEBOX | WS_SYSMENU)
-@cache
-def createTaskbarList():
- from ctypes import HRESULT, POINTER, WINFUNCTYPE, byref, c_byte, c_int, c_uint64, c_void_p, oledll
+def minimizeWithoutActivating(hwnd: int, x: int, y: int, width: int, height: int) -> None:
+ # Qt 对 WA_ShowWithoutActivating 的窗口会把 SW_SHOWMINIMIZED 改成 SW_SHOWNOACTIVATE
+ from ctypes import wintypes
+
+ addTaskbarButton(hwnd)
+
+ class WINDOWPLACEMENT(ctypes.Structure):
+ _fields_ = [("length", wintypes.UINT), ("flags", wintypes.UINT), ("showCmd", wintypes.UINT),
+ ("ptMinPosition", wintypes.POINT), ("ptMaxPosition", wintypes.POINT),
+ ("rcNormalPosition", wintypes.RECT)]
+
+ SW_SHOWMINNOACTIVE = 7
+ user32 = ctypes.windll.user32
+ placement = WINDOWPLACEMENT()
+ placement.length = ctypes.sizeof(WINDOWPLACEMENT)
+ user32.GetWindowPlacement(hwnd, ctypes.byref(placement))
+ placement.showCmd = SW_SHOWMINNOACTIVE
+ placement.rcNormalPosition = wintypes.RECT(x, y, x + width, y + height)
+ user32.SetWindowPlacement(hwnd, ctypes.byref(placement))
- from loguru import logger
+@cache
+def createTaskbarList():
# Qt6 和 pywin32 都没有封装 ITaskbarList3,只能按 shobjidl_core.h 的虚表序号直调
+ from ctypes import HRESULT, oledll
+
ole32 = oledll.ole32
clsid = (c_byte * 16)()
iid = (c_byte * 16)()
diff --git a/app/signal_bus.py b/app/signal_bus.py
index e3b0245c..29351e44 100644
--- a/app/signal_bus.py
+++ b/app/signal_bus.py
@@ -4,6 +4,7 @@ from PySide6.QtCore import QObject, Signal
class SignalBus(QObject):
activationRequested = Signal()
exceptionCaught = Signal(str)
+ taskPopupRequested = Signal(object)
signalBus = SignalBus()
diff --git a/app/view/cards/task_cards.py b/app/view/cards/task_cards.py
index 5fe22eb8..7315dc2e 100644
--- a/app/view/cards/task_cards.py
+++ b/app/view/cards/task_cards.py
@@ -15,7 +15,7 @@ from qfluentwidgets import (
isDarkTheme, themeColor,
)
-from app.config.cfg import cfg
+from app.config.cfg import canShowPopup, cfg
from app.format import toReadableSize, toReadableTime
from app.checksum import ALGORITHMS, COMMON_ALGORITHMS
from app.models.task import TaskStatus, SpecialFileSize
@@ -24,6 +24,7 @@ from app.platform.filesystem import isExisting, isFolder
from app.view.components.labels import IconBodyLabel, IconStrongBodyLabel
from app.view.components.category_settings import toCategoryName
from app.i18n import toLocalizedError
+from app.signal_bus import signalBus
if TYPE_CHECKING:
from app.models.task import Task
@@ -444,6 +445,10 @@ class TaskCard(CardWidget):
detail = Action(FluentIcon.INFO, self.tr("任务详情"), self)
detail.triggered.connect(self._openDrawer)
menu.addAction(detail)
+ if self._task.status == TaskStatus.RUNNING and canShowPopup():
+ showProgress = Action(FluentIcon.BACK_TO_WINDOW, self.tr("在单独弹窗中显示下载进度"), self)
+ showProgress.triggered.connect(lambda: signalBus.taskPopupRequested.emit(self._task))
+ menu.addAction(showProgress)
menu.addSeparator()
copyUrl = Action(FluentIcon.COPY, self.tr("复制下载链接"), self)
diff --git a/app/view/components/setting_cards.py b/app/view/components/setting_cards.py
index 7e8e4eaf..9743a3c3 100644
--- a/app/view/components/setting_cards.py
+++ b/app/view/components/setting_cards.py
@@ -329,7 +329,7 @@ class ClipboardSettingCard(CollapsibleSettingCard):
def __init__(self, packs: list, parent=None):
super().__init__(FluentIcon.PASTE, self.tr("剪贴板监听"),
- self.tr("剪贴板监听器将自动检测剪贴板中的链接并添加下载任务"), parent=parent)
+ self.tr("自动检测剪贴板中的下载链接"), parent=parent)
self._packs = [pack for pack in packs if pack.capturedLinks]
self._initWidget()
self._initLayout()
diff --git a/app/view/dialogs/task_draft.py b/app/view/dialogs/task_draft.py
index 3b96028f..44efbf4d 100644
--- a/app/view/dialogs/task_draft.py
+++ b/app/view/dialogs/task_draft.py
@@ -133,12 +133,12 @@ class TaskDraftDialog(MessageBoxBase):
self._parseTimer.timeout.connect(self._onParseNeeded)
self.urlEdit.textChanged.connect(self._parseTimer.start)
- self._draft.parsingBusyChanged.connect(self.progressBar.setVisible)
- self._draft.parseSucceeded.connect(self._onParseSucceeded)
- self._draft.parseFailed.connect(self._onParseFailed)
+ self._draft.parsingBusyChanged.connect(self.progressBar.setVisible, owner=self)
+ self._draft.parseSucceeded.connect(self._onParseSucceeded, owner=self)
+ self._draft.parseFailed.connect(self._onParseFailed, owner=self)
self.draftGroup.refreshRequested.connect(self._draft.refreshFailed)
- self._draft.itemsChanged.connect(self._onItemsChanged)
- self._draft.itemsCleared.connect(self._onCleared)
+ self._draft.itemsChanged.connect(self._onItemsChanged, owner=self)
+ self._draft.itemsCleared.connect(self._onCleared, owner=self)
self.downloadButton.clicked.connect(self._accept)
self.downloadButton.dropDownClicked.connect(lambda: self._accept(autoStart=False))
diff --git a/app/view/pages/setting_page.py b/app/view/pages/setting_page.py
index 880f0278..2c8c2e12 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 NoticeStyle, cfg, LANGUAGE_TEXTS
+from app.config.cfg import NoticeStyle, canShowPopup, cfg, LANGUAGE_TEXTS
from app.i18n import toLocalizedError
from app.models.task import toTaskError
from app.services.port_listener import ListenStatus
@@ -312,10 +312,10 @@ class SettingPage(QWidget):
self.tr("当前为用户模式,数据保存在: {0}").format(APP_DATA_DIR),
)
- self.taskPopupCard = SwitchSettingCard(
- FluentIcon.SPEED_HIGH, self.tr("新建任务时显示下载进度"),
- self.tr("在屏幕右下角显示进度,可最小化到任务栏;需要通知方式为弹窗"),
- cfg.isTaskPopupEnabled,
+ self.taskPopupCard = ComboBoxSettingCard(
+ cfg.taskPopupPlace, FluentIcon.SPEED_HIGH, self.tr("新建任务的下载进度"),
+ self.tr("选择新建任务下载进度的显示方式"),
+ texts=[self.tr("不显示"), self.tr("通过弹窗显示"), self.tr("显示于任务栏")],
)
self.taskPopupCard.setEnabled(cfg.noticeStyle.value == NoticeStyle.POPUP)
@@ -344,6 +344,14 @@ class SettingPage(QWidget):
*([self.taskPopupCard] if NoticeStyle.POPUP in cfg.noticeStyle.options else []),
ClipboardSettingCard(self._featureService.packs),
]
+ if canShowPopup():
+ self.clipboardAskCard = SwitchSettingCard(
+ FluentIcon.CHAT, self.tr("复制链接后先询问"),
+ self.tr("主窗口关闭或最小化时,开启则先弹出窗口询问是否下载,关闭则直接打开主窗口。"),
+ cfg.isClipboardRequestEnabled,
+ )
+ self.clipboardAskCard.setEnabled(cfg.isClipboardListenerEnabled.value)
+ softwareCards.append(self.clipboardAskCard)
if sys.platform != "darwin":
self.associationCard = AssociationCard(self._featureService.packs)
softwareCards.append(self.associationCard)
@@ -407,7 +415,9 @@ 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))
+ cfg.noticeStyle.valueChanged.connect(self._onNoticeStyleChanged)
+ if canShowPopup():
+ cfg.isClipboardListenerEnabled.valueChanged.connect(self.clipboardAskCard.setEnabled)
self.downloadFolderPicker.pathChanged.connect(self._onDownloadFolderChanged)
cfg.downloadFolder.valueChanged.connect(self.downloadFolderPicker.setPath)
@@ -426,6 +436,9 @@ class SettingPage(QWidget):
self.openLogButton.clicked.connect(self._onOpenLogClicked)
self.migrateCard.clicked.connect(self._onMigrateClicked)
+ def _onNoticeStyleChanged(self, _value=None) -> None:
+ self.taskPopupCard.setEnabled(cfg.noticeStyle.value == NoticeStyle.POPUP)
+
def _onAutoSelectPortChanged(self, isAuto: bool) -> None:
self.browserPortCard.setEnabled(not isAuto)
diff --git a/app/view/shell/task_popup.py b/app/view/shell/task_popup.py
index e45e2b1c..d7299ee7 100644
--- a/app/view/shell/task_popup.py
+++ b/app/view/shell/task_popup.py
@@ -1,10 +1,9 @@
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.QtCore import QFileInfo, Qt
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QFileIconProvider, QHBoxLayout, QLabel, QSizePolicy, QVBoxLayout
from qfluentwidgets import (
@@ -14,38 +13,47 @@ from qfluentwidgets import (
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,
+ FILE_ICON_SIZE, ICON_SPACING, PADDING, SPACING, TEXT_WIDTH, Popup,
)
-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
+def toRemainingText(seconds: int) -> str:
+ if seconds < 60:
+ return f"{seconds} 秒"
+ minutes, secs = divmod(seconds, 60)
+ if seconds < 3600:
+ return f"{minutes} 分 {secs} 秒" if secs else f"{minutes} 分"
+ hours, minutes = divmod(minutes, 60)
+ return f"{hours} 小时 {minutes} 分" if minutes else f"{hours} 小时"
-MAX_TASK_POPUPS = 3
+if TYPE_CHECKING:
+ from app.models.task import Task
+ from app.services.task_service import TaskService
+ from app.signal import Signal
class TaskPopup(Popup):
hasTaskbarButton = True
- def __init__(self, task: Task, start: Callable[[Task], None], pause: Callable[[Task], None],
- delete: Callable[[Task], None]):
+ def __init__(self, task: Task, taskService: TaskService, speedChanged: Signal):
super().__init__()
self._task = task
- self._start = start
- self._pause = pause
- self._delete = delete
+ self._taskService = taskService
+ self._speedChanged = speedChanged
+ self.popupId = f"task:{task.taskId}"
self._initWidget()
self._initLayout()
self._bind()
self.refresh()
- self.refreshTimer.start()
def _initWidget(self) -> None:
+ self.setWindowIcon(QFileIconProvider().icon(QFileInfo(self._task.outputPath)))
super()._initWidget()
self.setWindowTitle(self._task.name)
+ if sys.platform == "win32":
+ from app.config.constants import DESKTOP_ID
+ from app.platform.taskbar import setWindowAppId
+ setWindowAppId(int(self.winId()), f"{DESKTOP_ID}.{self._task.taskId.replace('_', '-')}")
self.minimizeButton = self._createHeaderButton(FluentIcon.MINIMIZE)
self.headerButtons.insert(0, self.minimizeButton)
@@ -70,9 +78,6 @@ class TaskPopup(Popup):
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()
@@ -104,21 +109,33 @@ class TaskPopup(Popup):
def _bind(self) -> None:
super()._bind()
- self.minimizeButton.clicked.connect(self.showMinimized)
+ self.minimizeButton.clicked.connect(self._onMinimizeClicked)
self.toggleButton.clicked.connect(self._onToggleClicked)
- self.cancelButton.clicked.connect(lambda: self._delete(self._task))
- self.refreshTimer.timeout.connect(self.refresh)
+ self.cancelButton.clicked.connect(lambda: self._taskService.delete(self._task, shouldDeleteFiles=True))
+ self._speedChanged.connect(self.refresh, owner=self)
+ self._taskService.taskPaused.connect(self._onTaskPaused, owner=self)
+ self._taskService.taskStarted.connect(self._onTaskStarted, owner=self)
- def refresh(self) -> None:
+ def refresh(self, _speed: int | None = None) -> 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)}")
+ if task.status == TaskStatus.RUNNING and speed > 0 and task.fileSize > 0:
+ remaining = int((task.fileSize - received) / speed)
+ self.statusLabel.setText(self.tr("速度 {0}/s,剩余 {1}").format(
+ toReadableSize(speed), toRemainingText(remaining)))
+ elif task.status == TaskStatus.RUNNING and speed > 0:
+ self.statusLabel.setText(self.tr("速度 {0}/s").format(toReadableSize(speed)))
+ elif task.status == TaskStatus.RUNNING:
+ self.statusLabel.setText(self.tr("正在计算速度"))
elif task.status == TaskStatus.PAUSED:
self.statusLabel.setText(self.tr("任务已经暂停"))
else:
self.statusLabel.setText(self.tr("任务正在等待"))
- self.sizeLabel.setText(toSizeText(task, speed, received) or "")
+ if task.fileSize > 0:
+ self.sizeLabel.setText(self.tr("已下载 {0},共 {1}").format(
+ toReadableSize(received), toReadableSize(task.fileSize)))
+ else:
+ self.sizeLabel.setText(self.tr("已下载 {0}").format(toReadableSize(received)))
isPaused = task.status == TaskStatus.PAUSED
if isinstance(self.progressBar, ProgressBar):
@@ -135,60 +152,25 @@ class TaskPopup(Popup):
isKnown = isinstance(self.progressBar, ProgressBar)
setWindowsProgress(int(self.winId()), task.status, progress if isKnown else None)
+ def _onTaskPaused(self, task: Task) -> None:
+ if task.taskId == self._task.taskId:
+ self.refresh()
+
+ def _onTaskStarted(self, task: Task) -> None:
+ if task.taskId == self._task.taskId:
+ self.refresh()
+
+ def _onMinimizeClicked(self) -> None:
+ if sys.platform != "win32":
+ self.showMinimized()
+ return
+ from app.platform.taskbar import minimizeWithoutActivating
+ pos = self._targetPos
+ minimizeWithoutActivating(int(self.winId()), pos.x(), pos.y(), self.width(), self.height())
+
def _onToggleClicked(self) -> None:
if self._task.status == TaskStatus.PAUSED:
- self._start(self._task)
+ self._taskService.start(self._task)
else:
- self._pause(self._task)
+ self._taskService.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/shell/tray.py b/app/view/shell/tray.py
index 09f50538..6070d653 100644
--- a/app/view/shell/tray.py
+++ b/app/view/shell/tray.py
@@ -198,7 +198,7 @@ class SystemTrayIcon(QSystemTrayIcon):
self.destroyed.connect(self._menu.deleteLater)
self.activated.connect(self._onActivated)
- self._speedMeter.speedChanged.connect(self._onSpeedChanged)
+ self._speedMeter.speedChanged.connect(self._onSpeedChanged, owner=self)
def _onActivated(self, reason: QSystemTrayIcon.ActivationReason) -> None:
if reason == QSystemTrayIcon.ActivationReason.Trigger:
diff --git a/app/view/windows/main_window.py b/app/view/windows/main_window.py
index 5fa5cabd..f10b7f2a 100644
--- a/app/view/windows/main_window.py
+++ b/app/view/windows/main_window.py
@@ -250,8 +250,8 @@ class MainWindow(MSFluentWindow):
self.searchEdit.selectAll()
def _bind(self) -> None:
- self._draft.addFailed.connect(self.addTasks)
- self._draft.parseFailed.connect(self._onDraftParseFailed)
+ self._draft.addFailed.connect(self.addTasks, owner=self)
+ self._draft.parseFailed.connect(self._onDraftParseFailed, owner=self)
cfg.themeChanged.connect(self._setTheme)
QApplication.instance().styleHints().colorSchemeChanged.connect(self._onSystemColorSchemeChanged)
self.titleBar.closeBtn.clicked.disconnect(self.close)
diff --git a/app/view/windows/oobe_window.py b/app/view/windows/oobe_window.py
index 0a68b498..d6101eae 100644
--- a/app/view/windows/oobe_window.py
+++ b/app/view/windows/oobe_window.py
@@ -662,7 +662,7 @@ class AdvancedOptionsPage(QWidget):
)
self.clipboardCard = OptionCard(
FluentIcon.PASTE, self.tr("剪贴板监听"),
- self.tr("复制下载链接时自动弹出新任务提示"),
+ self.tr("复制下载链接时由本程序接管"),
isChecked=cfg.isClipboardListenerEnabled.value, parent=self,
)
self.categoryCard = OptionCard(
diff --git a/docs/adr/0029-presence-via-appbar-wts-and-logind.md b/docs/adr/0029-presence-via-appbar-wts-and-logind.md
index 6aaa7180..2baf9628 100644
--- a/docs/adr/0029-presence-via-appbar-wts-and-logind.md
+++ b/docs/adr/0029-presence-via-appbar-wts-and-logind.md
@@ -1,6 +1,6 @@
# 用 appbar、WTS 和 logind 判断能否打扰用户
-Popup 置顶显示,必须避开全屏、演示和锁屏,否则会打断全屏游戏(独占全屏下出现置顶窗口,游戏可能被最小化),或在锁屏期间到时关闭而无人看见。这类时候 Popup 先暂存,等到可以打扰再显示。判断由 `Presence` 负责:`send` 时同步查询一次,此后只在系统事件唤醒时重新查询,不轮询。
+Popup 置顶显示,必须避开全屏、演示和锁屏,否则会打断全屏游戏(独占全屏下出现置顶窗口,游戏可能被最小化),或在锁屏期间到时关闭而无人看见。这类时候 Popup 先暂存,等到可以打扰再显示。判断由 `DoNotDisturb` 负责:`isOn` 在 `send` 时同步查询一次,此后只在系统事件唤醒时重新查询,不轮询。不读系统的勿扰开关。
- **Windows**:锁屏以 `WTSQuerySessionInformation` 的 `SessionFlags` 为准,全屏和演示以 `SHQueryUserNotificationState` 为准(`BUSY`、`RUNNING_D3D_FULL_SCREEN`、`PRESENTATION_MODE` 不能打扰)。唤醒事件有三个:
- `ABN_FULLSCREENAPP`:用一个隐藏窗口 `ABM_NEW` 注册 appbar,不 `ABM_SETPOS`,所以不占屏幕空间;退出前 `ABM_REMOVE`。
diff --git a/docs/adr/0032-task-popup-owns-taskbar-button.md b/docs/adr/0032-task-popup-owns-taskbar-button.md
index 0d2b4e0d..1bb11ca1 100644
--- a/docs/adr/0032-task-popup-owns-taskbar-button.md
+++ b/docs/adr/0032-task-popup-owns-taskbar-button.md
@@ -17,4 +17,4 @@
- 最小化的 Task Popup 退出右下角堆叠,还原时重新插入。
- 任务结束后 Task Popup 被普通 Popup 形式的结果提示取代,任务栏按钮随之消失;最小化中的任务完成时,结果提示直接出现在右下角,不闪烁任务栏按钮。
- Linux 只有应用级的 LauncherEntry 进度,Task Popup 有按钮但无单任务进度;macOS 和 Wayland 不显示 Popup。
-- 任务栏"合并"显示时合并按钮显示谁的进度、Win10 上的表现,均未实测。
+- 每张 Task Popup 使用单独的 `AppUserModelID`(`com.xychr.ghostdownloader.` 加任务 id),并禁止固定到任务栏。任务栏按这个 ID 分组,合并打开时进度按钮不跟主窗口或其他 Task Popup 合成一颗。窗口关闭前清掉该属性,避免系统留下这份存储。
diff --git a/tests/test_android.py b/tests/test_android.py
index fcfd5b4a..4825966d 100644
--- a/tests/test_android.py
+++ b/tests/test_android.py
@@ -25,9 +25,9 @@ DESKTOP_ONLY = {
("Browser", "UrlSchemeRegistered"),
("GeneralDownload", "HistoryDownloadFolder"),
("GeneralDownload", "RecentFolders"),
+ ("Notice", "TaskPopupPlace"),
("Notice", "SoundEnabled"),
("Notice", "Style"),
- ("Notice", "TaskPopupEnabled"),
("Personalization", "BackgroundEffect"),
("Personalization", "DpiScale"),
("Personalization", "Language"),
@@ -37,6 +37,7 @@ DESKTOP_ONLY = {
("Personalization", "ThemeMode"),
("Software", "AutoRun"),
("Software", "ClipboardIgnoredPacks"),
+ ("Software", "ClipboardRequest"),
("Software", "ClipboardListener"),
("Software", "CloseMode"),
("Software", "Geometry"),
diff --git a/tests/test_notice.py b/tests/test_notice.py
index 5f133566..5880c598 100644
--- a/tests/test_notice.py
+++ b/tests/test_notice.py
@@ -13,7 +13,7 @@ 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, NotificationPopup, Popup, PopupNotifier, PopupStack, Presence,
+ SCREEN_MARGIN, SPACING, DoNotDisturb, NotificationPopup, Popup, PopupNotifier, PopupStack,
buildDiskSpaceInsufficient, buildParseFailed, buildTaskCompleted,
)
@@ -32,7 +32,7 @@ def buildNotice(title: str = "下载完成", timeout: int = 60, **kwargs) -> Not
@pytest.fixture
def popupStack(qapp):
- stack = PopupStack(Presence())
+ stack = PopupStack(DoNotDisturb())
yield stack
stack.clear()
@@ -51,7 +51,7 @@ def test_build_task_completed_opens_output(monkeypatch, tmp_path):
notification = buildTaskCompleted(task, None)
- assert notification.message.splitlines() == ["ubuntu.iso", f"5.00 GB · {tmp_path}"]
+ assert notification.message.splitlines() == ["ubuntu.iso", f"大小 5.00 GB,保存于 {tmp_path}"]
for button in notification.buttons:
button.on_pressed()
notification.on_clicked()
@@ -148,6 +148,21 @@ def test_send_beyond_screen_keeps_long_lived_at_bottom(qtbot, popupNotifier):
assert "长驻" not in dismissed
+def test_send_replaces_notice_in_place(qtbot, popupNotifier):
+ dismissed = []
+ popupNotifier.send(buildNotice("进度", timeout=0, on_dismissed=lambda: dismissed.append(True)), "task:1")
+ popupNotifier.send(buildNotice("其他"))
+ qtbot.waitUntil(lambda: len(shownPopups()) == 2 and isSettled())
+ position = next(popup.pos() for popup in shownPopups() if popup.titleLabel.text() == "进度")
+
+ popupNotifier.send(buildNotice("完成", timeout=0), "task:1")
+
+ qtbot.waitUntil(lambda: len(shownPopups()) == 2 and isSettled())
+ finished = next(popup for popup in shownPopups() if popup.titleLabel.text() == "完成")
+ assert finished.pos() == position
+ assert dismissed == []
+
+
def test_add_replacing_takes_position_without_dismissing(qtbot, popupStack):
dismissed = []
old = NotificationPopup(buildNotice("进度", timeout=0, on_dismissed=lambda: dismissed.append(True)))