Skip to content

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

feat(android): 移动端界面

XiaoYouChRba50f0142d01
diff --git a/app/view/mobile/__init__.py b/app/view/mobile/__init__.py
new file mode 100644
index 00000000..7fa268c5
--- /dev/null
+++ b/app/view/mobile/__init__.py
@@ -0,0 +1 @@
+"""GD4A 移动端 UI —— 平行于桌面 MSFluentWindow 的 MobileMainWindow(QWidget + QStackedWidget + 自建底部导航), 两者不继承也不互相 import。"""
diff --git a/app/view/mobile/add_task_dialog.py b/app/view/mobile/add_task_dialog.py
new file mode 100644
index 00000000..11532787
--- /dev/null
+++ b/app/view/mobile/add_task_dialog.py
@@ -0,0 +1,73 @@
+"""移动端添加任务对话框 —— 把 ParseSettingCard 的右侧控件从单行下移到标题行下方整行铺开, 否则路径框、滑块(min 268px)在手机宽度下溢出右缘被裁。"""
+
+from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget
+from qfluentwidgets import ComboBox, LineEdit, Slider
+
+from app.view.components.add_task_dialog import AddTaskDialog
+from app.view.components.cards import ParseSettingCard
+
+_QWIDGETSIZE_MAX = (1 << 24) - 1
+_STRETCHY = (LineEdit, Slider, ComboBox) # 输入类控件: 在第二行铺满整行
+
+
+class MobileAddTaskDialog(AddTaskDialog):
+
+ def _initWidget(self):
+ super()._initWidget()
+ for card in self.settingGroup.cards:
+ if isinstance(card, ParseSettingCard):
+ _stackParseCardVertically(card)
+
+
+def _stackParseCardVertically(card: ParseSettingCard):
+ controls = _trailingControls(card)
+ if not controls:
+ return
+
+ oldLayout = card.hBoxLayout
+ while oldLayout.count():
+ oldLayout.takeAt(0)
+ QWidget().setLayout(oldLayout) # 腾出 card 以装竖排(一个 widget 同时只能有一个 layout)
+
+ outer = QVBoxLayout(card)
+ outer.setContentsMargins(24, 8, 24, 8)
+ outer.setSpacing(8)
+
+ titleRow = QHBoxLayout()
+ titleRow.setSpacing(12)
+ titleRow.addWidget(card.iconWidget)
+ titleRow.addWidget(card.titleLabel)
+ titleRow.addStretch(1)
+ outer.addLayout(titleRow)
+
+ controlRow = QHBoxLayout()
+ controlRow.setContentsMargins(28, 0, 0, 0) # 与标题文字左缘对齐(图标16 + 间距12)
+ controlRow.setSpacing(8)
+ hasStretchy = False
+ for widget in controls:
+ if isinstance(widget, _STRETCHY):
+ # 解除自带最小宽(如 Slider 写死 268px)再给伸展因子, 否则撑出横向滚动条
+ widget.setMinimumWidth(0)
+ controlRow.addWidget(widget, 1)
+ hasStretchy = True
+ else:
+ controlRow.addWidget(widget, 0)
+ if not hasStretchy:
+ controlRow.addStretch(1)
+ outer.addLayout(controlRow)
+
+ card.setMinimumHeight(0)
+ card.setMaximumHeight(_QWIDGETSIZE_MAX) # 解除组件写死的 setFixedHeight(50)
+
+
+def _trailingControls(card: ParseSettingCard) -> list[QWidget]:
+ """卡片标题之后的右侧控件 widget。"""
+ controls = []
+ afterTitle = False
+ for i in range(card.hBoxLayout.count()):
+ item = card.hBoxLayout.itemAt(i)
+ if item.widget() is card.titleLabel:
+ afterTitle = True
+ elif afterTitle and item.widget() is not None:
+ controls.append(item.widget())
+ return controls
diff --git a/app/view/mobile/cards.py b/app/view/mobile/cards.py
new file mode 100644
index 00000000..9c2c0d0c
--- /dev/null
+++ b/app/view/mobile/cards.py
@@ -0,0 +1,129 @@
+"""移动端任务卡 —— 窄屏呈现抽成 mixin 叠在桌面特性卡上(卡类由 featureService 分发, 动态合成保留各类特性)。"""
+
+from PySide6.QtCore import Qt, QTimer
+from qfluentwidgets import Action, CardWidget, FluentIcon, TransparentToolButton
+
+from app.bases.models import TaskStatus
+from app.supports.android import openFile, openFolder
+
+LONG_PRESS_MS = 450
+
+
+class MobileCardMixin:
+ """窄屏呈现 mixin: 只留 暂停/继续 + ⋮(overflow), 其余动作收进 ⋮ 菜单; tap=打开文件、长按=进多选。"""
+
+ def initLayout(self):
+ self.overflowButton = TransparentToolButton(FluentIcon.MORE, self)
+ # 改走 ⋮ 菜单, 不入布局; 不 hide 会因仍是子控件而停在 (0,0) 露出
+ for widget in (self.verifyHashButton, self.openFileButton, self.openFolderButton, self.cancelButton):
+ widget.hide()
+
+ self.hBoxLayout.addWidget(self.checkBox)
+ self.hBoxLayout.addWidget(self.iconLabel)
+
+ self.infoVBoxLayout.addWidget(self.filenameLabel)
+ self.infoLayout.addWidget(self.speedLabel)
+ self.infoLayout.addWidget(self.progressLabel)
+ self.infoLayout.addWidget(self.infoLabel)
+ self.infoLayout.addStretch()
+ self.infoVBoxLayout.addLayout(self.infoLayout)
+ self.infoVBoxLayout.setContentsMargins(2, 8, 2, 8)
+ self.hBoxLayout.addLayout(self.infoVBoxLayout, 1)
+
+ self.hBoxLayout.addWidget(self.toggleRunningStatusButton)
+ self.hBoxLayout.addWidget(self.overflowButton)
+ self.hBoxLayout.setContentsMargins(12, 0, 12, 0)
+
+ def refreshToggleButton(self):
+ super().refreshToggleButton()
+ self.verifyHashButton.hide() # 完成态基类会 setVisible 它; 校验入口已移到 ⋮ 菜单
+
+ def _renderTaskState(self):
+ super()._renderTaskState()
+ self.leftTimeLabel.hide() # 窄屏挤掉进度文本; 基类会在暂停→运行时重新 show, 故兜底
+
+ def connectSignalToSlot(self):
+ super().connectSignalToSlot()
+ self.overflowButton.clicked.connect(self._showOverflowMenu)
+ self._longPressed = False
+ self._longPressTimer = QTimer(self)
+ self._longPressTimer.setSingleShot(True)
+ self._longPressTimer.setInterval(LONG_PRESS_MS)
+ self._longPressTimer.timeout.connect(self._onLongPress)
+
+ def _appendOverflowActions(self, menu):
+ """子类钩子: 在 ⋮ 菜单的「打开文件」前追加特性专属动作(默认无)。"""
+
+ def _showOverflowMenu(self):
+ menu = self.createContextMenu() # 复制链接/编辑/重下/移动分类
+ menu.addSeparator()
+ self._appendOverflowActions(menu)
+
+ openFileAction = Action(FluentIcon.LINK, self.tr("打开文件"), self)
+ openFileAction.triggered.connect(lambda: openFile(self.task.outputFolder))
+ menu.addAction(openFileAction)
+
+ openFolderAction = Action(FluentIcon.FOLDER, self.tr("打开文件夹"), self)
+ openFolderAction.triggered.connect(lambda: openFolder(self.task.outputFolder))
+ menu.addAction(openFolderAction)
+
+ if self.task.status == TaskStatus.COMPLETED:
+ verifyAction = Action(FluentIcon.FINGERPRINT, self.tr("校验哈希"), self)
+ verifyAction.triggered.connect(self._onVerifyHashButtonClicked)
+ menu.addAction(verifyAction)
+
+ menu.addSeparator()
+ deleteAction = Action(FluentIcon.DELETE, self.tr("删除"), self)
+ deleteAction.triggered.connect(self._onDeleteButtonClicked)
+ menu.addAction(deleteAction)
+
+ menu.exec(self.overflowButton.mapToGlobal(self.overflowButton.rect().bottomLeft()))
+
+ def mousePressEvent(self, e):
+ super().mousePressEvent(e)
+ if e.button() == Qt.MouseButton.LeftButton:
+ self._longPressed = False
+ self._longPressTimer.start()
+
+ def mouseReleaseEvent(self, e):
+ # 跳过 TaskCard.mouseReleaseEvent 的「单击即选中」桌面语义,保留 CardWidget 的按压动画
+ CardWidget.mouseReleaseEvent(self, e)
+ self._longPressTimer.stop()
+ if e.button() != Qt.MouseButton.LeftButton or self._longPressed:
+ return
+ if self.isSelectionMode:
+ self.selectionChanged.emit(not self.isChecked(), False)
+ else:
+ openFile(self.task.outputFolder)
+
+ def mouseDoubleClickEvent(self, e):
+ pass # 移动端无双击;屏蔽桌面的双击打开文件夹
+
+ def _onLongPress(self):
+ self._longPressed = True
+ if self.isSelectionMode:
+ self.selectionChanged.emit(not self.isChecked(), False)
+ else:
+ self.selectionChanged.emit(True, False)
+
+
+class MobileFtpMixin:
+ """FTP 卡的移动端特化: 把桌面的「选择文件」按钮收进 ⋮ 菜单(窄屏布局里它落在边缘)。"""
+
+ def __init__(self, task, parent=None):
+ super().__init__(task, parent)
+ self.selectFilesButton.hide()
+
+ def refresh(self):
+ super().refresh()
+ # FtpTaskCard.refresh 会按 countAll 重新 show 这俩, 兜底隐藏(已移入 ⋮ 菜单)
+ self.selectFilesButton.hide()
+ self.verifyHashButton.hide()
+
+ def _appendOverflowActions(self, menu):
+ if self.task.countAll <= 1:
+ return
+ selectFilesAction = Action(FluentIcon.LIBRARY, self.tr("选择文件"), self)
+ selectFilesAction.setEnabled(self.task.status != TaskStatus.RUNNING)
+ selectFilesAction.triggered.connect(self._onSelectFilesClicked)
+ menu.addAction(selectFilesAction)
diff --git a/app/view/mobile/navigation.py b/app/view/mobile/navigation.py
new file mode 100644
index 00000000..56921628
--- /dev/null
+++ b/app/view/mobile/navigation.py
@@ -0,0 +1,117 @@
+"""移动端底部导航 —— 自建 icon-over-text 标签栏: QFluentWidgets 的 NavigationBarPushButton 为左侧竖栏设计, 平铺成全宽底栏不居中。"""
+
+from PySide6.QtCore import Qt, Signal
+from PySide6.QtGui import QColor, QPainter
+from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout
+from qfluentwidgets import CaptionLabel, FluentIcon, IconWidget, isDarkTheme, qconfig, themeColor
+
+NAV_BAR_HEIGHT = 58
+NAV_ICON_SIZE = 24
+
+
+class NavigationButton(QWidget):
+ """底部导航单项: 图标在上、文字在下, 选中态染主题色。"""
+
+ clicked = Signal()
+
+ def __init__(self, icon: FluentIcon, text: str, parent: QWidget | None = None):
+ super().__init__(parent)
+ self._icon = icon
+ self._isSelected = False
+ self.iconWidget = IconWidget(icon, self)
+ self.label = CaptionLabel(text, self)
+ self.vBoxLayout = QVBoxLayout(self)
+ self._initWidget()
+ self._initLayout()
+
+ def _initWidget(self):
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
+ self.iconWidget.setFixedSize(NAV_ICON_SIZE, NAV_ICON_SIZE)
+ self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
+ self._updateColors()
+
+ def _initLayout(self):
+ self.vBoxLayout.setContentsMargins(0, 8, 0, 6)
+ self.vBoxLayout.setSpacing(3)
+ self.vBoxLayout.addWidget(self.iconWidget, 0, Qt.AlignmentFlag.AlignHCenter)
+ self.vBoxLayout.addWidget(self.label, 0, Qt.AlignmentFlag.AlignHCenter)
+
+ def setSelected(self, isSelected: bool):
+ if self._isSelected == isSelected:
+ return
+ self._isSelected = isSelected
+ self._updateColors()
+
+ def _updateColors(self):
+ if self._isSelected:
+ color = themeColor()
+ self.iconWidget.setIcon(self._icon.colored(color, color))
+ self.label.setTextColor(color, color)
+ else:
+ self.iconWidget.setIcon(self._icon)
+ self.label.setTextColor(QColor(96, 96, 96), QColor(206, 206, 206))
+
+ def mouseReleaseEvent(self, event):
+ super().mouseReleaseEvent(event)
+ if event.button() == Qt.MouseButton.LeftButton and self.rect().contains(event.position().toPoint()):
+ self.clicked.emit()
+
+
+class BottomNavigationBar(QWidget):
+ """底部标签栏: 平铺若干 NavigationButton, 互斥选中, 切换时发 currentChanged(index)。"""
+
+ currentChanged = Signal(int)
+
+ def __init__(self, parent: QWidget | None = None):
+ super().__init__(parent)
+ self._buttons: list[NavigationButton] = []
+ self._currentIndex = -1
+ self.hBoxLayout = QHBoxLayout(self)
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+
+ def _initWidget(self):
+ self.setFixedHeight(NAV_BAR_HEIGHT)
+
+ def _initLayout(self):
+ self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
+ self.hBoxLayout.setSpacing(0)
+
+ def _bind(self):
+ qconfig.themeChanged.connect(self._onThemeChanged)
+
+ def addItem(self, icon: FluentIcon, text: str) -> int:
+ index = len(self._buttons)
+ button = NavigationButton(icon, text, self)
+ button.clicked.connect(lambda checked=False, i=index: self.setCurrentIndex(i))
+ self._buttons.append(button)
+ self.hBoxLayout.addWidget(button, 1)
+ if index == 0:
+ self._currentIndex = 0
+ button.setSelected(True)
+ return index
+
+ def setCurrentIndex(self, index: int):
+ if index == self._currentIndex or not 0 <= index < len(self._buttons):
+ return
+ self._currentIndex = index
+ for i, button in enumerate(self._buttons):
+ button.setSelected(i == index)
+ self.currentChanged.emit(index)
+
+ def _onThemeChanged(self):
+ for button in self._buttons:
+ button._updateColors()
+
+ def paintEvent(self, event):
+ painter = QPainter(self)
+ if isDarkTheme():
+ background = QColor(39, 39, 39)
+ divider = QColor(255, 255, 255, 18)
+ else:
+ background = QColor(243, 243, 243)
+ divider = QColor(0, 0, 0, 18)
+ painter.fillRect(self.rect(), background)
+ painter.setPen(divider)
+ painter.drawLine(0, 0, self.width(), 0)
diff --git a/app/view/mobile/permission.py b/app/view/mobile/permission.py
new file mode 100644
index 00000000..de4c266e
--- /dev/null
+++ b/app/view/mobile/permission.py
@@ -0,0 +1,41 @@
+"""存储权限软门横幅 —— Android 11+ 的 MANAGE_EXTERNAL_STORAGE 无运行时弹窗, 只能 Intent 跳设置页, 故未授权时常驻任务页顶部引导授权。"""
+
+from collections.abc import Callable
+
+from PySide6.QtCore import Qt
+from PySide6.QtGui import QColor, QPainter
+from PySide6.QtWidgets import QHBoxLayout, QWidget
+from qfluentwidgets import BodyLabel, FluentIcon, IconWidget, PrimaryPushButton, isDarkTheme
+
+
+class PermissionBanner(QWidget):
+
+ def __init__(self, onGrant: Callable[[], None], parent: QWidget | None = None):
+ super().__init__(parent)
+ self._onGrant = onGrant
+ self.iconWidget = IconWidget(FluentIcon.INFO, self)
+ self.label = BodyLabel(self.tr("未授予「所有文件访问」,下载到公共目录将失败"), self)
+ self.grantButton = PrimaryPushButton(self.tr("去授权"), self)
+ self.hBoxLayout = QHBoxLayout(self)
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+
+ def _initWidget(self):
+ self.setFixedHeight(48)
+ self.iconWidget.setFixedSize(18, 18)
+ self.label.setWordWrap(False)
+
+ def _initLayout(self):
+ self.hBoxLayout.setContentsMargins(16, 0, 12, 0)
+ self.hBoxLayout.setSpacing(10)
+ self.hBoxLayout.addWidget(self.iconWidget)
+ self.hBoxLayout.addWidget(self.label, 1)
+ self.hBoxLayout.addWidget(self.grantButton)
+
+ def _bind(self):
+ self.grantButton.clicked.connect(lambda: self._onGrant())
+
+ def paintEvent(self, event):
+ painter = QPainter(self)
+ painter.fillRect(self.rect(), QColor(66, 54, 20) if isDarkTheme() else QColor(255, 244, 206))
diff --git a/app/view/mobile/setting_page.py b/app/view/mobile/setting_page.py
new file mode 100644
index 00000000..6d55da06
--- /dev/null
+++ b/app/view/mobile/setting_page.py
@@ -0,0 +1,99 @@
+"""移动端设置页 —— 桌面横排设置卡的右侧控件在窄屏溢出, 改成标题行 + 控件整行铺开的竖排(只动扁平 SettingCard)。"""
+
+from PySide6.QtCore import Qt
+from PySide6.QtGui import QColor, QPalette
+from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget
+from qfluentwidgets import SettingCard, SwitchButton, isDarkTheme, qconfig
+
+from app.view.components.setting_card_group import CollapsibleSettingCardGroup
+from app.view.pages.setting_page import SettingPage
+
+_QWIDGETSIZE_MAX = (1 << 24) - 1 # 解除组件 setFixedHeight 后用作高度上限
+
+
+class MobileSettingPage(SettingPage):
+
+ def __init__(self, parent=None):
+ super().__init__(parent)
+ self._makeScrollContentOpaque()
+
+ def showEvent(self, event):
+ self._applyOpaqueBackground() # 每次显示按当前主题重刷: 兜住 Android 启动时序下容器底漏刷为浅色
+ super().showEvent(event)
+
+ def _makeScrollContentOpaque(self):
+ """容器改不透明(autoFillBackground+palette), 否则半透明容器滚动时无法 blit、Qt 每帧全量重绘致卡顿。
+
+ 不走 stylesheet+WA_OpaquePaintEvent: 普通 QWidget 不设 WA_StyledBackground 时 stylesheet 底不绘制, 会留黑底。
+ """
+ self.container.setStyleSheet("") # 去掉 qfluentwidgets 的 QWidget{transparent}: 它会盖过 autofill
+ self.container.setAutoFillBackground(True)
+ self._applyOpaqueBackground()
+ qconfig.themeChanged.connect(self._applyOpaqueBackground)
+
+ def _applyOpaqueBackground(self):
+ palette = self.container.palette()
+ palette.setColor( # 与主窗 paintEvent 同色, 衔接无缝
+ QPalette.ColorRole.Window,
+ QColor(32, 32, 32) if isDarkTheme() else QColor(243, 243, 243),
+ )
+ self.container.setPalette(palette)
+
+ def addSettingGroup(self, group: CollapsibleSettingCardGroup):
+ for i in range(group.cardLayout.count()):
+ card = group.cardLayout.itemAt(i).widget()
+ if isinstance(card, SettingCard):
+ self._stackCardVertically(card)
+ super().addSettingGroup(group)
+
+ def _stackCardVertically(self, card: SettingCard):
+ if getattr(card, "_mobileStacked", False):
+ return
+
+ controls = self._trailingControls(card)
+ if not controls:
+ return # 纯标题卡(如分组占位), 无右侧控件
+ if len(controls) == 1 and isinstance(controls[0], SwitchButton):
+ return # 开关卡: 标题左 / 开关右 已是移动端理想形态
+
+ # 一个 QWidget 只能装一个 layout: 清空旧横排并把它卸到临时 widget, 腾出 card 装竖排
+ oldLayout = card.hBoxLayout
+ while oldLayout.count():
+ oldLayout.takeAt(0)
+ QWidget().setLayout(oldLayout)
+
+ outer = QVBoxLayout(card)
+ outer.setContentsMargins(16, 10, 16, 10)
+ outer.setSpacing(8)
+
+ titleRow = QHBoxLayout()
+ titleRow.setSpacing(0)
+ titleRow.addWidget(card.iconLabel, 0, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
+ titleRow.addSpacing(16)
+ titleRow.addLayout(card.vBoxLayout, 1) # 标题/描述块铺满整行, 省略号空间更足
+ outer.addLayout(titleRow)
+
+ controlRow = QHBoxLayout()
+ controlRow.setContentsMargins(32, 0, 0, 0) # 与标题文字左缘对齐(图标16 + 间距16)
+ controlRow.setSpacing(8)
+ for widget in controls:
+ controlRow.addWidget(widget)
+ controlRow.addStretch(1)
+ outer.addLayout(controlRow)
+
+ # 解除组件写死的 setFixedHeight(70/50), 让卡片高度跟随两行内容
+ card.setMinimumHeight(0)
+ card.setMaximumHeight(_QWIDGETSIZE_MAX)
+ card._mobileStacked = True
+
+ def _trailingControls(self, card: SettingCard) -> list[QWidget]:
+ """卡片标题块(vBoxLayout)之后的右侧控件 widget。"""
+ controls = []
+ afterTitle = False
+ for i in range(card.hBoxLayout.count()):
+ item = card.hBoxLayout.itemAt(i)
+ if item.layout() is card.vBoxLayout:
+ afterTitle = True
+ elif afterTitle and item.widget() is not None:
+ controls.append(item.widget())
+ return controls
diff --git a/app/view/mobile/setup.py b/app/view/mobile/setup.py
new file mode 100644
index 00000000..b7ce2f2f
--- /dev/null
+++ b/app/view/mobile/setup.py
@@ -0,0 +1,193 @@
+"""移动端平台差异注入 —— 函数而非类, 在 main.py 构造后调用, 不改共享文件。"""
+
+
+def setupSystemTheme() -> None:
+ import darkdetect
+ from qfluentwidgets import setTheme
+
+ from app.supports.android import isSystemDark
+ from app.supports.config import cfg, toQFluentTheme
+
+ def themeName() -> str:
+ return "Dark" if isSystemDark() else "Light"
+
+ # darkdetect 在 Android 无后端(恒 None → 主题永远浅色), 桥到 uiMode 让 Theme.AUTO 解析正确
+ darkdetect.theme = themeName
+ darkdetect.isDark = isSystemDark
+ setTheme(toQFluentTheme(cfg.customThemeMode.value), save=False)
+
+
+def setupSystemFont() -> None:
+ """探测并启用 OEM 系统字体, 否则 Android 上 qfluentwidgets 默认族缺失会回退到 Roboto。须在建 widget 前调用。"""
+ from pathlib import Path
+
+ from loguru import logger
+ from PySide6.QtGui import QFontDatabase
+ from qfluentwidgets import qconfig
+
+ # 各 OEM 默认字体: 已收录直接用, 否则加载文件取族名
+ candidates = [
+ ("MiSans VF", "/system/fonts/MiSansVF.ttf"),
+ ("MiSans", "/system/fonts/MiSans-Regular.ttf"),
+ ("OPPO Sans", "/system/fonts/OPPOSans.ttf"),
+ ("OplusSans", "/system/fonts/OplusSans3.0.ttf"),
+ ("HarmonyOS Sans SC", "/system/fonts/HarmonyOS_Sans_SC_Regular.ttf"),
+ ("vivo Sans", "/system/fonts/VivoFont.ttf"),
+ ]
+ families = set(QFontDatabase.families())
+
+ picked = None
+ for name, path in candidates:
+ if name in families:
+ picked = name
+ break
+ if Path(path).exists():
+ loaded = QFontDatabase.applicationFontFamilies(QFontDatabase.addApplicationFont(path))
+ if loaded:
+ picked = loaded[0]
+ break
+
+ logger.info("系统字体: {}", picked or "Roboto(未识别 OEM 字体, 回退)")
+ qconfig.set(qconfig.fontFamilies, [picked, "sans-serif"] if picked else ["sans-serif"], save=False)
+
+
+def setupFluentIconRendering() -> None:
+ # qsvg 插件 W^X 下 dlopen 不了 → 图标全空白; 改走 QSvgRenderer。须同 patch FluentIconBase.icon 与 Icon(菜单经 Icon 持图标)
+ from PySide6.QtGui import QColor, QIcon
+ from qfluentwidgets import Theme
+ from qfluentwidgets.common.icon import FluentIconBase, Icon, SvgIconEngine, writeSvg
+
+ def svgBackedIcon(path: str, color=None) -> QIcon:
+ if not path.endswith(".svg"):
+ return QIcon(path)
+ svg = writeSvg(path, fill=QColor(color).name()) if color else writeSvg(path)
+ return QIcon(SvgIconEngine(svg))
+
+ def toSvgRendererIcon(self, theme=Theme.AUTO, color=None) -> QIcon:
+ return svgBackedIcon(self.path(theme), color)
+
+ def toSvgRendererIconObject(self, fluentIcon) -> None:
+ QIcon.__init__(self, svgBackedIcon(fluentIcon.path()))
+ self.fluentIcon = fluentIcon
+
+ FluentIconBase.icon = toSvgRendererIcon
+ Icon.__init__ = toSvgRendererIconObject
+
+
+def setupNativeDialogPaths() -> None:
+ """把 SAF 选择器返回的 content:// URI 转回真实路径 —— 本应用基于真实路径写公共目录(MANAGE_EXTERNAL_STORAGE)。"""
+ from urllib.parse import unquote
+
+ from PySide6.QtWidgets import QFileDialog
+
+ def toRealPath(uri: str) -> str:
+ if not uri:
+ return uri
+ if uri.startswith("file://"):
+ return unquote(uri[len("file://"):])
+ if not uri.startswith("content://"):
+ return uri
+ for marker in ("/tree/", "/document/"):
+ index = uri.find(marker)
+ if index < 0:
+ continue
+ documentId = unquote(uri[index + len(marker):]) # primary:Tencent/MobileQQ
+ volume, separator, relative = documentId.partition(":")
+ if not separator:
+ return uri
+ base = "/storage/emulated/0" if volume == "primary" else f"/storage/{volume}"
+ return f"{base}/{relative}" if relative else base
+ return uri
+
+ originalDirectory = QFileDialog.getExistingDirectory
+ originalOpenFiles = QFileDialog.getOpenFileNames
+
+ def resolveExistingDirectory(*args, **kwargs) -> str:
+ return toRealPath(originalDirectory(*args, **kwargs))
+
+ def resolveOpenFileNames(*args, **kwargs):
+ paths, selectedFilter = originalOpenFiles(*args, **kwargs)
+ return [toRealPath(path) for path in paths], selectedFilter
+
+ QFileDialog.getExistingDirectory = staticmethod(resolveExistingDirectory)
+ QFileDialog.getOpenFileNames = staticmethod(resolveOpenFileNames)
+
+
+def setupMobileDialogWidth() -> None:
+ """把 MessageBoxBase 对话框宽度封顶到窗内 —— 桌面写死的固定宽在手机会溢出屏幕。"""
+ from qfluentwidgets import MessageBoxBase
+
+ originalShowEvent = MessageBoxBase.showEvent
+
+ def cappedShowEvent(self, e):
+ parent = self.parent()
+ if parent is not None:
+ cap = parent.width() - 24
+ if 0 < cap < self.widget.width():
+ self.widget.setFixedWidth(cap)
+ originalShowEvent(self, e)
+
+ MessageBoxBase.showEvent = cappedShowEvent
+
+
+def setupCollapsibleGroupTouch() -> None:
+ """设置分组头部的展开/收起从按下改到松手 —— 否则触屏滑动按在头部会误触(ScrollClickGuard 只吞 release)。"""
+ from PySide6.QtCore import Qt
+ from PySide6.QtWidgets import QWidget
+
+ from app.view.components.setting_card_group import CollapsibleSettingCardGroup
+
+ def mousePressEvent(self, event) -> None:
+ self._headerPressed = (
+ event.button() == Qt.MouseButton.LeftButton
+ and event.position().y() < self.cardContainer.geometry().top()
+ )
+ QWidget.mousePressEvent(self, event) # 跳过原 toggle, 仅走默认
+
+ def mouseReleaseEvent(self, event) -> None:
+ if getattr(self, "_headerPressed", False) and event.button() == Qt.MouseButton.LeftButton:
+ self._onExpandButtonClicked()
+ self._headerPressed = False
+ QWidget.mouseReleaseEvent(self, event)
+
+ CollapsibleSettingCardGroup.mousePressEvent = mousePressEvent
+ CollapsibleSettingCardGroup.mouseReleaseEvent = mouseReleaseEvent
+
+
+def setupTouchScrolling(window) -> None:
+ """QScroller 触摸手势 + 滑动吞点击守卫(Qt Widgets 在 Android 默认无惯性甩动); 跳过 ExpandSettingCard(随页整体滚)。"""
+ from PySide6.QtCore import QEvent, QObject, Qt
+ from PySide6.QtWidgets import QAbstractScrollArea, QScroller, QScrollerProperties, QWidget
+ from qfluentwidgets.components.settings.expand_setting_card import ExpandSettingCard
+
+ class ScrollClickGuard(QObject):
+ """松手位置离按下位置超阈值即判为滑动, 吞掉 MouseButtonRelease, 避免触屏滑动误触点击。"""
+
+ def __init__(self, parent):
+ super().__init__(parent)
+ self._pressPosition = None
+
+ def eventFilter(self, obj, event) -> bool:
+ eventType = event.type()
+ if eventType == QEvent.Type.MouseButtonPress:
+ self._pressPosition = event.globalPosition().toPoint()
+ elif eventType == QEvent.Type.MouseButtonRelease and self._pressPosition is not None:
+ moved = (event.globalPosition().toPoint() - self._pressPosition).manhattanLength()
+ self._pressPosition = None
+ if moved > 12:
+ return True
+ return False
+
+ guard = ScrollClickGuard(window)
+ for scrollArea in window.findChildren(QAbstractScrollArea):
+ if isinstance(scrollArea, ExpandSettingCard):
+ continue
+ QScroller.grabGesture(scrollArea.viewport(), QScroller.ScrollerGestureType.TouchGesture)
+ scroller = QScroller.scroller(scrollArea.viewport())
+ properties = scroller.scrollerProperties()
+ noOvershoot = QScrollerProperties.OvershootPolicy.OvershootAlwaysOff # 禁用滑到边缘的橡皮筋回弹
+ properties.setScrollMetric(QScrollerProperties.ScrollMetric.VerticalOvershootPolicy, noOvershoot)
+ properties.setScrollMetric(QScrollerProperties.ScrollMetric.HorizontalOvershootPolicy, noOvershoot)
+ scroller.setScrollerProperties(properties)
+ for child in scrollArea.findChildren(QWidget):
+ child.installEventFilter(guard)
diff --git a/app/view/mobile/task_page.py b/app/view/mobile/task_page.py
new file mode 100644
index 00000000..2c1ad088
--- /dev/null
+++ b/app/view/mobile/task_page.py
@@ -0,0 +1,112 @@
+"""移动端任务页 —— 子类化 TaskPage: 挂载卡片套窄屏 mixin、头部单行工具栏(min 795px)拆两行、多选命令栏压进屏内。"""
+
+from PySide6.QtCore import Qt
+from PySide6.QtWidgets import QHBoxLayout, QWidget
+from qfluentwidgets import FluentIcon, PrimaryToolButton, ToolButton
+
+from app.bases.models import Task
+from app.services.feature_service import featureService
+from app.view.components.cards import TaskCard
+from app.view.mobile.cards import MobileCardMixin, MobileFtpMixin
+from app.view.pages.task_page import TaskPage
+
+
+class MobileTaskPage(TaskPage):
+
+ def __init__(self, parent=None, onSelectionModeChanged=None):
+ self._cardClassCache: dict[type, type] = {}
+ self._onSelectionModeChanged = onSelectionModeChanged
+ super().__init__(parent)
+
+ def setSelectionMode(self, enter: bool):
+ super().setSelectionMode(enter)
+ # 多选命令栏与右下 FAB 撞位, 据多选态收 FAB
+ if self._onSelectionModeChanged is not None:
+ self._onSelectionModeChanged()
+
+ def _initWidget(self):
+ super()._initWidget()
+ self.toolBar2 = QWidget(self)
+ self.toolBar2Layout = QHBoxLayout(self.toolBar2)
+ self.setViewportMargins(0, 104, 0, 0)
+
+ # 换图标化 ToolButton(PushButton 清文字后图标渲染不全); 须在基类 _bind 前替换
+ for old in (self.allStartButton, self.allPauseButton):
+ old.hide() # deleteLater 异步, 不先 hide 旧按钮会暂留 (0,0) 被绘制
+ old.deleteLater()
+ self.allStartButton = PrimaryToolButton(FluentIcon.PLAY, self)
+ self.allPauseButton = ToolButton(FluentIcon.PAUSE, self)
+ self.allStartButton.setToolTip(self.tr("全部开始"))
+ self.allPauseButton.setToolTip(self.tr("全部暂停"))
+
+ self.selectButton.hide() # 移动端长按进多选, 砍掉桌面「选择」按钮
+
+ def _initLayout(self):
+ self.vBoxLayout.setSpacing(6)
+ self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
+ self.vBoxLayout.addWidget(self.toolBar)
+ self.vBoxLayout.addWidget(self.toolBar2)
+
+ self.toolBarLayout.setContentsMargins(10, 4, 10, 0)
+ self.toolBarLayout.setSpacing(6)
+ self.toolBarLayout.addWidget(self.allStartButton)
+ self.toolBarLayout.addWidget(self.allPauseButton)
+ self.toolBarLayout.addWidget(self.speedBadge)
+ self.toolBarLayout.addStretch(1)
+ self.toolBarLayout.addWidget(self.rateLimitButton)
+ self.toolBarLayout.addWidget(self.planButton)
+
+ self.toolBar2Layout.setContentsMargins(10, 0, 10, 4)
+ self.toolBar2Layout.setSpacing(6)
+ self.toolBar2Layout.addWidget(self.sortButton)
+ self.toolBar2Layout.addWidget(self.filterButton)
+ self.toolBar2Layout.addWidget(self.categoryFilterButton)
+ self.toolBar2Layout.addWidget(self.searchLineEdit, 1)
+
+ self.searchLineEdit.setMinimumWidth(0)
+ self.searchLineEdit.setMaximumWidth(16777215)
+
+ def resizeEvent(self, event):
+ self._fitCommandView() # 先按当前页宽收窄多选命令栏, 再让基类按其新宽居中摆放
+ super().resizeEvent(event)
+
+ def _fitCommandView(self):
+ """把多选命令栏宽度改设成 页宽-边距, 触发 CommandBar 把放不下的动作折进「⋯」菜单; 桌面按全宽固定了 bar, 窄屏会超出屏幕。"""
+ bar = self.commandView.bar
+ margin = 12 # CommandBarView hBoxLayout 左右各 6
+ cap = max(self.width() - 24 - margin, bar.moreButton.width())
+ width = min(bar.suitableWidth(), cap)
+ bar.setFixedWidth(width)
+ self.commandView.setFixedWidth(width + margin)
+
+ def _mobileCardClass(self, task: Task) -> type:
+ """取 task 对应的桌面卡类(探针构造一次拿到), 套上窄屏 mixin, 按 Task 子类缓存; 复用 featureService 分发而非硬编码一种卡, 否则各任务类型丢特性。"""
+ taskType = type(task)
+ cached = self._cardClassCache.get(taskType)
+ if cached is not None:
+ return cached
+
+ probe = featureService.taskCard(task, None)
+ baseClass = type(probe)
+ probe.deleteLater()
+ mixins = (MobileFtpMixin, MobileCardMixin) if task.packId == "ftp" else (MobileCardMixin,)
+ mobileClass = type(f"Mobile{baseClass.__name__}", (*mixins, baseClass), {})
+
+ self._cardClassCache[taskType] = mobileClass
+ return mobileClass
+
+ def _mountCard(self, task: Task) -> TaskCard:
+ card = self._mobileCardClass(task)(task, self.container)
+ card.finished.connect(self._onCardFinished)
+ card.selectionChanged.connect(
+ lambda checked, extend, t=task: self._onCardSelectionChanged(t, checked, extend)
+ )
+ card.categoryChanged.connect(self._refreshTaskList)
+ card.show()
+ self.mountedCards[task.taskId] = card
+
+ if self.isSelectionMode:
+ card.setSelectionMode(True)
+ if task.taskId in self.selectedIds:
+ card.setChecked(True)
+ return card
diff --git a/app/view/mobile/window.py b/app/view/mobile/window.py
new file mode 100644
index 00000000..386cec7d
--- /dev/null
+++ b/app/view/mobile/window.py
@@ -0,0 +1,180 @@
+"""移动端主窗口 —— QWidget 壳, 不继承 MainWindow/MSFluentWindow(后者锁死左侧竖栏), 用 QStackedWidget + 自建底部导航。"""
+
+from pathlib import Path
+
+from PySide6.QtCore import QSize, Qt
+from PySide6.QtGui import QColor, QIcon, QPainter, QPalette
+from PySide6.QtWidgets import QApplication, QStackedWidget, QVBoxLayout, QWidget
+from loguru import logger
+from qfluentwidgets import (
+ FluentIcon,
+ InfoBar,
+ InfoBarPosition,
+ PrimaryToolButton,
+ Theme,
+ isDarkTheme,
+ qconfig,
+ setTheme,
+ setThemeColor,
+)
+
+from app.services.browser_service import BrowserService
+from app.services.category_service import categoryService
+from app.services.core_service import coreService
+from app.services.task_service import taskService
+from app.supports.android import isStorageGranted, requestStoragePermission
+from app.supports.config import cfg, toQFluentTheme
+from app.supports.utils import deduplicateFilename
+from app.view.components.labels import IconBodyLabel
+from app.view.mobile.navigation import BottomNavigationBar
+from app.view.mobile.permission import PermissionBanner
+from app.view.mobile.setting_page import MobileSettingPage
+from app.view.mobile.task_page import MobileTaskPage
+
+
+class MobileMainWindow(QWidget):
+
+ def __init__(self):
+ super().__init__(parent=None)
+ self.updateThemeColor()
+ BrowserService.initialize(self) # SettingPage 建页要读 pairToken, 须先就绪
+ self.stackedWidget = QStackedWidget(self)
+ self.navigationBar = BottomNavigationBar(self)
+ self.vBoxLayout = QVBoxLayout(self)
+ self.permissionBanner = PermissionBanner(requestStoragePermission, self)
+ self.taskPage = MobileTaskPage(self, onSelectionModeChanged=self._refreshAddButton)
+ self.settingPage = MobileSettingPage(self)
+ self.addButton = PrimaryToolButton(FluentIcon.ADD, self)
+ self._initWidget()
+ self._initLayout()
+ self._bind()
+ self._refreshPermissionGate()
+
+ def _initWidget(self):
+ self.setObjectName("MobileMainWindow")
+ self.setWindowIcon(QIcon(":/image/logo.png"))
+ self.setWindowTitle("Ghost Downloader")
+ self.taskPage.setObjectName("taskInterface")
+ self.settingPage.setObjectName("settingInterface")
+ self.addButton.setFixedSize(56, 56)
+ self.addButton.setIconSize(QSize(22, 22))
+ self.addButton.raise_()
+ self.addSubInterface(self.taskPage, FluentIcon.DOWNLOAD, self.tr("任务"))
+ self.addSubInterface(self.settingPage, FluentIcon.SETTING, self.tr("设置"))
+
+ def _initLayout(self):
+ self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
+ self.vBoxLayout.setSpacing(0)
+ self.vBoxLayout.addWidget(self.permissionBanner, 0)
+ self.vBoxLayout.addWidget(self.stackedWidget, 1)
+ self.vBoxLayout.addWidget(self.navigationBar, 0)
+
+ def _bind(self):
+ self.navigationBar.currentChanged.connect(self.stackedWidget.setCurrentIndex)
+ self.navigationBar.currentChanged.connect(lambda *_: self._refreshAddButton())
+ self.addButton.clicked.connect(self.showAddTaskDialog)
+ QApplication.instance().applicationStateChanged.connect(self._onApplicationStateChanged)
+ cfg.customThemeMode.valueChanged.connect(self._onThemeModeChanged)
+ QApplication.instance().styleHints().colorSchemeChanged.connect(self._onSystemColorSchemeChanged)
+ qconfig.themeChanged.connect(self.update)
+ qconfig.themeChanged.connect(lambda *_: IconBodyLabel.clearCache()) # 缓存按 id 不分主题, 切主题须清否则图标留旧色
+
+ def _onThemeModeChanged(self, mode: str):
+ setTheme(toQFluentTheme(mode), save=False)
+
+ def _onSystemColorSchemeChanged(self, colorScheme: Qt.ColorScheme):
+ if cfg.customThemeMode.value != "System":
+ return
+ if colorScheme == Qt.ColorScheme.Dark:
+ setTheme(Theme.DARK, save=False)
+ elif colorScheme == Qt.ColorScheme.Light:
+ setTheme(Theme.LIGHT, save=False)
+ else:
+ setTheme(Theme.AUTO, save=False)
+
+ def _onApplicationStateChanged(self, state: Qt.ApplicationState):
+ # onResume 复检权限, 收起 banner
+ if state == Qt.ApplicationState.ApplicationActive:
+ self._refreshPermissionGate()
+
+ def _refreshPermissionGate(self):
+ self.permissionBanner.setVisible(not isStorageGranted())
+
+ def _refreshAddButton(self):
+ # FAB 仅任务页且非多选时露面, 否则与右下多选命令栏撞位
+ onTaskPage = self.stackedWidget.currentIndex() == 0
+ self.addButton.setVisible(onTaskPage and not self.taskPage.isSelectionMode)
+
+ def addSubInterface(self, interface: QWidget, icon: FluentIcon, text: str) -> QWidget:
+ self.stackedWidget.addWidget(interface)
+ self.navigationBar.addItem(icon, text)
+ return interface
+
+ def showAddTaskDialog(self):
+ if not isStorageGranted(): # 软门: 未授权拦截新建, 跳设置页引导
+ requestStoragePermission()
+ InfoBar.warning(
+ self.tr("需要存储权限"),
+ self.tr("请在系统设置授予「所有文件访问」后再新建任务"),
+ duration=4000,
+ position=InfoBarPosition.TOP,
+ parent=self,
+ )
+ return
+
+ from app.view.mobile.add_task_dialog import MobileAddTaskDialog
+
+ dialog = MobileAddTaskDialog.initialize(self)
+ # 桌面固定 700px 在手机会溢出, 压到窗宽内
+ dialog.widget.setFixedWidth(min(700, self.width() - 24))
+ if dialog.isVisible() and not dialog.isStandaloneMode:
+ dialog.raise_()
+ dialog.activateWindow()
+ return
+ dialog.showMask()
+
+ def resizeEvent(self, event):
+ super().resizeEvent(event)
+ margin = 16
+ self.addButton.move(
+ self.width() - self.addButton.width() - margin,
+ self.height() - self.navigationBar.height() - self.addButton.height() - margin,
+ )
+
+ def addTask(self, task) -> bool:
+ try:
+ if (
+ cfg.enableCategory.value
+ and task.category
+ and task.path == Path(cfg.downloadFolder.value)
+ ):
+ folder = categoryService.folderOf(task.category)
+ if folder:
+ task.applySettings({"path": Path(folder)})
+
+ originalTitle = task.title
+ if deduplicateFilename(task):
+ logger.info("检测到重名文件,已自动重命名 {} -> {}", originalTitle, task.title)
+
+ taskService.add(task)
+ coreService.createTask(task)
+ return True
+ except Exception as e:
+ logger.opt(exception=e).error("无法创建任务卡片 {}", task.title)
+ return False
+
+ @staticmethod
+ def updateThemeColor():
+ palette = QApplication.palette()
+
+ for role in (QPalette.ColorRole.Accent, QPalette.ColorRole.Highlight):
+ color = palette.color(role)
+ if not color.isValid() or cfg.themeColor.value == color:
+ continue
+
+ setThemeColor(color, save=False)
+ return
+
+ def paintEvent(self, event):
+ painter = QPainter(self)
+ painter.fillRect(self.rect(), QColor(32, 32, 32) if isDarkTheme() else QColor(243, 243, 243))