The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(update): ProgressToast 下载进度反馈
XiaoYouChR74e0190041eb
diff --git a/app/view/components/progress_toast.py b/app/view/components/progress_toast.pynew file mode 100644index 00000000..a517a88e--- /dev/null+++ b/app/view/components/progress_toast.py@@ -0,0 +1,162 @@+from __future__ import annotations++from typing import TYPE_CHECKING++from PySide6.QtCore import QRectF, QSize, QTimer, Qt+from PySide6.QtGui import QColor, QPainter, QPainterPath+from qfluentwidgets import (+ FluentIcon, FluentStyleSheet, InfoBar, InfoBarIcon, InfoBarPosition,+ TransparentToolButton, isDarkTheme,+)++from app.services.update_service import UpdateState++if TYPE_CHECKING:+ from collections.abc import Callable++ from PySide6.QtWidgets import QWidget++ from app.services.update_service import UpdateInfo++BAR_HEIGHT = 3+CORNER_RADIUS = 6+FILL_EASING = 0.25+READY_DISMISS_MS = 5000++COLORS = {+ UpdateState.DOWNLOADING: {"light": QColor("#9D5D00"), "dark": QColor("#FCE100")},+ UpdateState.READY: {"light": QColor("#0F7B0F"), "dark": QColor("#6CCB5F")},+ UpdateState.FAILED: {"light": QColor("#C42B1C"), "dark": QColor("#FF99A4")},+}+++def barColor(state: UpdateState) -> QColor:+ pair = COLORS.get(state, COLORS[UpdateState.DOWNLOADING])+ return pair["dark"] if isDarkTheme() else pair["light"]+++class ProgressToast(InfoBar):++ def __init__(self, onRetry: Callable, parent: QWidget):+ super().__init__(+ icon=InfoBarIcon.WARNING,+ title="",+ content="",+ orient=Qt.Orientation.Horizontal,+ isClosable=True,+ duration=-1,+ position=InfoBarPosition.BOTTOM_RIGHT,+ parent=parent,+ )+ self.setProperty("type", "")+ FluentStyleSheet.INFO_BAR.apply(self)++ self.titleLabel.show()+ self.contentLabel.show()++ self._targetProgress = 0.0+ self._displayProgress = 0.0+ self._barColor = barColor(UpdateState.DOWNLOADING)+ self._isDismissed = False+ self._fillTimer = QTimer(self, interval=16)+ self._fillTimer.timeout.connect(self._onFillTick)+ self._dismissTimer = QTimer(self)+ self._dismissTimer.setSingleShot(True)+ self._dismissTimer.timeout.connect(self.close)++ self._retryButton = TransparentToolButton(FluentIcon.SYNC, self)+ self._retryButton.setFixedSize(36, 36)+ self._retryButton.setIconSize(QSize(12, 12))+ self._retryButton.hide()+ self._retryButton.clicked.connect(onRetry)+ self.widgetLayout.addSpacing(12)+ self.widgetLayout.addWidget(+ self._retryButton, 0, Qt.AlignLeft | Qt.AlignVCenter,+ )++ closeIdx = self.hBoxLayout.indexOf(self.closeButton)+ spacer = self.hBoxLayout.itemAt(closeIdx - 1)+ if spacer and spacer.spacerItem():+ spacer.spacerItem().changeSize(4, 0)++ self.closeButton.clicked.disconnect()+ self.closeButton.clicked.connect(self._onUserClose)++ def setInfo(self, info: UpdateInfo) -> None:+ if info.state == UpdateState.DOWNLOADING:+ if self._isDismissed:+ return+ self._targetProgress = info.progress+ self._barColor = barColor(UpdateState.DOWNLOADING)+ self.iconWidget.icon = InfoBarIcon.WARNING+ self.title = self.tr("正在下载更新")+ self.content = f"{info.latestVersion} ({info.progress:.0f}%)"+ self._retryButton.hide()+ self._stopDismissTimer()+ self._fillTimer.start()+ elif info.state == UpdateState.READY:+ self._isDismissed = False+ self._targetProgress = 100+ self._barColor = barColor(UpdateState.READY)+ self.iconWidget.icon = InfoBarIcon.SUCCESS+ self.title = self.tr("更新已就绪")+ self.content = self.tr("下次启动时生效")+ self._retryButton.hide()+ self._startDismissTimer()+ self._fillTimer.start()+ elif info.state == UpdateState.FAILED:+ self._isDismissed = False+ self._targetProgress = 100+ self._displayProgress = 100+ self._barColor = barColor(UpdateState.FAILED)+ self.iconWidget.icon = InfoBarIcon.ERROR+ self.title = self.tr("下载更新失败")+ self.content = info.error or self.tr("未知错误")+ self._retryButton.show()+ self._stopDismissTimer()+ self._fillTimer.stop()+ else:+ return++ self._adjustText()+ if not self.isVisible():+ self.show()+ self.iconWidget.update()+ self.update()++ def closeEvent(self, e):+ self._fillTimer.stop()+ self.closedSignal.emit()+ self.hide()+ e.ignore()++ def paintEvent(self, e):+ super().paintEvent(e)+ if self._displayProgress <= 0:+ return+ painter = QPainter(self)+ painter.setRenderHint(QPainter.RenderHint.Antialiasing)+ path = QPainterPath()+ path.addRoundedRect(QRectF(self.rect()), CORNER_RADIUS, CORNER_RADIUS)+ painter.setClipPath(path)+ barW = int(self.width() * self._displayProgress / 100)+ painter.fillRect(0, self.height() - BAR_HEIGHT, barW, BAR_HEIGHT, self._barColor)++ def _onFillTick(self):+ diff = self._targetProgress - self._displayProgress+ if abs(diff) < 0.5:+ self._displayProgress = self._targetProgress+ self._fillTimer.stop()+ else:+ self._displayProgress += diff * FILL_EASING+ self.update()++ def _onUserClose(self):+ self._isDismissed = True+ self.close()++ def _startDismissTimer(self):+ self._dismissTimer.start(READY_DISMISS_MS)++ def _stopDismissTimer(self):+ self._dismissTimer.stop()diff --git a/app/view/mobile/window.py b/app/view/mobile/window.pyindex 3e1cad3b..66e2e43c 100644--- a/app/view/mobile/window.py+++ b/app/view/mobile/window.py@@ -34,6 +34,7 @@ class MobileMainWindow(QWidget):self._speedMeter = speedMeterself._coroutineRunner = coroutineRunnerself._updateService = updateService+ self._progressToast = NonesetupAccentColor()self.stackedWidget = QStackedWidget(self)@@ -96,6 +97,8 @@ class MobileMainWindow(QWidget):self.taskPage.selectionModeChanged.connect(lambda *_: self._updateAddButtonVisibility())self.addButton.clicked.connect(self._showAddTaskDialog)self._draft.taskConfirmed.connect(self._taskService.add)+ if self._updateService is not None:+ self._updateService.changed.connect(self._onUpdateChanged)QApplication.instance().applicationStateChanged.connect(self._onApplicationStateChanged)cfg.themeChanged.connect(self._setTheme)QApplication.instance().styleHints().colorSchemeChanged.connect(self._onSystemColorSchemeChanged)@@ -203,6 +206,10 @@ class MobileMainWindow(QWidget):def _onUpdateAvailable(self, info) -> None:from qfluentwidgets import PrimaryPushButton, PushButton+ if self._progressToast is not None:+ self._progressToast.deleteLater()+ self._progressToast = None+infoBar = InfoBar(icon=FluentIcon.CLOUD,title=self.tr("检测到新版本"),@@ -214,13 +221,26 @@ class MobileMainWindow(QWidget):parent=self,)downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, self.tr("立即下载"))- downloadButton.clicked.connect(lambda: self._updateService.download("app"))+ downloadButton.clicked.connect(lambda: (infoBar.close(), self._updateService.download("app")))infoBar.addWidget(downloadButton)detailButton = PushButton(FluentIcon.CHAT, self.tr("查看详情"))detailButton.clicked.connect(self._showReleaseDetails)infoBar.addWidget(detailButton)infoBar.show()+ def _onUpdateChanged(self, info) -> None:+ if info.targetId != "app":+ return+ if info.state not in (UpdateState.DOWNLOADING, UpdateState.READY, UpdateState.FAILED):+ return+ if self._progressToast is None:+ from app.view.components.progress_toast import ProgressToast+ self._progressToast = ProgressToast(+ onRetry=lambda: self._updateService.download("app"),+ parent=self,+ )+ self._progressToast.setInfo(info)+def _showReleaseDetails(self) -> None:from app.models.task import TaskOptionsfrom app.update import fetchReleasediff --git a/app/view/windows/main_window.py b/app/view/windows/main_window.pyindex 9d824c6b..f779c741 100644--- a/app/view/windows/main_window.py+++ b/app/view/windows/main_window.py@@ -97,6 +97,7 @@ class MainWindow(MSFluentWindow):self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)self._pages: dict[str, QWidget] = {}+ self._progressToast = Noneself._draft = TaskDraft(self._coroutineRunner, self._featureService, parent=self)self.searchEdit = SearchLineEdit(self.titleBar)@@ -229,6 +230,9 @@ class MainWindow(MSFluentWindow):from PySide6.QtGui import QKeySequence, QShortcutQShortcut(QKeySequence.StandardKey.Find, self).activated.connect(self._onSearchShortcut)+ if self._updateService is not None:+ self._updateService.changed.connect(self._onUpdateChanged)+if sys.platform == "win32":cfg.backgroundEffect.valueChanged.connect(self._setBackgroundEffectWin)elif sys.platform == "darwin":@@ -290,6 +294,10 @@ class MainWindow(MSFluentWindow):def _onUpdateAvailable(self, info) -> None:from qfluentwidgets import PrimaryPushButton, PushButton+ if self._progressToast is not None:+ self._progressToast.deleteLater()+ self._progressToast = None+infoBar = InfoBar(icon=FluentIcon.CLOUD,title=self.tr("检测到新版本"),@@ -301,7 +309,7 @@ class MainWindow(MSFluentWindow):parent=self,)downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, self.tr("立即下载"))- downloadButton.clicked.connect(lambda: self._updateService.download("app"))+ downloadButton.clicked.connect(lambda: (infoBar.close(), self._updateService.download("app")))infoBar.addWidget(downloadButton)detailButton = PushButton(FluentIcon.CHAT, self.tr("查看详情"))detailButton.clicked.connect(self._showReleaseDetails)@@ -311,6 +319,19 @@ class MainWindow(MSFluentWindow):infoBar.addWidget(sponsorButton)infoBar.show()+ def _onUpdateChanged(self, info) -> None:+ if info.targetId != "app":+ return+ if info.state not in (UpdateState.DOWNLOADING, UpdateState.READY, UpdateState.FAILED):+ return+ if self._progressToast is None:+ from app.view.components.progress_toast import ProgressToast+ self._progressToast = ProgressToast(+ onRetry=lambda: self._updateService.download("app"),+ parent=self,+ )+ self._progressToast.setInfo(info)+def _showReleaseDetails(self) -> None:from app.models.task import TaskOptionsfrom app.update import fetchReleasediff --git a/tools/test_progress_toast.py b/tools/test_progress_toast.pynew file mode 100644index 00000000..42aaefaf--- /dev/null+++ b/tools/test_progress_toast.py@@ -0,0 +1,67 @@+"""Standalone visual test for ProgressToast. Run from project root:+ .venv/bin/python3 tools/test_progress_toast.py+"""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++from PySide6.QtCore import QTimer+from PySide6.QtWidgets import QApplication, QWidget++from app.services.update_service import UpdateInfo, UpdateState+from app.view.components.progress_toast import ProgressToast+++def main():+ app = QApplication(sys.argv)+ window = QWidget()+ window.setFixedSize(800, 500)+ window.setWindowTitle("ProgressToast Test")+ window.show()++ toast = ProgressToast(onRetry=lambda: print("retry clicked"), parent=window)++ progress = [0.0]++ def tick():+ progress[0] += 5+ if progress[0] > 100:+ progress[0] = 100+ info = UpdateInfo(+ targetId="app", label="Ghost Downloader v4.3.0",+ currentVersion="4.2.6", latestVersion="4.3.0",+ state=UpdateState.DOWNLOADING, progress=progress[0],+ )+ toast.setInfo(info)+ if progress[0] < 100:+ QTimer.singleShot(200, tick)+ else:+ QTimer.singleShot(1000, showReady)++ def showReady():+ info = UpdateInfo(+ targetId="app", label="Ghost Downloader v4.3.0",+ currentVersion="4.2.6", latestVersion="4.3.0",+ state=UpdateState.READY,+ )+ toast.setInfo(info)+ QTimer.singleShot(7000, showFailed)++ def showFailed():+ nonlocal toast+ toast.deleteLater()+ toast = ProgressToast(onRetry=lambda: print("retry clicked"), parent=window)+ info = UpdateInfo(+ targetId="app", label="Ghost Downloader v4.3.0",+ currentVersion="4.2.6", latestVersion="4.3.0",+ state=UpdateState.FAILED, error="网络连接超时",+ )+ toast.setInfo(info)++ QTimer.singleShot(500, tick)+ sys.exit(app.exec())+++if __name__ == "__main__":+ main()