Repository navigation
Expand file tree
/
Copy pathmain_window.py
More file actions
2192 lines (1842 loc) · 89.8 KB
/
Copy pathmain_window.py
File metadata and controls
2192 lines (1842 loc) · 89.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Python打包工具 - 主窗口
本模块实现主应用程序窗口,遵循PyQt6最佳实践:
1. 关注点分离(UI、逻辑、样式)
2. 后台任务通过 threading.Thread + pyqtSignal 跨线程回主线程更新 UI
3. 全面使用类型提示
4. 集中式主题管理
5. 模块化组件组织(对话框已抽离到 gui/dialogs/)
线程模型说明:
- 长任务(打包、依赖分析、GCC 下载)在 daemon Thread 中执行,
通过 log_signal / finished_signal 等 pyqtSignal 把结果投递回主线程。
- 取消机制:设置 self.cancel_packaging / self.cancel_download 标志位,
工作线程在各步骤之间轮询标志位并提前返回;同时 terminate() 子进程。
- self.thread_pool (QThreadPool.globalInstance()) 当前未启用业务任务,
保留作为未来轻量级任务的扩展点。
"""
import ast
import json
import os
import shutil
import subprocess
import sys
import tempfile
import threading
import webbrowser
from typing import Dict, Optional
from PyQt6.QtCore import (
QSettings,
Qt,
QThreadPool,
QTimer,
pyqtSignal,
pyqtSlot,
)
from PyQt6.QtGui import QAction, QBrush, QColor, QFont, QIcon, QPainter, QPen, QPixmap
from PyQt6.QtWidgets import (
QApplication,
QCheckBox,
QDialog,
QFileDialog,
QFormLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QMainWindow,
QMenu,
QMessageBox,
QPushButton,
QRadioButton,
QTextBrowser,
QTextEdit,
QVBoxLayout,
QWidget,
)
# 导入核心模块
from core.dependency_analyzer import DependencyAnalyzer
from core.packager import Packager
from core.packaging.config import PackagingConfig
# 导入重构后的GUI模块
from gui.dialogs.about_dialog import show_about_dialog
from gui.dialogs.donate_dialog import show_donate_dialog
from gui.dialogs.feedback_dialog import show_feedback_dialog
from gui.dialogs.nuitka_options_dialog import NuitkaOptionsDialog
from gui.dialogs.version_info_dialog import show_version_info_dialog
from gui.services.config_marshaller import ConfigMarshaller
from gui.services.icon_auto_loader import IconAutoLoader
from gui.services.version_info_detector import VersionInfoDetector
from gui.styles.themes import (
ThemeManager,
ThemeMode,
)
from gui.widgets.icons import IconGenerator
from utils.constants import SKIP_DIRECTORIES, get_nuitka_containing_dir, is_bundled, is_nuitka_compiled
from utils.dependency_manager import DependencyManager
from utils.gcc_downloader import GCCDownloader, validate_mingw_directory
# 导入版本信息
from version import APP_NAME, AUTHOR_EMAIL, DISPLAY_VERSION, SHOW_VIP_PRIVILEGE, get_about_html, should_show_donate_dialog
class MainWindow(QMainWindow):
"""
主应用程序窗口 - PyQt6最佳实践实现
主要改进:
- 后台任务通过 daemon Thread + pyqtSignal 跨线程通信
- 通过ThemeManager进行集中式主题管理
- 通过IconGenerator分离图标生成
- 清晰的信号/槽模式用于线程通信
- 全面使用类型提示
"""
# 用于线程安全通信的应用程序信号
log_signal = pyqtSignal(str)
finished_signal = pyqtSignal(bool, str)
update_exclude_modules_signal = pyqtSignal(str)
update_download_progress_signal = pyqtSignal(str)
gcc_download_complete_signal = pyqtSignal(str) # GCC 下载完成,参数为路径
gcc_download_reset_button_signal = pyqtSignal() # 重置下载按钮
analyze_finished_signal = pyqtSignal() # 依赖分析完成
def __init__(self) -> None:
super().__init__()
self.resize(900, 700)
# 初始化核心组件
self._init_directories()
self._init_managers()
self._init_state()
self._init_ui()
self._connect_signals()
self._load_settings()
self._apply_initial_theme()
# 延迟检查打开次数,确保主窗口已经显示
QTimer.singleShot(1000, self._check_launch_count_and_donate)
def _init_directories(self) -> None:
"""初始化应用程序目录"""
self.app_dir = self._get_app_dir()
# Config directory - 始终使用用户目录,确保配置持久化(尤其是打包后的exe)
# 这样GCC配置等可以在重启后保留
user_config_dir = os.path.join(os.path.expanduser("~"), ".python_packaging_tool")
try:
# 仅在目录首次创建时收紧权限;已存在的不强改(尊重用户自定义权限)
is_new_dir = not os.path.exists(user_config_dir)
os.makedirs(user_config_dir, exist_ok=True)
if is_new_dir:
self._restrict_dir_permissions(user_config_dir)
config_dir = user_config_dir
except Exception:
config_dir = os.path.join(self.app_dir, "config")
try:
is_new_dir = not os.path.exists(config_dir)
os.makedirs(config_dir, exist_ok=True)
if is_new_dir:
self._restrict_dir_permissions(config_dir)
except Exception:
pass
self.config_dir = config_dir
self.gcc_config_file = os.path.join(config_dir, "gcc_config.json")
self.theme_config_file = os.path.join(config_dir, "theme_config.json")
@staticmethod
def _restrict_dir_permissions(dir_path: str) -> None:
"""收紧用户配置目录权限,仅允许当前用户访问。
- Windows:通过 icacls 移除 Users 组的访问权限,仅保留当前用户
与 SYSTEM(防止同机其他标准用户读取 GCC 配置等)
- Linux/macOS:设置 0o700(仅所有者可读写执行)
- 失败时不抛异常,仅打印警告(权限收紧是防御性措施,不应阻断启动)
注意:仅在目录首次创建时调用,已存在的目录不修改(避免破坏
用户自定义的权限配置,如符号链接、网络盘等场景)。
"""
try:
if sys.platform == "win32":
# /inheritance:r 移除继承的 ACE,然后显式授予当前用户和 SYSTEM
import subprocess
username = os.environ.get("USERNAME") or os.environ.get("USER", "")
if not username:
return
subprocess.run(
[
"icacls", dir_path,
"/inheritance:r",
"/grant:r", f"{username}:(OI)(CI)F", # 完全控制,应用到子项
"/grant:r", "SYSTEM:(OI)(CI)F",
],
capture_output=True,
timeout=10,
creationflags=subprocess.CREATE_NO_WINDOW,
)
else:
# Unix: rwx------ (仅所有者)
os.chmod(dir_path, 0o700)
except Exception as e:
# 权限收紧失败不影响主流程
print(f"警告:收紧配置目录权限失败(不影响使用): {e}")
def _init_managers(self) -> None:
"""初始化管理器对象"""
# 主题和图标管理
self.icon_generator = IconGenerator(self.app_dir)
self.theme_manager = ThemeManager(self.app_dir)
# 生成主题图标
self.icon_generator.generate_theme_icons()
# 依赖管理
self.dependency_manager = DependencyManager()
# 服务层(可独立测试的业务逻辑)
self.config_marshaller = ConfigMarshaller()
self.version_detector = VersionInfoDetector()
self.icon_loader = IconAutoLoader()
# 用于后台任务的线程池
self.thread_pool = QThreadPool.globalInstance()
def _init_state(self) -> None:
"""初始化应用程序状态"""
# 日志最大化状态
self._log_maximized = False
# GCC配置状态
self.gcc_config_loaded = False
self.gcc_config_loading = False
# 下载状态
self.is_downloading = False
self.cancel_download = False
self.download_thread: Optional[threading.Thread] = None
# 打包状态
self.is_packaging = False
self.cancel_packaging = False
self.packaging_process: Optional[subprocess.Popen] = None
# 跟踪之前的项目目录和脚本路径以进行变更检测
self._previous_project_dir: Optional[str] = None
self._previous_script_path: Optional[str] = None
# 版权信息
self.version_info = {
"product_name": "",
"company_name": "",
"file_description": "",
"copyright": "Copyright © 2026",
"version": "1.0.0",
}
# 控制台自动管理(根据脚本自动判断)
self._console_auto_managed = True
# 图标手动选择标志(防止自动加载覆盖用户选择)
self._icon_manually_set = False
# Nuitka 高级选项(基于最佳实践)
self.nuitka_advanced_options = {}
def _connect_signals(self) -> None:
"""连接应用程序信号到槽"""
self.log_signal.connect(self._on_log_message)
self.finished_signal.connect(self._on_task_finished)
self.update_exclude_modules_signal.connect(self._on_exclude_modules_update)
self.update_download_progress_signal.connect(self._on_download_progress_update)
self.gcc_download_complete_signal.connect(self._on_gcc_download_complete)
self.gcc_download_reset_button_signal.connect(self._on_gcc_download_reset_button)
self.analyze_finished_signal.connect(self._on_analyze_finished)
# 主题改变信号
self.theme_manager.theme_changed.connect(self._on_theme_changed)
def _load_settings(self) -> None:
"""加载保存的设置"""
self._load_theme_setting()
# 自动加载 GCC 配置(如果在 Nuitka 模式下)
if hasattr(self, "nuitka_radio") and self.nuitka_radio.isChecked():
self.load_gcc_config()
def _apply_initial_theme(self) -> None:
"""应用初始主题"""
self.apply_theme()
self._update_theme_button_state()
# =========================================================================
# Directory and Resource Management
# =========================================================================
def _get_app_dir(self) -> str:
"""
获取应用程序目录(兼容打包后的exe)。
对于打包后的exe,使用临时目录以避免污染exe目录。
"""
if is_bundled():
app_temp_dir = os.path.join(tempfile.gettempdir(), "python_packaging_tool")
try:
os.makedirs(app_temp_dir, exist_ok=True)
return app_temp_dir
except Exception:
return os.path.dirname(sys.executable)
else:
return os.path.dirname(os.path.dirname(__file__))
def _get_resource_path(self, relative_path: str) -> Optional[str]:
"""获取资源文件路径(兼容 PyInstaller 和 Nuitka 打包后的 exe)"""
if is_bundled():
possible_paths = []
# Nuitka onefile 解包目录(优先)
if is_nuitka_compiled():
nuitka_dir = get_nuitka_containing_dir()
if nuitka_dir:
possible_paths.append(os.path.join(nuitka_dir, relative_path))
if relative_path.endswith("icon.ico"):
possible_paths.append(os.path.join(nuitka_dir, "icon.ico"))
# PyInstaller单文件模式使用_MEIPASS
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
possible_paths.append(os.path.join(meipass, relative_path))
if relative_path.endswith("icon.ico"):
possible_paths.append(os.path.join(meipass, "icon.ico"))
possible_paths.extend(
[
os.path.join(os.path.dirname(sys.executable), relative_path),
os.path.join(os.path.dirname(sys.executable), "icon.ico")
if relative_path.endswith("icon.ico")
else None,
os.path.join(os.getcwd(), relative_path),
os.path.join(os.getcwd(), "icon.ico") if relative_path.endswith("icon.ico") else None,
relative_path,
]
)
# 过滤None值
possible_paths = [p for p in possible_paths if p is not None]
for path in possible_paths:
if os.path.exists(path):
return path
# 如果找不到文件,对于图标文件,尝试从exe资源中提取
if relative_path.endswith("icon.ico") and sys.platform == "win32":
# 返回exe路径,Qt会自动从exe资源中提取图标
return sys.executable
return None
else:
return os.path.join(os.path.dirname(os.path.dirname(__file__)), relative_path)
# =========================================================================
# UI Initialization
# =========================================================================
def _init_ui(self) -> None:
"""初始化用户界面"""
# 创建菜单栏
self._create_menu_bar()
central_widget = QWidget()
central_widget.setObjectName("centralWidget")
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setSpacing(10)
main_layout.setContentsMargins(15, 15, 15, 15)
# Build UI sections
self._create_file_selection_group(main_layout)
self._create_tool_selection_group(main_layout)
self._create_options_group(main_layout)
self._create_log_group(main_layout)
self._create_button_bar(main_layout)
# Set window icon
self._set_window_icon()
# Initial log message
self.append_log("准备就绪...")
def _create_menu_bar(self) -> None:
"""创建菜单栏"""
menubar = self.menuBar()
if menubar is None:
return
# ===== 文件菜单 =====
file_menu = menubar.addMenu("文件")
if file_menu is None:
return
# 主题切换子菜单
theme_menu = QMenu("主题切换", self)
self.theme_system_action = QAction("🖥️ 跟随系统", self)
self.theme_system_action.setCheckable(True)
self.theme_system_action.setChecked(True)
self.theme_system_action.triggered.connect(lambda: self.set_theme(ThemeMode.SYSTEM))
theme_menu.addAction(self.theme_system_action)
self.theme_light_action = QAction("☀️ 浅色模式", self)
self.theme_light_action.setCheckable(True)
self.theme_light_action.triggered.connect(lambda: self.set_theme(ThemeMode.LIGHT))
theme_menu.addAction(self.theme_light_action)
self.theme_dark_action = QAction("🌙 深色模式", self)
self.theme_dark_action.setCheckable(True)
self.theme_dark_action.triggered.connect(lambda: self.set_theme(ThemeMode.DARK))
theme_menu.addAction(self.theme_dark_action)
file_menu.addMenu(theme_menu)
file_menu.addSeparator()
# 退出
exit_action = QAction("退出", self)
exit_action.setShortcut("Ctrl+Q")
exit_action.triggered.connect(self.close)
file_menu.addAction(exit_action)
# ===== 帮助菜单 =====
help_menu = menubar.addMenu("帮助")
if help_menu is None:
return
# 问题反馈
feedback_action = QAction("问题反馈", self)
feedback_action.triggered.connect(self._show_feedback_dialog)
help_menu.addAction(feedback_action)
# 文澜书库
wklan_action = QAction("文澜书库", self)
wklan_action.triggered.connect(lambda: webbrowser.open("https://books.wklan.com"))
help_menu.addAction(wklan_action)
# 关于
about_action = QAction("关于", self)
about_action.triggered.connect(self._show_about_dialog)
help_menu.addAction(about_action)
# ===== 捐赠菜单 =====
donate_action = QAction("捐赠", self)
donate_action.triggered.connect(self._show_donate_dialog)
menubar.addAction(donate_action)
def _show_feedback_dialog(self) -> None:
"""显示问题反馈对话框(实现已抽离到 gui.dialogs.feedback_dialog)。"""
show_feedback_dialog(
parent=self,
theme_manager=self.theme_manager,
app_name=APP_NAME,
display_version=DISPLAY_VERSION,
author_email=AUTHOR_EMAIL,
show_vip_privilege=SHOW_VIP_PRIVILEGE,
config=self.get_config(),
log_text=self.log_text.toPlainText(),
)
def _show_donate_dialog(self) -> None:
"""显示捐赠对话框(实现已抽离到 gui.dialogs.donate_dialog)。"""
show_donate_dialog(self, self.theme_manager, __file__)
def _check_launch_count_and_donate(self) -> None:
"""检查软件打开次数并根据规则弹出捐赠框。
弹出规则由 version.py 中的 DONATE_PROMPT_INITIAL_COUNTS 和
DONATE_PROMPT_INTERVAL 控制,便于无需改代码即可调整频率。
"""
settings = QSettings("PythonPackagingTool", "LaunchCount")
count = settings.value("count", 0, type=int)
count += 1
settings.setValue("count", count)
if should_show_donate_dialog(count):
self._show_donate_dialog()
def _show_about_dialog(self) -> None:
"""显示关于对话框(实现已抽离到 gui.dialogs.about_dialog)。"""
show_about_dialog(self, self.theme_manager, self.windowIcon(), get_about_html())
def _create_file_selection_group(self, parent_layout: QVBoxLayout) -> None:
"""创建文件选择组"""
self.file_group = file_group = QGroupBox("文件选择")
file_layout = QVBoxLayout(file_group)
# Project directory
project_layout = QHBoxLayout()
project_layout.addWidget(QLabel("项目目录:"))
self.project_dir_edit = QLineEdit()
self.project_dir_edit.setPlaceholderText("可选,选择Python项目根目录")
self.project_dir_edit.textChanged.connect(self.on_project_dir_changed)
project_layout.addWidget(self.project_dir_edit)
project_btn = QPushButton("浏览")
project_btn.setStyleSheet("QPushButton { min-width: 0; }") # 覆盖全局样式,让按钮宽度适应文字
project_btn.clicked.connect(self.browse_project_dir)
project_layout.addWidget(project_btn)
file_layout.addLayout(project_layout)
# 运行脚本
script_layout = QHBoxLayout()
script_layout.addWidget(QLabel("运行脚本:"))
self.script_path_edit = QLineEdit()
self.script_path_edit.setPlaceholderText("必选,指定要执行的Python脚本")
self.script_path_edit.textChanged.connect(self.on_script_path_changed)
script_layout.addWidget(self.script_path_edit)
script_btn = QPushButton("浏览")
script_btn.setStyleSheet("QPushButton { min-width: 0; }") # 覆盖全局样式,让按钮宽度适应文字
script_btn.clicked.connect(self.browse_script)
script_layout.addWidget(script_btn)
file_layout.addLayout(script_layout)
# 输出目录
output_layout = QHBoxLayout()
output_layout.addWidget(QLabel("输出目录:"))
self.output_dir_edit = QLineEdit()
self.output_dir_edit.setPlaceholderText("可选,默认为项目目录下的build文件夹")
output_layout.addWidget(self.output_dir_edit)
output_btn = QPushButton("浏览")
output_btn.setStyleSheet("QPushButton { min-width: 0; }") # 覆盖全局样式,让按钮宽度适应文字
output_btn.clicked.connect(self.browse_output_dir)
output_layout.addWidget(output_btn)
file_layout.addLayout(output_layout)
# 图标路径
icon_layout = QHBoxLayout()
icon_layout.addWidget(QLabel("程序图标:"))
self.icon_path_edit = QLineEdit()
self.icon_path_edit.setPlaceholderText("可选,支持 .ico/.png/.svg 等格式,自动转换为多尺寸图标")
icon_layout.addWidget(self.icon_path_edit)
icon_btn = QPushButton("浏览")
icon_btn.setStyleSheet("QPushButton { min-width: 0; }") # 覆盖全局样式,让按钮宽度适应文字
icon_btn.clicked.connect(self.browse_icon)
icon_layout.addWidget(icon_btn)
file_layout.addLayout(icon_layout)
# 程序名称
name_layout = QHBoxLayout()
name_layout.addWidget(QLabel("程序名称:"))
self.program_name_edit = QLineEdit()
self.program_name_edit.setPlaceholderText("可选,指定打包后的exe文件名(不含.exe扩展名)")
name_layout.addWidget(self.program_name_edit)
file_layout.addLayout(name_layout)
# Python路径
python_layout = QHBoxLayout()
python_layout.addWidget(QLabel("Python路径:"))
self.python_path_edit = QLineEdit()
self.python_path_edit.setPlaceholderText("可选,留空将自动检测系统Python")
python_layout.addWidget(self.python_path_edit)
python_btn = QPushButton("浏览")
python_btn.setStyleSheet("QPushButton { min-width: 0; }") # 覆盖全局样式,让按钮宽度适应文字
python_btn.clicked.connect(self.browse_python)
python_layout.addWidget(python_btn)
file_layout.addLayout(python_layout)
parent_layout.addWidget(file_group)
def _create_tool_selection_group(self, parent_layout: QVBoxLayout) -> None:
"""创建工具选择组"""
self.tool_group = tool_group = QGroupBox("打包工具")
tool_layout = QVBoxLayout(tool_group)
tool_radio_layout = QHBoxLayout()
self.nuitka_radio = QRadioButton("Nuitka")
self.nuitka_radio.setChecked(True)
self.nuitka_radio.toggled.connect(self.on_tool_changed)
self.pyinstaller_radio = QRadioButton("PyInstaller")
self.pyinstaller_radio.toggled.connect(self.on_tool_changed)
self.cx_freeze_radio = QRadioButton("cx_Freeze")
self.cx_freeze_radio.toggled.connect(self.on_tool_changed)
tool_radio_layout.addWidget(self.nuitka_radio)
tool_radio_layout.addWidget(self.pyinstaller_radio)
tool_radio_layout.addWidget(self.cx_freeze_radio)
tool_radio_layout.addStretch()
tool_layout.addLayout(tool_radio_layout)
# GCC path widget (Nuitka only)
self.gcc_widget = QWidget()
gcc_widget_layout = QVBoxLayout(self.gcc_widget)
gcc_widget_layout.setContentsMargins(0, 0, 0, 0)
gcc_widget_layout.setSpacing(5)
gcc_layout = QHBoxLayout()
gcc_layout.addWidget(QLabel("GCC编译链:"))
self.gcc_path_edit = QLineEdit()
self.gcc_path_edit.setPlaceholderText("必选,指定GCC工具链目录,一般为mingw64或mingw32目录")
self.gcc_path_edit.textChanged.connect(self.on_gcc_path_changed)
gcc_layout.addWidget(self.gcc_path_edit)
self.gcc_browse_btn = QPushButton("浏览")
self.gcc_browse_btn.setStyleSheet("QPushButton { min-width: 0; }") # 覆盖全局样式,让按钮宽度适应文字
self.gcc_browse_btn.clicked.connect(self.browse_gcc)
gcc_layout.addWidget(self.gcc_browse_btn)
self.gcc_download_btn = QPushButton("自动下载")
self.gcc_download_btn.clicked.connect(self.download_gcc)
gcc_layout.addWidget(self.gcc_download_btn)
# Nuitka 高级选项按钮
self.nuitka_options_btn = QPushButton("高级选项")
self.nuitka_options_btn.setToolTip("配置 Nuitka 高级选项(基于官方最佳实践)")
self.nuitka_options_btn.clicked.connect(self._show_nuitka_options_dialog)
gcc_layout.addWidget(self.nuitka_options_btn)
gcc_widget_layout.addLayout(gcc_layout)
# GCC download progress label
self.gcc_download_label = QLabel("")
gcc_widget_layout.addWidget(self.gcc_download_label)
tool_layout.addWidget(self.gcc_widget)
self.gcc_widget.setVisible(self.nuitka_radio.isChecked())
parent_layout.addWidget(tool_group)
def _create_options_group(self, parent_layout: QVBoxLayout) -> None:
"""Create packaging options group"""
self.options_group = options_group = QGroupBox("打包选项")
options_layout = QVBoxLayout(options_group)
# 复选框行
checkboxes_layout = QHBoxLayout()
self.onefile_check = QCheckBox("单文件模式")
self.onefile_check.setChecked(True)
self.onefile_check.setToolTip("打包成单个exe文件")
self.clean_check = QCheckBox("清理构建缓存")
self.clean_check.setChecked(True)
self.clean_check.setToolTip("打包前清理临时文件")
self.venv_check = QCheckBox("使用虚拟环境")
self.venv_check.setChecked(True)
self.venv_check.setToolTip("在虚拟环境中打包以隔离依赖")
self.upx_check = QCheckBox("使用UPX压缩")
self.upx_check.setChecked(True) # Nuitka 默认开启 UPX
self.upx_check.setToolTip("压缩exe体积(需安装UPX)")
# 初始可见性根据工具选择决定
if hasattr(self, "nuitka_radio"):
is_nuitka = self.nuitka_radio.isChecked()
self.upx_check.setVisible(is_nuitka)
if not is_nuitka:
self.upx_check.setChecked(False)
self.console_check = QCheckBox("显示控制台窗口")
self.console_check.setChecked(False)
self.console_check.setToolTip("运行时是否显示CMD窗口")
self.console_check.stateChanged.connect(self._on_console_check_changed)
self.version_info_check = QCheckBox("添加版权信息")
self.version_info_check.setChecked(False)
self.version_info_check.setToolTip("配置软件版权、公司等信息")
self.version_info_check.clicked.connect(self._on_version_info_check_clicked)
checkboxes_layout.addWidget(self.onefile_check)
checkboxes_layout.addWidget(self.clean_check)
checkboxes_layout.addWidget(self.venv_check)
checkboxes_layout.addWidget(self.upx_check)
checkboxes_layout.addWidget(self.console_check)
checkboxes_layout.addWidget(self.version_info_check)
checkboxes_layout.addStretch()
options_layout.addLayout(checkboxes_layout)
# Exclude modules row
exclude_layout = QHBoxLayout()
exclude_layout.addWidget(QLabel("排除模块:"))
self.exclude_modules_edit = QLineEdit()
self.exclude_modules_edit.setPlaceholderText(
"可选,默认会自动排除,你也可以手动追加需要排除的模块,多个模块用逗号分隔,如:wx,wxPython,ui"
)
exclude_layout.addWidget(self.exclude_modules_edit)
self.analyze_btn = QPushButton("分析依赖")
self.analyze_btn.setMinimumHeight(35)
self.analyze_btn.setStyleSheet("QPushButton { min-width: 0; }") # 覆盖全局样式,让按钮宽度适应文字
self.analyze_btn.clicked.connect(self.analyze_dependencies)
exclude_layout.addWidget(self.analyze_btn)
options_layout.addLayout(exclude_layout)
parent_layout.addWidget(options_group)
def _create_log_group(self, parent_layout: QVBoxLayout) -> None:
"""创建日志输出组"""
self.log_group = log_group = QGroupBox("日志输出")
log_layout = QVBoxLayout(log_group)
# 日志区域顶部工具栏(放置最大化按钮和复制日志按钮)
log_toolbar = QHBoxLayout()
log_toolbar.setContentsMargins(0, 0, 0, 0)
# 一键复制完整日志按钮
self.log_copy_btn = QPushButton("一键复制完整日志")
self.log_copy_btn.setFixedHeight(24)
self.log_copy_btn.setCursor(Qt.CursorShape.PointingHandCursor)
self.log_copy_btn.setToolTip("复制所有日志内容到剪贴板")
self.log_copy_btn.setStyleSheet("QPushButton { padding: 0px 8px; font-size: 12px;}")
self.log_copy_btn.clicked.connect(self._copy_all_log)
log_toolbar.addWidget(self.log_copy_btn)
log_toolbar.addStretch()
self.log_maximize_btn = QPushButton()
self.log_maximize_btn.setFixedSize(22, 22)
self.log_maximize_btn.setCursor(Qt.CursorShape.PointingHandCursor)
self.log_maximize_btn.setToolTip("最大化日志")
self.log_maximize_btn.clicked.connect(self._toggle_log_maximize)
self._update_log_maximize_btn_icon()
log_toolbar.addWidget(self.log_maximize_btn)
log_layout.addLayout(log_toolbar)
self.log_text = QTextEdit()
self.log_text.setReadOnly(True)
self.log_text.setFont(QFont("Consolas", 9))
log_layout.addWidget(self.log_text)
parent_layout.addWidget(log_group)
def _create_button_bar(self, parent_layout: QVBoxLayout) -> None:
"""Create bottom button bar"""
self.btn_bar_widget = QWidget()
btn_layout = QHBoxLayout(self.btn_bar_widget)
btn_layout.setContentsMargins(0, 0, 0, 0)
# 问题反馈文字链接(左侧)
colors = self.theme_manager.colors
self.feedback_label = QLabel(
f'<a href="#" style="text-decoration: none; color: {colors.text_primary};">问题反馈</a>'
)
self.feedback_label.setOpenExternalLinks(False)
self.feedback_label.linkActivated.connect(lambda: self._show_feedback_dialog())
self.feedback_label.setCursor(Qt.CursorShape.PointingHandCursor)
btn_layout.addWidget(self.feedback_label)
# 间距
btn_layout.addSpacing(15)
# 请喝咖啡文字链接
self.donate_label = QLabel(
f'<a href="#" style="text-decoration: none; color: {colors.text_primary};">☕ 请作者喝杯咖啡</a>'
)
self.donate_label.setOpenExternalLinks(False)
self.donate_label.linkActivated.connect(lambda: self._show_donate_dialog())
self.donate_label.setCursor(Qt.CursorShape.PointingHandCursor)
btn_layout.addWidget(self.donate_label)
btn_layout.addStretch()
# Action buttons
self.package_btn = QPushButton("开始打包")
self.package_btn.setMinimumHeight(40)
self.package_btn.setMinimumWidth(120)
self.package_btn.setProperty("buttonType", "primary")
self.package_btn.clicked.connect(self.toggle_packaging)
self.clear_btn = QPushButton("清空日志")
self.clear_btn.setMinimumHeight(40)
self.clear_btn.setMinimumWidth(120)
self.clear_btn.clicked.connect(self.clear_log)
# 设置清空日志按钮为灰色背景
self.clear_btn.setProperty("buttonType", "secondary")
# 先添加清空日志按钮,再添加开始打包按钮
btn_layout.addWidget(self.clear_btn)
btn_layout.addWidget(self.package_btn)
parent_layout.addWidget(self.btn_bar_widget)
def _on_version_info_check_clicked(self, checked: bool) -> None:
"""版权信息复选框被点击时触发(使用 clicked 信号更可靠)"""
if checked:
# 显示对话框
self._show_version_info_dialog()
def _detect_version_info_from_project(self) -> Dict[str, str]:
"""从项目目录检测版本信息(委托给 VersionInfoDetector)"""
project_dir = self.project_dir_edit.text().strip() if hasattr(self, "project_dir_edit") else ""
script_path = self.script_path_edit.text().strip() if hasattr(self, "script_path_edit") else ""
return self.version_detector.detect(project_dir, script_path)
def _find_version_info_source_file(self, project_dir: str, script_path: str) -> Optional[str]:
"""查找实际使用的版本信息源文件路径(用于在对话框中显示来源提示)。
查找顺序:项目根目录 → 常见子目录(core/src/lib/utils/config)→ 递归查找 → 脚本本身。
"""
if project_dir and os.path.isdir(project_dir):
# 1. 项目根目录
for vf in ["version.py", "main.py"]:
vf_path = os.path.join(project_dir, vf)
if os.path.exists(vf_path):
return vf_path
# 2. 常见子目录
skip_dirs = set(SKIP_DIRECTORIES) | {".tox", ".pytest_cache", "egg-info", ".eggs"}
priority_dirs = ["core", "src", "lib", "utils", "config"]
for priority_dir in priority_dirs:
for vf in ["version.py", "main.py"]:
vf_path = os.path.join(project_dir, priority_dir, vf)
if os.path.exists(vf_path):
return vf_path
# 3. 递归查找
for root, dirs, files in os.walk(project_dir):
dirs[:] = [d for d in dirs if d not in skip_dirs and not d.startswith(".")]
for vf in ["version.py", "main.py"]:
if vf in files:
return os.path.join(root, vf)
# 4. 脚本本身
if script_path and os.path.isfile(script_path):
if script_path.lower().endswith((".py", ".pyw")):
return script_path
return None
def _show_version_info_dialog(self) -> None:
"""显示版权信息配置对话框(实现已抽离到 gui.dialogs.version_info_dialog)。"""
# 1. 检测版本信息
detected_info = self._detect_version_info_from_project()
project_dir = self.project_dir_edit.text().strip() if hasattr(self, "project_dir_edit") else ""
script_path = self.script_path_edit.text().strip() if hasattr(self, "script_path_edit") else ""
source_file = self._find_version_info_source_file(project_dir, script_path) if any(detected_info.values()) else None
# 2. Nuitka SDK 支持检测
is_nuitka = self.nuitka_radio.isChecked()
sdk_supported = False
sdk_message = ""
if is_nuitka:
from core.packager import Packager
temp_packager = Packager()
sdk_supported, sdk_message = temp_packager.check_windows_sdk_support()
# 3. 委托给独立对话框组件
result_info = show_version_info_dialog(
parent=self,
theme_manager=self.theme_manager,
current_info=self.version_info,
detected_info=detected_info,
is_nuitka=is_nuitka,
sdk_supported=sdk_supported,
sdk_message=sdk_message,
source_file=source_file,
project_dir=project_dir or None,
)
# 4. 处理结果
if result_info is not None:
self.version_info = result_info
self.append_log(f"已配置版权信息: {self.version_info.get('product_name', 'N/A')}")
else:
# 用户取消,取消勾选(setChecked 不会触发 clicked 信号,无需 blockSignals)
self.version_info_check.setChecked(False)
def _set_window_icon(self) -> None:
"""设置窗口图标(兼容 PyInstaller 和 Nuitka 打包后的 exe)"""
try:
icon_filename = "icon.ico"
possible_paths = []
if is_bundled():
# Nuitka onefile 解包目录(优先)
if is_nuitka_compiled():
nuitka_dir = get_nuitka_containing_dir()
if nuitka_dir:
possible_paths.extend(
[
os.path.join(nuitka_dir, icon_filename),
os.path.join(nuitka_dir, "resources", "icons", icon_filename),
]
)
# PyInstaller的_MEIPASS
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
possible_paths.extend(
[
os.path.join(meipass, icon_filename),
os.path.join(meipass, "resources", "icons", icon_filename),
]
)
# exe目录和当前工作目录
exe_dir = os.path.dirname(sys.executable)
possible_paths.extend(
[
os.path.join(exe_dir, icon_filename),
os.path.join(exe_dir, "resources", "icons", icon_filename),
os.path.join(os.getcwd(), icon_filename),
]
)
for path in possible_paths:
if os.path.exists(path):
self.setWindowIcon(QIcon(path))
return
else:
# 开发模式
icon_path = self._get_resource_path("resources/icons/icon.ico")
if icon_path and os.path.exists(icon_path):
self.setWindowIcon(QIcon(icon_path))
except Exception as e:
print(f"加载图标失败: {e}")
# =========================================================================
# Theme Management
# =========================================================================
def set_theme(self, mode: ThemeMode) -> None:
"""设置主题模式"""
self.theme_manager.current_mode = mode
self._update_theme_button_state()
self._save_theme_setting()
self.apply_theme()
def apply_theme(self) -> None:
"""将当前主题应用到界面"""
app = QApplication.instance()
if not app:
return
is_dark = self.theme_manager.is_dark
# 根据主题获取图标路径(从resources/icons目录)
if is_dark:
check_icon = self.icon_generator.get_icon_path("resources/icons/check_dark.png")
radio_icon = self.icon_generator.get_icon_path("resources/icons/radio_dark.png")
else:
check_icon = self.icon_generator.get_icon_path("resources/icons/check_light.png")
radio_icon = self.icon_generator.get_icon_path("resources/icons/radio_light.png")
# 应用样式表
stylesheet = self.theme_manager.get_stylesheet(check_icon, radio_icon)
self.setStyleSheet(stylesheet)
# 更新GCC下载标签颜色
if hasattr(self, "gcc_download_label"):
color = self.theme_manager.get_label_color("warning" if is_dark else "accent")
self.gcc_download_label.setStyleSheet(f"color: {color};")
# 更新问题反馈文字颜色
if hasattr(self, "feedback_label"):
colors = self.theme_manager.colors
self.feedback_label.setText(
f'<a href="#" style="text-decoration: none; color: {colors.text_primary};">问题反馈</a>'
)
# 更新捐赠文字颜色
if hasattr(self, "donate_label"):
colors = self.theme_manager.colors
self.donate_label.setText(
f'<a href="#" style="text-decoration: none; color: {colors.text_primary};">☕ 请作者喝杯咖啡</a>'
)
# 更新日志最大化按钮图标(跟随主题颜色)
if hasattr(self, "log_maximize_btn"):
self._update_log_maximize_btn_icon()
def _update_theme_button_state(self) -> None:
"""更新主题菜单状态以反映当前设置"""
mode = self.theme_manager.current_mode
self.theme_system_action.setChecked(mode == ThemeMode.SYSTEM)
self.theme_light_action.setChecked(mode == ThemeMode.LIGHT)
self.theme_dark_action.setChecked(mode == ThemeMode.DARK)
def _load_theme_setting(self) -> None:
"""从配置文件加载主题设置"""
try:
if os.path.exists(self.theme_config_file):
with open(self.theme_config_file, "r", encoding="utf-8") as f:
config = json.load(f)
mode_str = config.get("theme_mode", "system")
mode_map = {
"system": ThemeMode.SYSTEM,
"light": ThemeMode.LIGHT,
"dark": ThemeMode.DARK,
}
self.theme_manager.current_mode = mode_map.get(mode_str, ThemeMode.SYSTEM)
except Exception as e:
print(f"加载主题设置失败: {e}")
def _save_theme_setting(self) -> None:
"""保存主题设置到配置文件"""
try:
config = {"theme_mode": self.theme_manager.current_mode.value}
with open(self.theme_config_file, "w", encoding="utf-8") as f:
json.dump(config, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"保存主题设置失败: {e}")
@pyqtSlot(bool)
def _on_theme_changed(self, is_dark: bool) -> None:
"""处理主题改变信号"""
self.apply_theme()
# =========================================================================
# 信号槽
# =========================================================================
@pyqtSlot(str)
def _on_log_message(self, message: str) -> None: