The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
优化程序启动方式,优化唤醒已经启动的应用逻辑,优化程序路径获取逻辑
XiaoYouChRf2f46f5bcc9d
diff --git a/app/common/config.py b/app/common/config.pyindex e47352ba..a31aa63d 100644--- a/app/common/config.py+++ b/app/common/config.py@@ -1,9 +1,7 @@# coding:utf-8from PySide6.QtCore import QDir-from PySide6.QtWidgets import QApplication-from loguru import logger-from qfluentwidgets import (qconfig, QConfig, ConfigItem, OptionsConfigItem, BoolValidator,+from qfluentwidgets import (QConfig, ConfigItem, OptionsConfigItem, BoolValidator,OptionsValidator, RangeConfigItem, RangeValidator,FolderValidator)@@ -29,6 +27,9 @@ class Config(QConfig):checkUpdateAtStartUp = ConfigItem("Software", "CheckUpdateAtStartUp", True, BoolValidator())autoRun = ConfigItem("Software", "AutoRun", False, BoolValidator())+ # 程序运行路径+ appPath = "./"+YEAR = 2024AUTHOR = "XiaoYouChR"@@ -39,7 +40,3 @@ FEEDBACK_URL = "https://github.com/XiaoYouChR/Ghost-Downloader-3/issues"cfg = Config()-try:- qconfig.load('{}/Ghost Downloader 配置文件.json'.format(QApplication.applicationDirPath()), cfg)-except Exception as e:- logger.error(e)diff --git a/app/components/task_card.py b/app/components/task_card.pyindex 3e1af034..83dcafb5 100644--- a/app/components/task_card.py+++ b/app/components/task_card.py@@ -14,6 +14,7 @@ from qfluentwidgets import FluentIcon as FIFfrom .Ui_TaskCard import Ui_TaskCardfrom .task_progress_bar import TaskProgressBar+from ..common.config import cfgfrom ..common.download_task import DownloadTaskfrom ..common.methods import getWindowsProxy, getReadableSize@@ -113,7 +114,7 @@ class TaskCard(CardWidget, Ui_TaskCard):# 写入未完成任务记录文件,以供下次打开时继续下载if not autoCreated:- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "a", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "a", encoding="utf-8") as f:_ = {"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),"blockNum": self.maxBlockNum, "status": self.status}f.write(str(_) + "\n")@@ -138,7 +139,7 @@ class TaskCard(CardWidget, Ui_TaskCard):self.task.terminate()# 改变记录状态- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "r", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:_ = f.read()_ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),@@ -146,7 +147,7 @@ class TaskCard(CardWidget, Ui_TaskCard):str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),"blockNum": self.maxBlockNum, "status": "paused"}) + "\n")- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "w", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:f.write(_)self.speedLable.setText("任务已经暂停")@@ -162,7 +163,7 @@ class TaskCard(CardWidget, Ui_TaskCard):self.task.taskFinished.connect(self.taskFinished)# 改变记录状态- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "r", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:_ = f.read()_ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),@@ -170,7 +171,7 @@ class TaskCard(CardWidget, Ui_TaskCard):str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),"blockNum": self.maxBlockNum, "status": "working"}) + "\n")- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "w", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:f.write(_)self.speedLable.setText("任务正在开始")@@ -207,13 +208,13 @@ class TaskCard(CardWidget, Ui_TaskCard):sleep(0.1)# 删除记录文件- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "r", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:_ = f.read()_ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),"blockNum": self.maxBlockNum, "status": self.status}) + "\n", "")- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "w", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:f.write(_)self.status = "canceled"@@ -258,7 +259,7 @@ class TaskCard(CardWidget, Ui_TaskCard):if not self.status == "finished": # 不是自动创建的已完成任务# 改变记录状态- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "r", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "r", encoding="utf-8") as f:_ = f.read()_ = _.replace(str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),@@ -266,7 +267,7 @@ class TaskCard(CardWidget, Ui_TaskCard):str({"url": self.url, "fileName": self.fileName, "filePath": str(self.filePath),"blockNum": self.maxBlockNum, "status": "finished"}) + "\n")- with open("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()), "w", encoding="utf-8") as f:+ with open("{}/Ghost Downloader 记录文件".format(cfg.appPath), "w", encoding="utf-8") as f:f.write(_)# 再获取一次图标diff --git a/app/view/main_window.py b/app/view/main_window.pyindex 6e6e411a..8cbbe2be 100644--- a/app/view/main_window.py+++ b/app/view/main_window.py@@ -1,4 +1,5 @@# coding: utf-8+import ctypesfrom pathlib import Pathimport darkdetect@@ -8,6 +9,7 @@ from PySide6.QtWidgets import QApplicationfrom loguru import loggerfrom qfluentwidgets import FluentIcon as FIF, setTheme, Themefrom qfluentwidgets import NavigationItemPosition, MSFluentWindow, SplashScreen+from win32comext.shell.shellcon import WM_USERfrom .setting_interface import SettingInterfacefrom .task_interface import TaskInterface@@ -47,7 +49,7 @@ class MainWindow(MSFluentWindow):self.themeChangedListener.start()# 创建未完成的任务- historyFile = Path("{}/Ghost Downloader 记录文件".format(QApplication.applicationDirPath()))+ historyFile = Path("{}/Ghost Downloader 记录文件".format(cfg.appPath))# 未完成任务记录文件格式示例: [{"url": "xxx", "fileName": "xxx", "filePath": "xxx", "blockNum": x, "status": "xxx"}]if historyFile.exists():with open(historyFile, 'r', encoding='utf-8') as f:@@ -125,4 +127,15 @@ class MainWindow(MSFluentWindow):def closeEvent(self, event):# 拦截关闭事件,隐藏窗口而不是退出event.ignore()- self.hide()\ No newline at end of file+ self.hide()++ def nativeEvent(self, eventType, message):+ # 处理窗口重复打开事件+ if eventType == "windows_generic_MSG":+ msg = ctypes.wintypes.MSG.from_address(message.__int__())++ if msg.message == WM_USER + 1:+ self.show()+ return True, 0++ return super().nativeEvent(eventType, message)\ No newline at end of filediff --git a/main.py b/main.pyindex 1ff23a0f..34fd657e 100644--- a/main.py+++ b/main.py@@ -1,14 +1,39 @@# coding:utf-8-import sys-from PySide6.QtCore import Qt, QSharedMemory+# 创建 Application+import sysfrom PySide6.QtWidgets import QApplication-# create applicationapp = QApplication(sys.argv)-app.setAttribute(Qt.AA_DontCreateNativeWidgetSiblings)-import ctypes+# 检测程序重复运行+from PySide6.QtCore import QSharedMemory++# 尝试访问+sharedMemory = QSharedMemory()+sharedMemory.setKey("Ghost Downloader")++if sharedMemory.attach(): # 访问成功, 说明程序正在运行++ if sys.platform == "win32":+ import win32gui+ import win32con++ hWnd = win32gui.FindWindow(None, "Ghost Downloader")+ win32gui.ShowWindow(hWnd, 1)++ # 发送自定义信息唤醒窗口+ # WM_CUSTOM = win32con.WM_USER + 1+ # win32gui.SendMessage(hWnd, WM_CUSTOM, 0, 0)+ win32gui.SendMessage(hWnd, win32con.WM_USER + 1, 0, 0)++ win32gui.SetForegroundWindow(hWnd)++ sys.exit(-1)+# 创建 SharedMemory+sharedMemory.create(1)++# Starting Programimport osimport time@@ -17,34 +42,39 @@ import warningsimport darkdetectfrom PySide6.QtGui import QColor+from PySide6.QtCore import Qtfrom loguru import logger-from qfluentwidgets import setTheme, Theme, setThemeColor+from qfluentwidgets import setTheme, Theme, setThemeColor, qconfig# noinspection PyUnresolvedReferencesimport Res_rc+from app.common.config import cfgfrom app.common.methods import loadPluginsfrom app.view.main_window import MainWindow-# create shareMemory-shareMemory = QSharedMemory()-shareMemory.setKey("Ghost Downloader")-if shareMemory.attach():- if sys.platform == "win32":- import win32gui- hWnd = win32gui.FindWindow(None, "Ghost Downloader")- win32gui.ShowWindow(hWnd, 1)- win32gui.SetForegroundWindow(hWnd)- sys.exit(-1)-shareMemory.create(1)+# 设置程序运行路径, 便于调试+if "--debug" in sys.argv: # 调试时候请使用相对路径!+ cfg.appPath = "./"+ qconfig.load('./Ghost Downloader 配置文件.json', cfg)+else: # 编译后+ cfg.appPath = app.applicationDirPath()+ qconfig.load('{}/Ghost Downloader 配置文件.json'.format(QApplication.applicationDirPath()), cfg)++# 防止 Mica 背景失效+app.setAttribute(Qt.AA_DontCreateNativeWidgetSiblings)# config loguru-# logger.add("Ghost Downloader 运行日志.log", rotation="512 KB")-logger.add('{}/Ghost Downloader 运行日志.log'.format(QApplication.applicationDirPath()))+logger.add('{}/Ghost Downloader 运行日志.log'.format(cfg.appPath), rotation="512 KB")logger.info(f"Ghost Downloader is launched at {time.time_ns()}")+warnings.warn = logger.warning+# def exceptionHandler(type, value, traceback): # 自定义错误捕捉函数+# logger.exception(f"意料之外的错误! {type}: {value}. Traceback: {traceback}")+# sys.excepthook = exceptionHandler+# enable dpi scaleif cfg.get(cfg.dpiScale) == "Auto":pass@@ -59,22 +89,22 @@ setTheme(Theme.DARK if darkdetect.isDark() else Theme.LIGHT, save=False)try:# Windows Onlyif sys.platform == "win32":- # 定义用于获取主题色的函数-- ctypes.windll.dwmapi.DwmGetColorizationColor.restype = ctypes.c_ulong- ctypes.windll.dwmapi.DwmGetColorizationColor.argtypes = [ctypes.POINTER(ctypes.c_ulong),- ctypes.POINTER(ctypes.c_bool)]+ import ctypes+ # 定义用于获取主题色的函数+ ctypes.windll.dwmapi.DwmGetColorizationColor.restype = ctypes.c_ulong+ ctypes.windll.dwmapi.DwmGetColorizationColor.argtypes = [ctypes.POINTER(ctypes.c_ulong),+ ctypes.POINTER(ctypes.c_bool)]- color = ctypes.c_ulong()- opaque = ctypes.c_bool()+ color = ctypes.c_ulong()+ opaque = ctypes.c_bool()- # 获取主题颜色值- ctypes.windll.dwmapi.DwmGetColorizationColor(ctypes.byref(color), ctypes.byref(opaque))+ # 获取主题颜色值+ ctypes.windll.dwmapi.DwmGetColorizationColor(ctypes.byref(color), ctypes.byref(opaque))- # 将颜色值转换为RGB元组- b, g, r = color.value % 256, (color.value >> 8) % 256, (color.value >> 16) % 256+ # 将颜色值转换为RGB元组+ b, g, r = color.value % 256, (color.value >> 8) % 256, (color.value >> 16) % 256- setThemeColor(QColor(r, g, b), save=False)+ setThemeColor(QColor(r, g, b), save=False)elif sys.platform == "darwin": # macOS Only# 咱就是说为什么苹果要把开发者文档做成英文,出个中文版不好吗?@@ -93,17 +123,11 @@ try:color = NSColor.controlAccentColor() #md就是这个API让我找了好久……# 欸,这时还不能用,因为现在这是NSColor Catalog color,还要转换!color = color.colorUsingColorSpace_(NSColorSpace.sRGBColorSpace())- # 获取颜色的 RGB 分量- red = color.redComponent()- green = color.greenComponent()- blue = color.blueComponent()+ # 获取颜色的 RGB 分量, 并将颜色分量转换为 0-255 范围+ r, g, b = int(color.redComponent() * 255), int(color.greenComponent() * 255), int(color.blueComponent() * 255)- # 将颜色分量转换为 0-255 范围- red = int(red * 255)- green = int(green * 255)- blue = int(blue * 255)+ setThemeColor(QColor(r, g, b), save=False)- setThemeColor(QColor(red, green, blue), save=False)except Exception as e:logger.error(f"Cannot get theme color: {e}")@@ -111,12 +135,11 @@ except Exception as e:w = MainWindow()# loading plugins-pluginsPath=os.path.join(app.applicationDirPath(), "plugins")-# pluginsPath=("./plugins")+pluginsPath=os.path.join(cfg.appPath, "plugins")loadPlugins(w, pluginsPath)try: # 静默启动- if sys.argv[1] == "--silence":+ if "--silence" in sys.argv:w.hide()except:w.show()diff --git a/requirements.txt b/requirements.txtindex 2e33df55..593ee837 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,5 +1,6 @@-PySide6-Fluent-Widgets>=1.1.8-PySide6<=6.6.3.1+PySide6-Fluent-Widgets<=1.5.0+PySide6<=6.4.2loguru>=0.7.2httpx>=0.27.0-pyobjc>=10.3.1; sys_platform == 'darwin'++pyobjc>=10.3.1; sys_platform == 'darwin'\ No newline at end of file