Skip to content

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

refactor(platform): 清理 Kivy 遗留代码,统一 android.py

XiaoYouChR9d91b12f4e6c
diff --git a/app/platform/android.py b/app/platform/android.py
index e23be4c9..57a682bd 100644
--- a/app/platform/android.py
+++ b/app/platform/android.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import re
import sys
from functools import lru_cache
@@ -9,173 +8,6 @@ IS_ANDROID = hasattr(sys, "getandroidapilevel")
@lru_cache(maxsize=1)
def nativeLibraryDir() -> str:
- from jnius import autoclass
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
+ from java import jclass
+ activity = jclass("com.chaquo.python.Python").getPlatform().getApplication()
return activity.getApplicationInfo().nativeLibraryDir
-
-
-def isSystemDark() -> bool:
- from jnius import autoclass
- Configuration = autoclass("android.content.res.Configuration")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- uiMode = activity.getResources().getConfiguration().uiMode
- return (uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
-
-
-WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE"
-
-
-def isStorageGranted() -> bool:
- from jnius import autoclass
- # API30+ scoped storage 下下载到任意公共目录需 All Files Access; API<30(Android 9/10)回退运行时 WRITE 权限
- # (Android 10 靠 manifest 的 requestLegacyExternalStorage 让 WRITE 仍能自由写外置存储)。
- if autoclass("android.os.Build$VERSION").SDK_INT >= 30:
- return autoclass("android.os.Environment").isExternalStorageManager()
- PackageManager = autoclass("android.content.pm.PackageManager")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- return activity.checkSelfPermission(WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
-
-
-def requestStoragePermission() -> None:
- from jnius import autoclass
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- if autoclass("android.os.Build$VERSION").SDK_INT >= 30:
- Settings = autoclass("android.provider.Settings")
- Uri = autoclass("android.net.Uri")
- Intent = autoclass("android.content.Intent")
- intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
- intent.setData(Uri.parse("package:" + activity.getPackageName()))
- activity.startActivity(intent)
- return
- # <30 弹运行时权限对话框; 结果由 MainWindow 的 applicationStateChanged 重查 banner, 无需回调。
- activity.requestPermissions([WRITE_EXTERNAL_STORAGE], 0)
-
-
-_fileUriPolicyRelaxed = False
-
-
-def _relaxFileUriPolicy() -> None:
- # Android 24+ 用 Uri.fromFile 调起外部应用会抛 FileUriExposedException, 放宽 StrictMode
- global _fileUriPolicyRelaxed
- if _fileUriPolicyRelaxed:
- return
- from jnius import autoclass
- StrictMode = autoclass("android.os.StrictMode")
- VmPolicyBuilder = autoclass("android.os.StrictMode$VmPolicy$Builder")
- StrictMode.setVmPolicy(VmPolicyBuilder().build())
- _fileUriPolicyRelaxed = True
-
-
-def _launchView(path: str, mimeType: str) -> None:
- from jnius import autoclass
- _relaxFileUriPolicy()
- Uri = autoclass("android.net.Uri")
- File = autoclass("java.io.File")
- Intent = autoclass("android.content.Intent")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- intent = Intent(Intent.ACTION_VIEW)
- intent.setDataAndType(Uri.fromFile(File(path)), mimeType)
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- try:
- activity.startActivity(intent)
- except Exception as error:
- from loguru import logger
- logger.opt(exception=error).info("打开失败, 放弃: {} ({})", path, mimeType)
-
-
-def openFile(filePath) -> None:
- from jnius import autoclass
- text = str(filePath)
- extension = text.rsplit(".", 1)[-1].lower() if "." in text else ""
- mimeType = autoclass("android.webkit.MimeTypeMap").getSingleton().getMimeTypeFromExtension(extension) or "*/*"
- _launchView(text, mimeType)
-
-
-def openFolder(folder) -> None:
- _launchView(str(folder), "vnd.android.document/directory")
-
-
-def toFileUri(activity: "JavaObject", contentUri: "JavaObject") -> str | None:
- from pathlib import Path
- from jnius import autoclass
-
- try:
- resolver = activity.getContentResolver()
-
- displayName = "shared"
- cursor = resolver.query(contentUri, None, None, None, None)
- if cursor is not None:
- try:
- if cursor.moveToFirst():
- idx = cursor.getColumnIndex("_display_name")
- if idx >= 0:
- displayName = cursor.getString(idx) or displayName
- finally:
- cursor.close()
-
- cacheDir = Path(activity.getCacheDir().getAbsolutePath()) / "shared"
- cacheDir.mkdir(parents=True, exist_ok=True)
- dest = cacheDir / displayName
-
- inputStream = resolver.openInputStream(contentUri)
- if inputStream is None:
- return None
- try:
- Files = autoclass("java.nio.file.Files")
- Paths = autoclass("java.nio.file.Paths")
- if dest.exists():
- dest.unlink()
- Files.copy(inputStream, Paths.get(str(dest)))
- finally:
- inputStream.close()
-
- return dest.as_uri()
-
- except Exception as error:
- from loguru import logger
- logger.opt(exception=error).warning("content:// 拷贝失败")
- return None
-
-
-def parseShare() -> list[str] | None:
- from jnius import autoclass, cast
- Intent = autoclass("android.content.Intent")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- intent = activity.getIntent()
- if intent is None:
- return None
-
- action = intent.getAction()
- if action not in (Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE):
- return None
-
- if action == Intent.ACTION_SEND_MULTIPLE:
- streams = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM)
- if not streams:
- return []
- return [fileUri for i in range(streams.size())
- if (fileUri := toFileUri(activity, cast("android.net.Uri", streams.get(i))))]
-
- stream = intent.getParcelableExtra(Intent.EXTRA_STREAM)
- if stream is not None:
- uri = toFileUri(activity, cast("android.net.Uri", stream))
- return [uri] if uri else []
-
- # 文本分享(ACTION_SEND 且无 EXTRA_STREAM)
- text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT)
- if text is None:
- return []
- text = text if isinstance(text, str) else text.toString()
-
- standard = re.findall(r'(?i)(?:https?|ftps?|ed2k)://[^\s"\'<>,。!?、;:)》】」]+', text)
- magnets = re.findall(r'(?i)magnet:\?[^\s"\'<>,。!?、;:)》】」]+', text)
- return [url.rstrip(".,!?;:)]}>") for url in standard + magnets]
-
-
-def clearShare() -> None:
- from jnius import autoclass
- Intent = autoclass("android.content.Intent")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- intent = activity.getIntent()
- if intent is not None:
- intent.setAction(Intent.ACTION_MAIN) # 分享已取走, 防回前台重复添加同一分享
diff --git a/app/platform/android_keepalive.py b/app/platform/android_keepalive.py
deleted file mode 100644
index d2838589..00000000
--- a/app/platform/android_keepalive.py
+++ /dev/null
@@ -1,117 +0,0 @@
-from __future__ import annotations
-
-from PySide6.QtCore import QCoreApplication
-
-from app.platform.android_notification import notify
-
-REASON_DOWNLOAD = "download"
-REASON_BROWSER = "browser"
-
-SERVICE_CLASS = "org.ghostdownloader.KeepAliveService"
-KEEPALIVE_CHANNEL = "gd3_keepalive"
-KEEPALIVE_NOTIF_ID = 0x47443301
-
-
-class BackgroundKeepAlive:
- def __init__(self):
- self._activeReasons: set[str] = set()
- self._running = False
- self._statusMessage = ""
- self._speed = 0
- self._wakeLock = None
-
- def holdFor(self, reason: str) -> None:
- self._activeReasons.add(reason)
- if reason == REASON_DOWNLOAD:
- self._setWakeLock(True)
- self._updateService()
-
- def release(self, reason: str) -> None:
- self._activeReasons.discard(reason)
- if reason == REASON_DOWNLOAD:
- self._setWakeLock(False)
- self._updateService()
-
- def setSpeed(self, speed: int) -> None:
- self._speed = speed
- if self._running:
- self._updateService()
-
- def _setWakeLock(self, active: bool) -> None:
- from jnius import autoclass, cast
-
- if active:
- if self._wakeLock is not None:
- return
- Context = autoclass("android.content.Context")
- PowerManager = autoclass("android.os.PowerManager")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- powerManager = cast("android.os.PowerManager", activity.getSystemService(Context.POWER_SERVICE))
- self._wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "GhostDownloader::Download")
- self._wakeLock.setReferenceCounted(False)
- self._wakeLock.acquire()
- elif self._wakeLock is not None:
- self._wakeLock.release()
- self._wakeLock = None
-
- def _updateService(self) -> None:
- if self._activeReasons:
- statusMessage = self._buildStatusMessage()
- if not self._running:
- self._startService(statusMessage)
- self._running = True
- elif statusMessage != self._statusMessage:
- notify(KEEPALIVE_CHANNEL, QCoreApplication.translate("KeepAlive", "后台任务"),
- KEEPALIVE_NOTIF_ID, "Ghost Downloader", statusMessage,
- ongoing=True, lowImportance=True)
- self._statusMessage = statusMessage
- elif self._running:
- self._stopService()
- self._running = False
- self._statusMessage = ""
-
- def _buildStatusMessage(self) -> str:
- if self._speed > 0:
- from app.format import toReadableSize
- return f"{toReadableSize(self._speed)}/s"
- if REASON_DOWNLOAD in self._activeReasons:
- return QCoreApplication.translate("KeepAlive", "下载中")
- return QCoreApplication.translate("KeepAlive", "浏览器扩展已连接")
-
- def _startService(self, statusMessage: str) -> None:
- from jnius import autoclass
- Intent = autoclass("android.content.Intent")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- intent = Intent(activity, autoclass(SERVICE_CLASS))
- intent.putExtra("text", statusMessage)
- if autoclass("android.os.Build$VERSION").SDK_INT >= 26:
- activity.startForegroundService(intent)
- else:
- activity.startService(intent)
-
- def _stopService(self) -> None:
- from jnius import autoclass
- Intent = autoclass("android.content.Intent")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- activity.stopService(Intent(activity, autoclass(SERVICE_CLASS)))
-
-
-keepAlive = BackgroundKeepAlive()
-
-
-def requestIgnoreBatteryOptimizations() -> None:
- from jnius import autoclass, cast
-
- if autoclass("android.os.Build$VERSION").SDK_INT < 23:
- return
- Context = autoclass("android.content.Context")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- powerManager = cast("android.os.PowerManager", activity.getSystemService(Context.POWER_SERVICE))
- if powerManager.isIgnoringBatteryOptimizations(activity.getPackageName()):
- return
- Settings = autoclass("android.provider.Settings")
- Uri = autoclass("android.net.Uri")
- Intent = autoclass("android.content.Intent")
- intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
- intent.setData(Uri.parse("package:" + activity.getPackageName()))
- activity.startActivity(intent)
diff --git a/app/platform/android_notification.py b/app/platform/android_notification.py
deleted file mode 100644
index bea58d1c..00000000
--- a/app/platform/android_notification.py
+++ /dev/null
@@ -1,122 +0,0 @@
-from __future__ import annotations
-
-from typing import TYPE_CHECKING
-
-from PySide6.QtCore import QCoreApplication
-
-if TYPE_CHECKING:
- from app.models.task import Task
-
-DOWNLOAD_CHANNEL = "gd3_downloads"
-
-
-def notify(channelId: str, channelName: str, notificationId: int,
- title: str, text: str, *, ongoing: bool, lowImportance: bool) -> None:
- from jnius import autoclass, cast
-
- Context = autoclass("android.content.Context")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- manager = cast("android.app.NotificationManager", activity.getSystemService(Context.NOTIFICATION_SERVICE))
-
- if autoclass("android.os.Build$VERSION").SDK_INT >= 26:
- NotificationManager = autoclass("android.app.NotificationManager")
- NotificationChannel = autoclass("android.app.NotificationChannel")
- importance = NotificationManager.IMPORTANCE_LOW if lowImportance else NotificationManager.IMPORTANCE_DEFAULT
- manager.createNotificationChannel(NotificationChannel(channelId, channelName, importance))
- builder = autoclass("android.app.Notification$Builder")(activity, channelId)
- else:
- builder = autoclass("android.app.Notification$Builder")(activity)
-
- builder.setSmallIcon(activity.getApplicationInfo().icon)
- builder.setContentTitle(title)
- builder.setContentText(text)
- builder.setOngoing(ongoing)
- builder.setAutoCancel(not ongoing)
- builder.setOnlyAlertOnce(True)
- builder.setContentIntent(_reopenAppIntent(activity))
- manager.notify(notificationId, builder.build())
-
-
-def notifyTaskCompleted(task: Task) -> None:
- notify(DOWNLOAD_CHANNEL, QCoreApplication.translate("Notifications", "下载"),
- hash(task.taskId) & 0x7FFFFFFF,
- QCoreApplication.translate("Notifications", "下载完成"), task.name,
- ongoing=False, lowImportance=False)
-
-
-DISK_SPACE_NOTIFICATION_ID = 0x6764_0003
-
-
-def notifyDiskSpaceInsufficient(free: int, needed: int) -> None:
- from app.format import toReadableSize
- notify(DOWNLOAD_CHANNEL, QCoreApplication.translate("Notifications", "下载"),
- DISK_SPACE_NOTIFICATION_ID,
- QCoreApplication.translate("Notifications", "磁盘空间不足"),
- QCoreApplication.translate("Notifications", "剩余 {0},需要 {1},任务未自动开始").format(
- toReadableSize(free), toReadableSize(needed)),
- ongoing=False, lowImportance=False)
-
-
-BROWSER_PUSH_NOTIFICATION_ID = 0x6764_0001
-BROWSER_PAIR_NOTIFICATION_ID = 0x6764_0002
-
-
-def notifyBrowserTaskAdded(tasks: list[Task]) -> None:
- if not tasks:
- return
- count = len(tasks)
- title = QCoreApplication.translate("Notifications", "浏览器推送") if count == 1 \
- else QCoreApplication.translate("Notifications", "浏览器推送({count})").format(count=count)
- text = tasks[0].name if count == 1 else "、".join(t.name for t in tasks[:3])
- if count > 3:
- text += QCoreApplication.translate("Notifications", "等 {count} 个").format(count=count)
- notify(DOWNLOAD_CHANNEL, QCoreApplication.translate("Notifications", "下载"),
- BROWSER_PUSH_NOTIFICATION_ID,
- title, text, ongoing=False, lowImportance=False)
-
-
-def notifyBrowserPaired(peerAddress: str) -> None:
- notify(DOWNLOAD_CHANNEL, QCoreApplication.translate("Notifications", "下载"),
- BROWSER_PAIR_NOTIFICATION_ID,
- QCoreApplication.translate("Notifications", "浏览器扩展已连接"), peerAddress,
- ongoing=False, lowImportance=True)
-
-
-def isNotificationEnabled() -> bool:
- from jnius import autoclass, cast
-
- Context = autoclass("android.content.Context")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- manager = cast("android.app.NotificationManager",
- activity.getSystemService(Context.NOTIFICATION_SERVICE))
- return manager.areNotificationsEnabled()
-
-
-def requestNotificationPermission() -> None:
- from jnius import autoclass
-
- if isNotificationEnabled():
- return
- Settings = autoclass("android.provider.Settings")
- Intent = autoclass("android.content.Intent")
- activity = autoclass("org.kivy.android.PythonActivity").mActivity
- intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
- intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.getPackageName())
- activity.startActivity(intent)
-
-
-def _reopenAppIntent(activity):
- from jnius import autoclass
-
- Intent = autoclass("android.content.Intent")
- PendingIntent = autoclass("android.app.PendingIntent")
- PythonActivity = autoclass("org.kivy.android.PythonActivity")
-
- intent = Intent(activity, PythonActivity)
- intent.setAction(Intent.ACTION_MAIN)
- intent.addCategory(Intent.CATEGORY_LAUNCHER)
- intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
- flags = PendingIntent.FLAG_UPDATE_CURRENT
- if autoclass("android.os.Build$VERSION").SDK_INT >= 23:
- flags |= PendingIntent.FLAG_IMMUTABLE
- return PendingIntent.getActivity(activity, 0, intent, flags)
diff --git a/app/view/mobile/__init__.py b/app/view/mobile/__init__.py
deleted file mode 100644
index 3d21e518..00000000
--- a/app/view/mobile/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-def setupAndroid() -> None:
- from .device import setupFont, setupTheme
- from .patches import (
- patchDialogWidth, patchFileDialogs, patchGroupTouch,
- patchIconRendering, patchMenus, patchOptionCardLayout,
- )
-
- setupTheme()
- setupFont()
- patchIconRendering()
- patchFileDialogs()
- patchDialogWidth()
- patchGroupTouch()
- patchMenus()
- patchOptionCardLayout()
diff --git a/app/view/mobile/cards.py b/app/view/mobile/cards.py
deleted file mode 100644
index d6baf5d4..00000000
--- a/app/view/mobile/cards.py
+++ /dev/null
@@ -1,78 +0,0 @@
-from __future__ import annotations
-
-from PySide6.QtCore import Qt, QTimer
-from qfluentwidgets import Action, CardWidget, FluentIcon, TransparentToolButton
-
-from app.models.task import TaskStatus
-from app.platform.android import openFile, openFolder
-
-LONG_PRESS_MS = 450
-
-
-class MobileTaskCardBase:
- """窄屏触屏改造: 操作按钮收进 ⋮ 溢出菜单, 长按多选, 轻触打开。"""
-
- def setupMobile(self) -> None:
- self.overflowButton = TransparentToolButton(FluentIcon.MORE, self)
- for button in (self.verifyHashButton, self.openFileButton, self.openFolderButton, self.deleteButton):
- button.hide()
- self.hBoxLayout.addWidget(self.overflowButton)
- self.overflowButton.clicked.connect(self._showOverflowMenu)
-
- self._hasLongPressed = False
- self._longPressTimer = QTimer(self, singleShot=True)
- self._longPressTimer.setInterval(LONG_PRESS_MS)
- self._longPressTimer.timeout.connect(self._onLongPress)
-
- def _refreshButtons(self) -> None:
- super()._refreshButtons(names={"toggle", "selectFiles"})
-
- def _showOverflowMenu(self) -> None:
- menu = self.createContextMenu()
- menu.addSeparator()
-
- openFileAction = Action(FluentIcon.LINK, self.tr("打开文件"), self)
- openFileAction.triggered.connect(lambda: openFile(self.task.outputPath))
- 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._onVerifyHashClicked)
- menu.addAction(verifyAction)
-
- menu.addSeparator()
- deleteAction = Action(FluentIcon.DELETE, self.tr("删除"), self)
- deleteAction.triggered.connect(self._onDeleteClicked)
- menu.addAction(deleteAction)
-
- menu.exec(self.overflowButton.mapToGlobal(self.overflowButton.rect().bottomLeft()))
-
- def mousePressEvent(self, e) -> None:
- super().mousePressEvent(e)
- if e.button() == Qt.MouseButton.LeftButton:
- self._hasLongPressed = False
- self._longPressTimer.start()
-
- def mouseReleaseEvent(self, e) -> None:
- CardWidget.mouseReleaseEvent(self, e) # 跳过桌面卡的「松手即选中」, 改走下面触屏语义
- self._longPressTimer.stop()
- if e.button() != Qt.MouseButton.LeftButton or self._hasLongPressed:
- return
- if self._isSelectionMode:
- self.selectionChanged.emit(not self.isChecked(), False)
- else:
- openFile(self.task.outputPath)
-
- def mouseDoubleClickEvent(self, e) -> None:
- pass
-
- def _onLongPress(self) -> None:
- self._hasLongPressed = True
- if self._isSelectionMode:
- self.selectionChanged.emit(not self.isChecked(), False)
- else:
- self.selectionChanged.emit(True, False)
diff --git a/app/view/mobile/device.py b/app/view/mobile/device.py
deleted file mode 100644
index 444d3386..00000000
--- a/app/view/mobile/device.py
+++ /dev/null
@@ -1,82 +0,0 @@
-from __future__ import annotations
-
-
-def setupAccentColor() -> None:
- from PySide6.QtGui import QPalette
- from PySide6.QtWidgets import QApplication
- from qfluentwidgets import setThemeColor
-
- from app.config.cfg import cfg
-
- palette = QApplication.palette()
- for role in (QPalette.ColorRole.Accent, QPalette.ColorRole.Highlight):
- color = palette.color(role)
- if color.isValid() and cfg.themeColor.value != color:
- setThemeColor(color, save=False)
- return
-
-
-def setupTheme() -> None:
- import darkdetect
- from qfluentwidgets import setTheme
-
- from app.config.cfg import cfg
- from app.platform.android import isSystemDark
-
- def themeName() -> str:
- return "Dark" if isSystemDark() else "Light"
-
- darkdetect.theme = themeName
- darkdetect.isDark = isSystemDark
- setTheme(cfg.themeMode.value, save=False)
-
-
-def setupFont() -> None:
- from loguru import logger
- from PySide6.QtGui import QFontDatabase
- from qfluentwidgets import qconfig
-
- # Android 的 Qt 平台字体库启动时已注册全部系统字体, 按名取用即可。
- # 绝不对系统字体 addApplicationFont: 既多余, 又会在 MIUI 的 MiSans 可变字体上让 Qt 段错误。
- known = set(QFontDatabase.families())
- preferred = ("MiSans VF", "MiSans", "OPPO Sans", "OplusSans", "HarmonyOS Sans SC", "vivo Sans")
- picked = next((name for name in preferred if name in known), None)
-
- logger.info("系统字体: {}", picked or "sans-serif(回退)")
- qconfig.set(qconfig.fontFamilies, [picked, "sans-serif"] if picked else ["sans-serif"], save=False)
-
-
-def setupTouchScrolling(window) -> None:
- from PySide6.QtCore import QEvent, QObject
- from PySide6.QtWidgets import QAbstractScrollArea, QScroller, QScrollerProperties, QWidget
- from qfluentwidgets.components.settings.expand_setting_card import ExpandSettingCard
-
- class ScrollClickGuard(QObject):
- 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/navigation.py b/app/view/mobile/navigation.py
deleted file mode 100644
index c287fe5f..00000000
--- a/app/view/mobile/navigation.py
+++ /dev/null
@@ -1,107 +0,0 @@
-from __future__ import annotations
-
-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()
- self._bind()
-
- 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 _bind(self):
- qconfig.themeChanged.connect(self._updateColors)
-
- 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):
- 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()
-
- def _initWidget(self):
- self.setFixedHeight(NAV_BAR_HEIGHT)
-
- def _initLayout(self):
- self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
- self.hBoxLayout.setSpacing(0)
-
- 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 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/patches.py b/app/view/mobile/patches.py
deleted file mode 100644
index 22291f18..00000000
--- a/app/view/mobile/patches.py
+++ /dev/null
@@ -1,243 +0,0 @@
-from __future__ import annotations
-
-
-def patchFileDialogs() -> None:
- 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):])
- 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
- originalSaveFile = QFileDialog.getSaveFileName
-
- 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
-
- def resolveSaveFileName(*args, **kwargs):
- path, selectedFilter = originalSaveFile(*args, **kwargs)
- return toRealPath(path), selectedFilter
-
- QFileDialog.getExistingDirectory = staticmethod(resolveExistingDirectory)
- QFileDialog.getOpenFileNames = staticmethod(resolveOpenFileNames)
- QFileDialog.getSaveFileName = staticmethod(resolveSaveFileName)
-
-
-def patchDialogWidth() -> None:
- from qfluentwidgets import MessageBoxBase
-
- originalShowEvent = MessageBoxBase.showEvent
-
- def showEventWithWidthLimit(self, event):
- parent = self.parent()
- if parent is not None:
- widthLimit = parent.width() - 24
- if 0 < widthLimit < self.widget.width():
- self.widget.setFixedWidth(widthLimit)
- originalShowEvent(self, event)
-
- MessageBoxBase.showEvent = showEventWithWidthLimit
-
-
-def patchIconRendering() -> None:
- 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 patchMenus() -> None:
- from PySide6.QtCore import Qt
- from PySide6.QtWidgets import QApplication, QWidget
- from qfluentwidgets.components.widgets.menu import RoundMenu
-
- class MenuDismissOverlay(QWidget):
- def __init__(self, host: QWidget, menu: RoundMenu):
- super().__init__(host)
- self._menu = menu
- self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
- self.setGeometry(host.rect())
-
- def mousePressEvent(self, event) -> None:
- self._menu._hideMenu(False)
- for menu in self.parent().findChildren(RoundMenu):
- if menu.isVisible():
- menu.hide()
- event.accept()
-
- def hostWindow(menu: RoundMenu) -> QWidget | None:
- widget = menu.parent()
- while isinstance(widget, RoundMenu):
- widget = widget.parent()
- if widget is not None:
- return widget.window()
- active = QApplication.activeWindow()
- return active if not isinstance(active, RoundMenu) else None
-
- originalExec = RoundMenu.exec
- originalHideEvent = RoundMenu.hideEvent
-
- def execInWindow(self, pos, *args, **kwargs):
- host = hostWindow(self)
- if host is None:
- return originalExec(self, pos, *args, **kwargs)
-
- self.setParent(host, Qt.WindowType.Widget)
- if not self.isSubMenu:
- self._androidOverlay = MenuDismissOverlay(host, self)
- self._androidOverlay.show()
- self.raise_()
- return originalExec(self, host.mapFromGlobal(pos), *args, **kwargs)
-
- def hideEventInWindow(self, event) -> None:
- overlay = self.__dict__.pop("_androidOverlay", None)
- if overlay is not None:
- overlay.deleteLater()
-
- focused = QApplication.focusWidget()
- if focused is not None and (focused is self or self.isAncestorOf(focused)):
- host = self.parent()
- if isinstance(host, QWidget):
- host.setFocus(Qt.FocusReason.OtherFocusReason)
- originalHideEvent(self, event)
-
- RoundMenu.exec = execInWindow
- RoundMenu.hideEvent = hideEventInWindow
-
-
-def patchOptionCardLayout() -> None:
- from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget
- from qfluentwidgets import ComboBox, LineEdit, Slider
-
- from app.view.components.card_groups import OptionCardGroup
-
- MAX_WIDGET_SIZE = (1 << 24) - 1
- expandingControls = (LineEdit, Slider, ComboBox)
-
- def reflowToVertical(card: QWidget) -> None:
- # 窄屏横排会把路径框/滑块挤没
- layout = card.layout()
- title = getattr(card, "titleLabel", None)
- if layout is None or title is None or getattr(card, "_usesMobileLayout", False):
- return
-
- controls = []
- afterTitle = False
- for i in range(layout.count()):
- widget = layout.itemAt(i).widget()
- if widget is title:
- afterTitle = True
- elif afterTitle and widget is not None:
- controls.append(widget)
- if not controls:
- return
-
- while layout.count():
- layout.takeAt(0)
- QWidget().setLayout(layout)
-
- outer = QVBoxLayout(card)
- outer.setContentsMargins(24, 8, 24, 8)
- outer.setSpacing(8)
-
- titleRow = QHBoxLayout()
- titleRow.setSpacing(12)
- icon = getattr(card, "iconWidget", None)
- if icon is not None:
- titleRow.addWidget(icon)
- titleRow.addWidget(title)
- titleRow.addStretch(1)
- outer.addLayout(titleRow)
-
- controlRow = QHBoxLayout()
- controlRow.setContentsMargins(28, 0, 0, 0)
- controlRow.setSpacing(8)
- hasExpanding = False
- for widget in controls:
- if isinstance(widget, expandingControls):
- widget.setMinimumWidth(0)
- controlRow.addWidget(widget, 1)
- hasExpanding = True
- else:
- controlRow.addWidget(widget, 0)
- if not hasExpanding:
- controlRow.addStretch(1)
- outer.addLayout(controlRow)
-
- card.setMinimumHeight(0)
- card.setMaximumHeight(MAX_WIDGET_SIZE)
- card._usesMobileLayout = True
-
- originalAdd = OptionCardGroup.addCard
- originalInsert = OptionCardGroup.insertCard
-
- def addCard(self, card) -> None:
- reflowToVertical(card)
- originalAdd(self, card)
-
- def insertCard(self, index, card) -> None:
- reflowToVertical(card)
- originalInsert(self, index, card)
-
- OptionCardGroup.addCard = addCard
- OptionCardGroup.insertCard = insertCard
-
-
-def patchGroupTouch() -> None:
- 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)
-
- def mouseReleaseEvent(self, event) -> None:
- if getattr(self, "_headerPressed", False) and event.button() == Qt.MouseButton.LeftButton:
- self._onExpandClicked()
- self._headerPressed = False
- QWidget.mouseReleaseEvent(self, event)
-
- CollapsibleSettingCardGroup.mousePressEvent = mousePressEvent
- CollapsibleSettingCardGroup.mouseReleaseEvent = mouseReleaseEvent
diff --git a/app/view/mobile/permission.py b/app/view/mobile/permission.py
deleted file mode 100644
index ac4450f2..00000000
--- a/app/view/mobile/permission.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from __future__ import annotations
-
-from collections.abc import Callable
-
-from PySide6.QtWidgets import QHBoxLayout, QWidget
-from qfluentwidgets import BodyLabel, FluentIcon, IconWidget, PrimaryPushButton
-
-from app.view.components.banners import WarningBanner
-
-
-class PermissionBanner(WarningBanner):
- def __init__(self, onGrant: Callable[[], None], text: str = "",
- parent: QWidget | None = None):
- super().__init__(parent, radius=0)
- self._onGrant = onGrant
- self.iconWidget = IconWidget(FluentIcon.INFO, self)
- self.label = BodyLabel(text or 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())
diff --git a/app/view/mobile/setting_page.py b/app/view/mobile/setting_page.py
deleted file mode 100644
index 985f17f2..00000000
--- a/app/view/mobile/setting_page.py
+++ /dev/null
@@ -1,104 +0,0 @@
-from __future__ import annotations
-
-from PySide6.QtCore import Qt
-from PySide6.QtGui import QColor, QPalette
-from PySide6.QtWidgets import QHBoxLayout, QSizePolicy, QVBoxLayout, QWidget
-from qfluentwidgets import SettingCard, SwitchButton, isDarkTheme, qconfig
-
-from app.view.components.setting_card_group import CollapsibleSettingCard, CollapsibleSettingCardGroup
-from app.view.pages.setting_page import SettingPage
-
-QWIDGETSIZE_MAX = (1 << 24) - 1
-
-
-class MobileSettingPage(SettingPage):
- def __init__(self, featureService, browserService, coroutineRunner, categoryService, taskService, updateService, parent=None):
- super().__init__(featureService, browserService, coroutineRunner, categoryService, taskService, updateService, parent=parent)
- self._setScrollContentOpaque()
-
- def showEvent(self, event):
- self._updateScrollBackground()
- super().showEvent(event)
-
- def _setScrollContentOpaque(self):
- self.container.setStyleSheet("")
- self.container.setAutoFillBackground(True)
- self._updateScrollBackground()
- qconfig.themeChanged.connect(self._updateScrollBackground)
-
- def _updateScrollBackground(self):
- palette = self.container.palette()
- palette.setColor(
- 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._reflowToVertical(card)
- elif isinstance(card, CollapsibleSettingCard):
- policy = card.sizePolicy()
- policy.setHorizontalPolicy(QSizePolicy.Policy.Ignored)
- card.setSizePolicy(policy)
- super().addSettingGroup(group)
-
- def _reflowToVertical(self, card: SettingCard):
- if getattr(card, "_usesMobileLayout", False):
- return
-
- controls = self._controlsAfterTitle(card)
- if not controls:
- return
- if len(controls) == 1 and isinstance(controls[0], SwitchButton):
- return
-
- 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)
- controlRow.setSpacing(8)
- # 桌面控件(滑块 268 / 下拉 200 / 选择框 180 / 商店按钮 等)自带硬最小宽, 窄屏会把整页撑出屏外。
- # 让行内最宽的主控件填满并可收缩到 0, 辅助控件(数值标签 / 图标按钮)保持原宽, 整页便不再被撑宽。
- primary = max(controls, key=lambda w: w.sizeHint().width())
- for widget in controls:
- widget.setMinimumWidth(0)
- if widget is primary:
- policy = widget.sizePolicy()
- policy.setHorizontalPolicy(QSizePolicy.Policy.Ignored) # 仅放开水平轴, 使其填满行宽并可收缩
- widget.setSizePolicy(policy)
- controlRow.addWidget(widget, 1)
- else:
- controlRow.addWidget(widget)
- outer.addLayout(controlRow)
-
- card.setMinimumHeight(0)
- card.setMaximumHeight(QWIDGETSIZE_MAX)
- card._usesMobileLayout = True
-
- def _controlsAfterTitle(self, card: SettingCard) -> list[QWidget]:
- 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/task_page.py b/app/view/mobile/task_page.py
deleted file mode 100644
index 54dec8dd..00000000
--- a/app/view/mobile/task_page.py
+++ /dev/null
@@ -1,92 +0,0 @@
-from __future__ import annotations
-
-from PySide6.QtCore import Qt, Signal
-from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget
-from qfluentwidgets import FluentIcon, PrimaryToolButton, ToolButton
-
-from app.models.task import Task
-from app.view.cards.task_cards import TaskCard
-from app.view.mobile.cards import MobileTaskCardBase
-from app.view.pages.task_page import TaskPage
-
-
-class MobileTaskPage(TaskPage):
- selectionModeChanged = Signal(bool)
-
- def __init__(self, taskService, featureService, categoryService, speedMeter, parent=None):
- self._mobileCardTypes: dict[type, type] = {}
- super().__init__(taskService, featureService, categoryService, speedMeter, parent=parent)
-
- def setSelectionMode(self, enter: bool) -> None:
- super().setSelectionMode(enter)
- self.selectionModeChanged.emit(enter)
-
- def _bind(self) -> None:
- super()._bind()
- self._bandSelector.setEnabled(False)
-
- def _initWidget(self) -> None:
- super()._initWidget()
- # 桌面的文字按钮在窄屏太宽, 换图标按钮; 选择改长按触发, 收起 selectButton
- for old in (self.startAllButton, self.pauseAllButton):
- old.hide()
- old.deleteLater()
- self.startAllButton = PrimaryToolButton(FluentIcon.PLAY, self.toolBar)
- self.pauseAllButton = ToolButton(FluentIcon.PAUSE, self.toolBar)
- self.startAllButton.setToolTip(self.tr("全部开始"))
- self.pauseAllButton.setToolTip(self.tr("全部暂停"))
- self.selectButton.hide()
-
- self.filterToolBar = QWidget(self)
-
- def _initLayout(self) -> None:
- toolBarLayout = QHBoxLayout(self.toolBar)
- toolBarLayout.setContentsMargins(10, 4, 10, 0)
- toolBarLayout.setSpacing(6)
- toolBarLayout.addWidget(self.startAllButton)
- toolBarLayout.addWidget(self.pauseAllButton)
- toolBarLayout.addWidget(self.speedBadge)
- toolBarLayout.addStretch(1)
- toolBarLayout.addWidget(self.rateLimitButton)
- toolBarLayout.addWidget(self.planButton)
-
- filterToolBarLayout = QHBoxLayout(self.filterToolBar)
- filterToolBarLayout.setContentsMargins(10, 0, 10, 4)
- filterToolBarLayout.setSpacing(6)
- filterToolBarLayout.addWidget(self.filterSegment)
- filterToolBarLayout.addStretch(1)
- filterToolBarLayout.addWidget(self.sortButton)
- filterToolBarLayout.addWidget(self.categoryFilterButton)
-
- layout = QVBoxLayout(self)
- layout.setContentsMargins(0, 0, 0, 0)
- layout.setSpacing(6)
- layout.addWidget(self.toolBar)
- layout.addWidget(self.filterToolBar)
- layout.addWidget(self.scrollArea)
-
- def _createCard(self, task: Task) -> TaskCard | None:
- card = super()._createCard(task)
- if card is None: # 该任务所属 pack 未打包(如 Android 排除的 ed2k)
- return None
- baseType = type(card)
- mobileType = self._mobileCardTypes.get(baseType)
- if mobileType is None:
- mobileType = type(f"Mobile{baseType.__name__}", (MobileTaskCardBase, baseType), {})
- self._mobileCardTypes[baseType] = mobileType
- card.__class__ = mobileType # 套上移动 mixin: 同一 C++ 类型, 仅改 Python MRO
- card.setupMobile()
- return card
-
- def resizeEvent(self, event) -> None:
- self._fitCommandView()
- super().resizeEvent(event)
-
- def _fitCommandView(self) -> None:
- # 窄屏放不下整条命令栏, 收窄它好让溢出动作折进「更多」按钮
- bar = self.commandView.bar
- margin = 12
- widthLimit = max(self.width() - 24 - margin, bar.moreButton.width())
- width = min(bar.suitableWidth(), widthLimit)
- bar.setFixedWidth(width)
- self.commandView.setFixedWidth(width + margin)
diff --git a/app/view/mobile/window.py b/app/view/mobile/window.py
deleted file mode 100644
index d5166166..00000000
--- a/app/view/mobile/window.py
+++ /dev/null
@@ -1,333 +0,0 @@
-from __future__ import annotations
-
-from loguru import logger
-from PySide6.QtCore import QEvent, QSize, Qt
-from PySide6.QtGui import QColor, QIcon, QPainter
-from PySide6.QtWidgets import QApplication, QHBoxLayout, QStackedWidget, QVBoxLayout, QWidget
-from qfluentwidgets import (
- FluentIcon, InfoBar, InfoBarPosition, PrimaryToolButton, SearchLineEdit,
- Theme, isDarkTheme, qconfig,
-)
-
-from app.config.cfg import cfg
-from app.platform.android import clearShare, isStorageGranted, parseShare, requestStoragePermission
-from app.platform.android_notification import isNotificationEnabled, requestNotificationPermission
-from app.services.task_draft import TaskDraft
-from app.services.update_service import UpdateState
-from app.view.dialogs.task_draft import TaskDraftDialog
-from app.view.mobile.device import setupAccentColor
-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
-
-TASK_PAGE_INDEX = 0
-
-
-class MobileMainWindow(QWidget):
- def __init__(self, taskService, featureService, browserService, categoryService, speedMeter, coroutineRunner, updateService=None):
- super().__init__(parent=None)
- self._taskService = taskService
- self._featureService = featureService
- self._browserService = browserService
- self._categoryService = categoryService
- self._speedMeter = speedMeter
- self._coroutineRunner = coroutineRunner
- self._updateService = updateService
- self._progressToast = None
- setupAccentColor()
-
- self.stackedWidget = QStackedWidget(self)
- self.navigationBar = BottomNavigationBar(self)
- self.permissionBanner = PermissionBanner(requestStoragePermission, parent=self)
- self.notificationBanner = PermissionBanner(
- requestNotificationPermission,
- text=self.tr("未开启通知权限,下载完成后将无法提醒"),
- parent=self,
- )
- self.taskPage = MobileTaskPage(taskService, featureService, categoryService, speedMeter, parent=self)
- self.settingPage = MobileSettingPage(featureService, browserService, coroutineRunner, categoryService, taskService, updateService, parent=self)
- self.searchEdit = SearchLineEdit(self)
- self.addButton = PrimaryToolButton(FluentIcon.ADD, self)
- self.vBoxLayout = QVBoxLayout(self)
-
- self._draft = TaskDraft(coroutineRunner, featureService)
- self._draftDialog = TaskDraftDialog(self._draft, featureService, categoryService, parent=self)
-
- self._initWidget()
- self._initLayout()
- self._bind()
- self._updatePermissionBanner()
- self._updateAddButtonVisibility()
- self._updateSearchTarget(self.taskPage)
-
- 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.searchEdit.setClearButtonEnabled(True)
- self.addButton.setFixedSize(56, 56)
- self.addButton.setIconSize(QSize(22, 22))
- self.addButton.raise_()
- self._addPage(self.taskPage, FluentIcon.DOWNLOAD, self.tr("任务"))
- self._addPage(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.notificationBanner, 0)
- searchBar = QWidget(self)
- searchBarLayout = QHBoxLayout(searchBar)
- searchBarLayout.setContentsMargins(10, 4, 10, 2)
- searchBarLayout.addWidget(self.searchEdit)
- self.vBoxLayout.addWidget(searchBar, 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._updateAddButtonVisibility())
- self.navigationBar.currentChanged.connect(
- lambda index: self._updateSearchTarget(self.stackedWidget.widget(index))
- )
- self.searchEdit.textChanged.connect(self._onSearchTextChanged)
- 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)
- qconfig.themeChanged.connect(self.update)
-
- def _addPage(self, page: QWidget, icon: FluentIcon, text: str):
- self.stackedWidget.addWidget(page)
- self.navigationBar.addItem(icon, text)
-
- def _onSearchTextChanged(self, text: str) -> None:
- page = self.stackedWidget.currentWidget()
- if isinstance(page, MobileTaskPage):
- page.setSearchText(text)
-
- def _updateSearchTarget(self, page: QWidget) -> None:
- self.searchEdit.clear()
- if isinstance(page, MobileTaskPage):
- self.searchEdit.setPlaceholderText(page.searchPlaceholder)
- self.searchEdit.show()
- else:
- self.searchEdit.hide()
-
- def _onSystemColorSchemeChanged(self, colorScheme):
- if cfg.themeMode.value != Theme.AUTO:
- return
- if colorScheme == Qt.ColorScheme.Dark:
- self._setTheme(Theme.DARK)
- elif colorScheme == Qt.ColorScheme.Light:
- self._setTheme(Theme.LIGHT)
- else:
- self._setTheme(Theme.AUTO)
-
- def _setTheme(self, value):
- from qfluentwidgets.common.style_sheet import updateStyleSheet
- prevTheme = qconfig.theme
- qconfig.theme = value
- if qconfig.theme != prevTheme:
- qconfig.themeChanged.emit(qconfig.theme)
- updateStyleSheet()
- qconfig.themeChangedFinished.emit()
-
- def changeEvent(self, event):
- super().changeEvent(event)
- if event.type() == QEvent.Type.PaletteChange:
- setupAccentColor()
-
- def _onApplicationStateChanged(self, state: Qt.ApplicationState):
- if state == Qt.ApplicationState.ApplicationActive:
- self._updatePermissionBanner()
- self._addSharedTasks()
-
- def _addSharedTasks(self) -> None:
- uris = parseShare()
- if uris is None:
- return
- clearShare()
- if not uris:
- return
- if cfg.shouldDraftTakenDownload.value or not isStorageGranted():
- self._draftDialog.addUrls(uris)
- self._draftDialog.showMask()
- return
- self.navigationBar.setCurrentIndex(TASK_PAGE_INDEX)
- self._autoAddUrls(uris)
-
- def _autoAddUrls(self, urls: list[str]) -> None:
- from app.models.task import TaskOptions
-
- async def parseAndAdd():
- for url in urls:
- try:
- task = await self._featureService.parse(TaskOptions(url=url))
- self._taskService.add(task)
- except Exception as e:
- logger.warning("自动下载失败 {}: {}", url, e)
-
- self._coroutineRunner.submit(parseAndAdd())
-
- def _updatePermissionBanner(self):
- self.permissionBanner.setVisible(not isStorageGranted())
- self.notificationBanner.setVisible(not isNotificationEnabled())
-
- def _updateAddButtonVisibility(self):
- onTaskPage = self.stackedWidget.currentIndex() == TASK_PAGE_INDEX
- self.addButton.setVisible(onTaskPage and not self.taskPage.isSelectionMode)
-
- def _showAddTaskDialog(self):
- if not isStorageGranted():
- requestStoragePermission()
- InfoBar.warning(
- self.tr("需要存储权限"),
- self.tr("请授予存储权限后再新建任务"),
- duration=4000,
- position=InfoBarPosition.TOP,
- parent=self,
- )
- return
- self._draftDialog.widget.setFixedWidth(min(700, self.width() - 24))
- if self._draftDialog.isVisible():
- self._draftDialog.raise_()
- self._draftDialog.activateWindow()
- return
- self._draftDialog.showMask()
-
- 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("检测到新版本"),
- content=self.tr("最新版本: {0}").format(info.latestVersion),
- orient=Qt.Orientation.Vertical,
- isClosable=True,
- duration=-1,
- position=InfoBarPosition.BOTTOM_RIGHT,
- parent=self,
- )
- downloadButton = PrimaryPushButton(FluentIcon.DOWNLOAD, self.tr("立即下载"))
- downloadButton.clicked.connect(lambda: (infoBar.close(), self._downloadBestAsset()))
- infoBar.addWidget(downloadButton)
- detailButton = PushButton(FluentIcon.CHAT, self.tr("查看详情"))
- detailButton.clicked.connect(self._showReleaseDetails)
- infoBar.addWidget(detailButton)
- infoBar.show()
-
- def _downloadBestAsset(self) -> None:
- from app.models.task import TaskOptions
- from app.update import fetchBestAssetUrl
-
- def onUrl(url):
- if url is None:
- self._showReleaseDetails()
- return
- self._coroutineRunner.submit(
- self._featureService.parse(TaskOptions(url=url)),
- done=self._taskService.add,
- owner=self,
- )
-
- self._coroutineRunner.submit(fetchBestAssetUrl(), done=onUrl, owner=self)
-
- 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 TaskOptions
- from app.update import fetchAssetUrl, fetchRelease
- from app.view.dialogs.release_info import ReleaseInfoDialog
-
- def onFetched(release):
- dialog = ReleaseInfoDialog(release, self)
-
- def onAccepted():
- asset = dialog.selectedAsset()
- if asset is None:
- return
-
- def onUrl(url):
- self._coroutineRunner.submit(
- self._featureService.parse(TaskOptions(url=url)),
- done=self._taskService.add,
- owner=self,
- )
-
- self._coroutineRunner.submit(
- fetchAssetUrl(release.version, asset.name),
- done=onUrl, owner=self,
- )
-
- dialog.accepted.connect(onAccepted)
- dialog.open()
-
- self._coroutineRunner.submit(fetchRelease(), done=onFetched, owner=self)
-
- def alertException(self, message: str) -> None:
- from PySide6.QtCore import QUrl
- from PySide6.QtGui import QDesktopServices
- from PySide6.QtWidgets import QHBoxLayout
- from qfluentwidgets import MessageBox, ToolTipFilter, TransparentToolButton
-
- from app.config.constants import FEEDBACK_URL
- from app.config.paths import APP_DATA_DIR
- from app.platform.android import openFile
-
- dialog = MessageBox(
- self.tr("程序发生异常"),
- self.tr('点击"确定"后将复制错误信息并打开反馈页面。\n\n{0}').format(message),
- self,
- )
- logButton = TransparentToolButton(FluentIcon.DOCUMENT, dialog)
- logButton.setToolTip(self.tr("查看日志"))
- logButton.installEventFilter(ToolTipFilter(logButton))
- logButton.clicked.connect(lambda: openFile(f"{APP_DATA_DIR}/GhostDownloader.log"))
-
- dialog.contentLabel.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
-
- titleLayout = dialog.textLayout
- titleLayout.removeWidget(dialog.titleLabel)
- titleRow = QHBoxLayout()
- titleRow.addWidget(dialog.titleLabel, 1)
- titleRow.addWidget(logButton)
- titleLayout.insertLayout(0, titleRow)
-
- if dialog.exec():
- QApplication.clipboard().setText(message)
- QDesktopServices.openUrl(QUrl(FEEDBACK_URL))
-
- 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 paintEvent(self, event):
- painter = QPainter(self)
- painter.fillRect(self.rect(), QColor(32, 32, 32) if isDarkTheme() else QColor(243, 243, 243))