Repository navigation
Expand file tree
/
Copy pathProgram_Launcher.py
More file actions
3763 lines (3156 loc) · 146 KB
/
Copy pathProgram_Launcher.py
File metadata and controls
3763 lines (3156 loc) · 146 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
import os
import sys
import time
import threading
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
# 更鲁棒的 win32 模块导入处理
def setup_win32_imports():
"""设置 win32 模块的导入路径"""
if getattr(sys, 'frozen', False):
# 打包后的环境
base_path = sys._MEIPASS if hasattr(sys, '_MEIPASS') else os.path.dirname(sys.executable)
# 添加所有可能的路径
possible_paths = [
base_path,
os.path.join(base_path, 'win32'),
os.path.join(base_path, 'win32com'),
os.path.join(base_path, 'win32ctypes'),
os.path.join(base_path, 'pywin32-ctypes'),
os.path.join(base_path, 'pywin32_system32'),
os.path.join(base_path, 'win32ctypes', 'pywin32'),
os.path.join(base_path, 'win32ctypes', 'win32api'),
]
for path in possible_paths:
if os.path.exists(path):
sys.path.insert(0, path)
# 设置环境变量
os.environ['PATH'] = base_path + os.pathsep + os.environ.get('PATH', '')
# 尝试设置 PYTHONPATH
python_paths = [p for p in possible_paths if os.path.exists(p)]
if python_paths:
os.environ['PYTHONPATH'] = os.pathsep.join(python_paths) + os.pathsep + os.environ.get('PYTHONPATH', '')
# 调用设置
setup_win32_imports()
# 现在尝试导入 win32 模块,使用更灵活的方式
win32_modules_available = False
try:
# 尝试各种导入方式
try:
import win32api
import win32con
import win32gui
import win32process
win32_modules_available = True
except ImportError:
try:
# 尝试从 win32ctypes 导入
import win32ctypes.pywin32.win32api as win32api
import win32ctypes.pywin32.win32con as win32con
import win32ctypes.pywin32.win32gui as win32gui
import win32ctypes.pywin32.win32process as win32process
win32_modules_available = True
except ImportError:
# 最后尝试
import ctypes
# 创建简单的包装器
class Win32Wrapper:
@staticmethod
def MessageBox(hWnd, text, caption, type):
return ctypes.windll.user32.MessageBoxW(hWnd, text, caption, type)
win32api = Win32Wrapper()
except Exception as e:
print(f"Warning: Failed to import win32 modules: {e}")
# 如果某些模块不可用,创建占位符
if not win32_modules_available:
# 创建简单的替代实现
class Win32Fallback:
def __getattr__(self, name):
return lambda *args, **kwargs: None
win32api = Win32Fallback()
win32con = Win32Fallback()
win32gui = Win32Fallback()
win32process = Win32Fallback()
# 禁用 PyInstaller 时间戳设置
def disable_pyinstaller_timestamp():
"""禁用 PyInstaller 的时间戳设置"""
try:
import PyInstaller.utils.win32.versioninfo
PyInstaller.utils.win32.versioninfo.SetVersion = lambda *args, **kwargs: None
except ImportError:
pass
def disable_timestamp_check():
if getattr(sys, 'frozen', False):
try:
import PyInstaller.utils.win32.versioninfo
PyInstaller.utils.win32.versioninfo.SetVersion = lambda *args, **kwargs: None
except ImportError:
pass
# 在程序开始处调用
disable_pyinstaller_timestamp()
disable_timestamp_check()
import shutil
import glob
import datetime
import pinyin
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QLineEdit, QTabWidget, QMessageBox,
QFileDialog, QGroupBox, QScrollArea, QSizePolicy, QSpacerItem,
QMenu, QTableWidget, QTableWidgetItem, QDialog, QLayout,
QCheckBox, QComboBox, QInputDialog, QToolButton,
QSpinBox, QListWidget, QListWidgetItem, QTextEdit)
from PySide6.QtCore import Qt, QSize, QSettings, QTimer, QRect, QPoint, Signal, QThread, QObject
from PySide6.QtGui import QIcon, QColor, QTextCursor, QTextCharFormat, QFont, QPixmap, QKeySequence, QPalette, QAction, QCursor
from PIL import Image, ImageDraw, ImageFont
import sqlite3
import win32api
import win32con
import win32process
import win32gui
from typing import Optional, List, Tuple, Dict, Any
# 程序基目录:打包后为 exe 所在目录,源码运行为本文件所在目录(资源/缓存统一用此定位,Nuitka 打包后 __file__ 不可靠)
if getattr(sys, 'frozen', False):
BASE_DIR = os.path.dirname(os.path.abspath(sys.executable))
else:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class ProjectInfo:
"""项目信息元数据(集中管理所有项目相关信息)"""
VERSION = "3.17"
BUILD_DATE = "2026-08-19"
AUTHOR = "杜玛"
LICENSE = "MIT"
COPYRIGHT = "© 永久 杜玛"
URL = "https://github.com/duma520"
MAINTAINER_EMAIL = "不提供"
NAME = "程序启动器"
DESCRIPTION = "程序启动器,基于PySide6的桌面应用程序"
HELP_TEXT = """
使用说明:
1. 搜索功能: 在顶部搜索框中输入关键词可以快速查找分组或按钮
2. 批量操作: 右键按钮可以选择批量操作
3. 启动参数: 编辑按钮时可以设置启动参数和工作目录
4. 管理员权限: 可以设置以管理员权限运行程序
5. 图标支持: 自动提取exe图标或自定义图标
6. 收藏功能: 可以将常用程序置顶
"""
@classmethod
def get_metadata(cls) -> dict:
"""获取主要元数据字典"""
return {
'version': cls.VERSION,
'author': cls.AUTHOR,
'license': cls.LICENSE,
'url': cls.URL
}
@classmethod
def get_header(cls) -> str:
"""生成标准化的项目头信息"""
return f"{cls.NAME} {cls.VERSION} | {cls.LICENSE} License | {cls.URL}"
# 马卡龙色系定义
class MacaronColors:
# 粉色系
SAKURA_PINK = QColor(255, 183, 206) # 樱花粉
ROSE_PINK = QColor(255, 154, 162) # 玫瑰粉
# 蓝色系
SKY_BLUE = QColor(162, 225, 246) # 天空蓝
LILAC_MIST = QColor(230, 230, 250) # 淡丁香
# 绿色系
MINT_GREEN = QColor(181, 234, 215) # 薄荷绿
APPLE_GREEN = QColor(212, 241, 199) # 苹果绿
# 黄色/橙色系
LEMON_YELLOW = QColor(255, 234, 165) # 柠檬黄
BUTTER_CREAM = QColor(255, 248, 184) # 奶油黄
PEACH_ORANGE = QColor(255, 218, 193) # 蜜桃橙
# 紫色系
LAVENDER = QColor(199, 206, 234) # 薰衣草紫
TARO_PURPLE = QColor(216, 191, 216) # 香芋紫
# 中性色
CARAMEL_CREAM = QColor(240, 230, 221) # 焦糖奶霜
class FlowLayout(QLayout):
"""自定义流式布局,实现从左到右、自动换行的布局效果"""
def __init__(self, parent=None, margin=10, spacing=10):
super().__init__(parent)
self._items = []
self._margin = margin
self._spacing = spacing
def addItem(self, item):
self._items.append(item)
def count(self):
return len(self._items)
def itemAt(self, index):
if 0 <= index < len(self._items):
return self._items[index]
return None
def takeAt(self, index):
if 0 <= index < len(self._items):
return self._items.pop(index)
return None
def expandingDirections(self):
return Qt.Orientations(Qt.Orientation(0))
def hasHeightForWidth(self):
return True
def heightForWidth(self, width):
return self._doLayout(QRect(0, 0, width, 0), True)
def setGeometry(self, rect):
super().setGeometry(rect)
self._doLayout(rect, False)
def sizeHint(self):
return self.minimumSize()
def minimumSize(self):
size = QSize()
for item in self._items:
size = size.expandedTo(item.minimumSize())
margin = self._margin
return QSize(size.width() + 2 * margin, size.height() + 2 * margin)
def _doLayout(self, rect, test_only):
margin = self._margin
spacing = self._spacing
x = rect.x() + margin
y = rect.y() + margin
line_height = 0
for item in self._items:
wid = item.widget()
space_x = spacing
space_y = spacing
next_x = x + item.sizeHint().width() + space_x
if next_x - space_x > rect.right() and line_height > 0:
x = rect.x() + margin
y = y + line_height + space_y
next_x = x + item.sizeHint().width() + space_x
line_height = 0
if not test_only:
item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))
x = next_x
line_height = max(line_height, item.sizeHint().height())
return y + line_height - rect.y()
# ===================== 图标方案配置(设置,实时自动保存 + 持久保存) =====================
_ICON_SCHEME = 1 # 当前采用的图标方案(1=方案1;2=方案2 自定义顺序;100+=用户另存的自定义方案)
_CUSTOM_SCHEME_START = 100 # 用户另存的自定义方案 id 起始
# 可调整顺序的步骤(方案2 / 自定义方案可重新排列 ①~⑤;⑥⑦为固定兜底/保险)
ICON_STEPS = {
1: "① exe/dll 等可执行文件自带图标 → extract_exe_icon",
2: "② 程序所在目录下自带的图标文件 → find_icon_in_directory",
3: "③ 图标库 resource\\icons 精确匹配 → find_icon_in_library",
4: "④ 调用 Windows 系统图标 → extract_system_icon_os",
5: "⑤ 从 Windows 图标资源文件中提取 → extract_icon_resource",
}
# 固定兜底/保险(不可调整顺序)
ICON_TAIL = (
"(以下两步为兜底 / 保险,顺序固定,不可调整)\n"
"⑥ 兜底:默认图标(blank.svg) → find_default_icon_in_library\n"
"⑦ 最终保险:按类型生成默认图标 → generate_default_icon"
)
# 内置方案定义(order 为可调整步骤①~⑤的执行顺序)
ICON_SCHEMES = {
1: {
"name": "方案1:默认方案(固定顺序,推荐)",
"order": [1, 2, 3, 4, 5],
"editable": False,
},
2: {
"name": "方案2:自定义逻辑顺序",
"order": [1, 2, 3, 4, 5], # 用户可在设置中调整并实时保存
"editable": True,
},
}
def _step_text(order: list) -> str:
"""把步骤顺序渲染为多行说明文本"""
lines = []
for i, s in enumerate(order, 1):
lines.append(f"第{i}步:{ICON_STEPS.get(s, f'步骤{s}')}")
return "\n".join(lines)
def get_icon_scheme() -> int:
"""获取当前图标方案编号"""
return _ICON_SCHEME
def set_icon_scheme(scheme: int) -> None:
"""设置当前图标方案(实时自动保存,持久化)"""
global _ICON_SCHEME
if scheme in ICON_SCHEMES:
_ICON_SCHEME = scheme
save_icon_scheme()
def get_scheme_order(scheme: int) -> list:
"""获取方案的步骤执行顺序(①~⑤)"""
info = ICON_SCHEMES.get(scheme)
if info and info.get("order"):
return list(info["order"])
return [1, 2, 3, 4, 5]
def get_scheme_desc(scheme: int) -> str:
"""获取图标方案说明文本(名称 + 先后顺序逻辑 + 固定兜底)"""
info = ICON_SCHEMES.get(scheme)
if not info:
return "(未知方案)"
order = info.get("order", [1, 2, 3, 4, 5])
return f"{info['name']}\n\n【采用先后顺序逻辑】\n{_step_text(order)}\n\n{ICON_TAIL}"
def set_scheme2_order(order: list) -> None:
"""更新方案2 的可调整顺序(实时自动保存,持久化)"""
ICON_SCHEMES[2]["order"] = [s for s in order if s in ICON_STEPS]
try:
s = QSettings("ProgramLauncher", "Settings")
s.setValue("scheme2_order", json.dumps(ICON_SCHEMES[2]["order"]))
except Exception:
pass
def add_custom_scheme(name: str, order: list) -> int:
"""把自定义后的方案另存为新方案(持久化),返回新方案 id"""
sid = _CUSTOM_SCHEME_START
while sid in ICON_SCHEMES:
sid += 1
ICON_SCHEMES[sid] = {
"name": name,
"order": [s for s in order if s in ICON_STEPS],
"editable": True,
"custom": True,
}
_save_custom_schemes()
return sid
def update_custom_scheme(scheme: int, name: str = None, order: list = None) -> None:
"""更新已另存的自定义方案(顺序或名称,实时自动保存)"""
info = ICON_SCHEMES.get(scheme)
if not info or not info.get("custom"):
return
if name:
info["name"] = name
if order:
info["order"] = [s for s in order if s in ICON_STEPS]
_save_custom_schemes()
def _save_custom_schemes() -> None:
"""持久化所有用户另存的自定义方案"""
try:
customs = [
{"name": info["name"], "order": info.get("order", [1, 2, 3, 4, 5])}
for sid, info in ICON_SCHEMES.items() if sid >= _CUSTOM_SCHEME_START
]
s = QSettings("ProgramLauncher", "Settings")
s.setValue("custom_schemes", json.dumps(customs, ensure_ascii=False))
except Exception:
pass
def load_icon_scheme() -> None:
"""启动时加载图标方案设置(QSettings 持久化)"""
global _ICON_SCHEME
try:
s = QSettings("ProgramLauncher", "Settings")
# 方案2 的自定义顺序
try:
o = json.loads(s.value("scheme2_order", "[1,2,3,4,5]"))
if isinstance(o, list) and o:
ICON_SCHEMES[2]["order"] = [x for x in o if x in ICON_STEPS]
except Exception:
pass
# 用户另存的自定义方案
try:
customs = json.loads(s.value("custom_schemes", "[]"))
if isinstance(customs, list):
for i, c in enumerate(customs):
sid = _CUSTOM_SCHEME_START + i
ICON_SCHEMES[sid] = {
"name": str(c.get("name", f"自定义方案{i + 1}")),
"order": [x for x in c.get("order", [1, 2, 3, 4, 5]) if x in ICON_STEPS],
"editable": True,
"custom": True,
}
except Exception:
pass
# 当前选中的方案
val = int(s.value("icon_scheme", 1))
_ICON_SCHEME = val if val in ICON_SCHEMES else 1
except Exception:
_ICON_SCHEME = 1
def save_icon_scheme() -> None:
"""保存当前选中的图标方案(QSettings 持久化)"""
try:
s = QSettings("ProgramLauncher", "Settings")
s.setValue("icon_scheme", _ICON_SCHEME)
except Exception:
pass
class DynamicIconGenerator:
@staticmethod
def generate_icon(text: str = "APP", size: Tuple[int, int] = (64, 64)) -> str:
"""动态生成ICO图标文件"""
# 创建图像
img = Image.new('RGB', size, (70, 130, 180)) # 蓝色背景
draw = ImageDraw.Draw(img)
try:
# 尝试使用系统字体
font = ImageFont.truetype("arial.ttf", 20)
except:
# 回退到默认字体
font = ImageFont.load_default()
# 计算文本位置 (兼容新旧Pillow版本)
try:
# 新版本Pillow使用textbbox
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
except AttributeError:
# 旧版本Pillow使用textsize
text_width, text_height = draw.textsize(text, font)
position = ((size[0] - text_width) // 2, (size[1] - text_height) // 2)
# 绘制文本
draw.text(position, text, fill=(255, 255, 255), font=font)
# 保存为ICO文件
ico_path = "icon.ico"
img.save(ico_path, sizes=[size])
return ico_path
@staticmethod
def extract_exe_icon(exe_path: str, output_path: str = None) -> Optional[str]:
"""从exe文件中提取图标(改进版)"""
try:
import win32ui
if not os.path.exists(exe_path):
return None
if not output_path:
# 使用绝对路径
output_dir = os.path.abspath(os.path.join(BASE_DIR, "temp_icons"))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
output_path = os.path.abspath(os.path.join(output_dir, f"{os.path.basename(exe_path)}_{hash(exe_path)}.ico"))
# 方法1: 使用win32gui.ExtractIconEx
try:
large, small = win32gui.ExtractIconEx(exe_path, 0)
if large:
icon = large[0]
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), icon)
hbmp.SaveBitmapFile(hdc, output_path)
win32gui.DestroyIcon(icon)
return output_path
except Exception:
pass
# 方法2: 使用Pillow提取
try:
from PIL import Image
ico_x = win32gui.ExtractIcon(exe_path, 0)
if ico_x:
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), ico_x)
bmpinfo = hbmp.GetInfo()
bmpstr = hbmp.GetBitmapBits(True)
img = Image.frombuffer(
'RGB',
(bmpinfo['bmWidth'], bmpinfo['bmHeight']),
bmpstr, 'raw', 'BGRX', 0, 1
)
img.save(output_path)
win32gui.DestroyIcon(ico_x)
return output_path
except Exception:
pass
# 方法3: 使用Shell API
try:
import ctypes
from ctypes import wintypes
SHGFI_ICON = 0x000000100
SHGFI_LARGEICON = 0x000000000
SHGFI_SMALLICON = 0x000000001
class SHFILEINFO(ctypes.Structure):
_fields_ = [
('hIcon', ctypes.c_void_p),
('iIcon', ctypes.c_int),
('dwAttributes', ctypes.c_uint),
('szDisplayName', ctypes.c_wchar * 260),
('szTypeName', ctypes.c_wchar * 80)
]
shell32 = ctypes.windll.shell32
info = SHFILEINFO()
res = shell32.SHGetFileInfoW(
exe_path, 0, ctypes.byref(info),
ctypes.sizeof(info),
SHGFI_ICON | SHGFI_LARGEICON
)
if info.hIcon:
import win32ui
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), info.hIcon)
hbmp.SaveBitmapFile(hdc, output_path)
win32gui.DestroyIcon(info.hIcon)
return output_path
except Exception:
pass
# 方法4: 使用系统默认图标
try:
from win32com.shell import shell, shellcon
from win32com.shell.shell import SHGetFileInfo
flags = shellcon.SHGFI_ICON | shellcon.SHGFI_LARGEICON
info = SHGetFileInfo(exe_path, 0, flags)
if info[0]:
icon = info[0]
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), icon)
hbmp.SaveBitmapFile(hdc, output_path)
win32gui.DestroyIcon(icon)
return output_path
except Exception:
pass
return None
except Exception:
return None
@staticmethod
def find_icon_in_directory(directory: str) -> Optional[str]:
"""在指定目录下查找图标文件"""
if not os.path.isdir(directory):
return None
# 查找常见的图标文件
icon_patterns = ["icon.*", "*.ico"]
for pattern in icon_patterns:
files = glob.glob(os.path.join(directory, pattern))
if files:
# 优先返回.ico文件
ico_files = [f for f in files if f.lower().endswith('.ico')]
if ico_files:
return ico_files[0]
return files[0] # 返回找到的第一个匹配文件
return None
@staticmethod
def find_icon_in_library(path: str) -> Optional[str]:
"""方案2(精确匹配):从现成图标库 resource/icons 中按类型查找图标
图标库位于程序当前目录的子目录 resource\icons(只读,不写入):
- classic\ : 按扩展名命名的图标库(如 exe.svg / pdf.svg / folder.svg / default.svg / blank.svg)
- extra\ : 文件夹系列图标(folder-*.svg,更丰富)
仅做**精确匹配**:目录 → extra\folder.svg(回退 classic\folder.svg);
文件 → classic\<扩展名>.svg;无精确匹配一律返回 None。
(注意:不要在这里回退 default/blank,否则链路中后续的"Windows 系统图标"步骤永远不会执行;
默认图标兜底由 find_default_icon_in_library 负责)
"""
base = os.path.join(BASE_DIR, "resource", "icons")
classic_dir = os.path.join(base, "classic")
extra_dir = os.path.join(base, "extra")
# 目录:优先 extra 文件夹图标,回退 classic
if os.path.isdir(path):
for d in (extra_dir, classic_dir):
candidate = os.path.join(d, "folder.svg")
if os.path.exists(candidate):
return candidate
return None
# 文件:按扩展名精确匹配 classic 图标库
ext = os.path.splitext(path)[1].lower().lstrip('.')
if ext:
candidate = os.path.join(classic_dir, f"{ext}.svg")
if os.path.exists(candidate):
return candidate
return None
@staticmethod
def find_default_icon_in_library(path: str) -> Optional[str]:
"""兜底:无图标时的默认图标(直接用图标库默认图标,不做"最相似"归并)
- 目录 → extra\folder.svg(回退 classic\folder.svg)
- 文件 → ① 先精确匹配 classic\<扩展名>.svg(有专属图标用专属)
② 无专属图标 → classic\blank.svg(再退 default.svg)
仍无 → 返回 None
"""
base = os.path.join(BASE_DIR, "resource", "icons")
classic_dir = os.path.join(base, "classic")
extra_dir = os.path.join(base, "extra")
# 目录:文件夹图标
if os.path.isdir(path):
for d in (extra_dir, classic_dir):
candidate = os.path.join(d, "folder.svg")
if os.path.exists(candidate):
return candidate
# 文件:优先专属图标,其次默认图标
ext = os.path.splitext(path)[1].lower().lstrip('.')
if ext:
candidate = os.path.join(classic_dir, f"{ext}.svg")
if os.path.exists(candidate):
return candidate
# 默认图标:blank.svg 优先,default.svg 备用
for name in ("blank.svg", "default.svg"):
candidate = os.path.join(classic_dir, name)
if os.path.exists(candidate):
return candidate
return None
@staticmethod
def find_icon_auto(path: str, name: str = "") -> Optional[str]:
"""按用户选择的图标方案自动获取图标(设置中可选)
方案1:固定顺序;方案2 / 用户另存的自定义方案:自定义①~⑤顺序(⑥⑦固定兜底)。
"""
order = get_scheme_order(get_icon_scheme())
return DynamicIconGenerator._find_icon_by_order(path, name, order)
@staticmethod
def _find_icon_by_order(path: str, name: str, order: list) -> Optional[str]:
"""按指定步骤顺序执行①~⑤;⑥兜底 / ⑦保险固定在后"""
for step in order:
icon = DynamicIconGenerator._exec_icon_step(path, step)
if icon:
return icon
# ⑥ 兜底:默认图标(固定,blank.svg/default.svg)
icon = DynamicIconGenerator.find_default_icon_in_library(path)
if icon:
return icon
# ⑦ 最终保险:按类型生成默认图标(固定)
return DynamicIconGenerator.generate_default_icon(path, name)
@staticmethod
def _exec_icon_step(path: str, step: int) -> Optional[str]:
"""执行单个图标步骤(①~⑤),失败返回 None"""
try:
if step == 1:
# ① 仅对含内嵌图标资源的文件(exe/dll 等);.bat/.cmd 是文本无图标资源,交由 ③ 图标库 bat.svg/cmd.svg
ext = os.path.splitext(path)[1].lower() if not os.path.isdir(path) else ""
if ext in ('.exe', '.dll', '.com', '.msi', '.ocx', '.sys', '.scr', '.pif', '.app'):
return DynamicIconGenerator.extract_exe_icon(path)
elif step == 2:
if not os.path.isdir(path):
d = os.path.dirname(path)
if d:
return DynamicIconGenerator.find_icon_in_directory(d)
elif step == 3:
return DynamicIconGenerator.find_icon_in_library(path)
elif step == 4:
return DynamicIconGenerator.extract_system_icon_os(path)
elif step == 5:
return DynamicIconGenerator.extract_icon_resource(path)
except Exception:
pass
return None
@staticmethod
def _resolve_lnk_path(lnk_path: str) -> str:
"""解析.lnk快捷方式的目标路径(兼容Nuitka打包环境)"""
# 先尝试 pythoncom 方式(非 frozen 环境)
if not getattr(sys, 'frozen', False):
try:
import pythoncom
from win32com.shell import shell
pythoncom.CoInitialize()
shortcut = pythoncom.CoCreateInstance(
shell.CLSID_ShellLink, None,
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(lnk_path)
target = shortcut.GetPath(shell.SLGP_UNCPRIORITY)[0]
if target and os.path.exists(target):
return target
except Exception:
pass
# ctypes 回退方案(Nuitka frozen 环境兼容)
try:
import ctypes
from ctypes import wintypes
# COM GUIDs
CLSID_ShellLink = bytes([
0x01,0x14,0x02,0x00,0x00,0x00,0x00,0x00,
0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46])
IID_IShellLinkW = bytes([
0xF9,0x14,0x02,0x00,0x00,0x00,0x00,0x00,
0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46])
IID_IPersistFile = bytes([
0x0b,0x01,0x00,0x00,0x00,0x00,0x00,0x00,
0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46])
ole32 = ctypes.windll.ole32
# IShellLinkW vtable 函数指针
# IUnknown: QueryInterface(0), AddRef(1), Release(2)
# IShellLinkW: GetPath(3), GetIDList(4), SetIDList(5), ...
pSl = ctypes.c_void_p()
hr = ole32.CoCreateInstance(
ctypes.create_string_buffer(CLSID_ShellLink, 16), None, 1, # CLSCTX_INPROC_SERVER
ctypes.create_string_buffer(IID_IShellLinkW, 16),
ctypes.byref(pSl))
if hr != 0 or not pSl:
return lnk_path
# QueryInterface for IPersistFile (通过 IShellLinkW 的 vtable)
vtable = ctypes.cast(pSl, ctypes.POINTER(ctypes.c_void_p)).contents
vtable = ctypes.cast(vtable, ctypes.POINTER(ctypes.c_void_p))
# IUnknown::QueryInterface
pPf = ctypes.c_void_p()
QueryInterface = ctypes.cast(vtable[0], ctypes.CFUNCTYPE(
ctypes.c_long, ctypes.c_void_p,
ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)))
hr = QueryInterface(pSl, ctypes.create_string_buffer(IID_IPersistFile, 16), ctypes.byref(pPf))
if hr != 0 or not pPf:
vtable2 = ctypes.cast(pSl, ctypes.POINTER(ctypes.c_void_p)).contents
vtable2 = ctypes.cast(vtable2, ctypes.POINTER(ctypes.c_void_p))
Release = ctypes.cast(vtable2[2], ctypes.CFUNCTYPE(ctypes.c_ulong, ctypes.c_void_p))
Release(pSl)
return lnk_path
# IPersistFile::Load
pf_vtable = ctypes.cast(pPf, ctypes.POINTER(ctypes.c_void_p)).contents
pf_vtable = ctypes.cast(pf_vtable, ctypes.POINTER(ctypes.c_void_p))
Load = ctypes.cast(pf_vtable[5], ctypes.CFUNCTYPE(
ctypes.c_long, ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_uint))
hr = Load(pPf, lnk_path, 0)
if hr != 0:
return lnk_path
# IShellLinkW::GetPath
GetPath = ctypes.cast(vtable[3], ctypes.CFUNCTYPE(
ctypes.c_long, ctypes.c_void_p, ctypes.c_wchar_p,
ctypes.c_int, ctypes.c_void_p, ctypes.c_uint))
buf = ctypes.create_unicode_buffer(260)
hr = GetPath(pSl, buf, 260, None, 0) # SLGP_UNCPRIORITY = 0
# Release interfaces
pf_vtable2 = ctypes.cast(pPf, ctypes.POINTER(ctypes.c_void_p)).contents
pf_vtable2 = ctypes.cast(pf_vtable2, ctypes.POINTER(ctypes.c_void_p))
Release2 = ctypes.cast(pf_vtable2[2], ctypes.CFUNCTYPE(ctypes.c_ulong, ctypes.c_void_p))
Release2(pPf)
vtable3 = ctypes.cast(pSl, ctypes.POINTER(ctypes.c_void_p)).contents
vtable3 = ctypes.cast(vtable3, ctypes.POINTER(ctypes.c_void_p))
Release3 = ctypes.cast(vtable3[2], ctypes.CFUNCTYPE(ctypes.c_ulong, ctypes.c_void_p))
Release3(pSl)
if hr == 0 and buf.value and os.path.exists(buf.value):
return buf.value
except Exception:
pass
return lnk_path # 解析失败返回原路径
@staticmethod
def extract_icon_resource(path: str, output_path: str = None) -> Optional[str]:
"""步骤⑤:从 Windows 图标资源文件中提取(win32gui.ExtractIconEx,适用于 .exe/.dll 等含内嵌图标的文件)"""
if not os.path.exists(path):
return None
if output_path is None:
output_dir = os.path.abspath(os.path.join(BASE_DIR, "temp_icons"))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
output_path = os.path.abspath(os.path.join(
output_dir, f"sysicon_{hash(path)}_{os.path.basename(path)}.ico"))
if os.path.exists(output_path):
return output_path
actual_path = path
if path.lower().endswith('.lnk'):
try:
actual_path = DynamicIconGenerator._resolve_lnk_path(path)
except Exception:
pass
try:
import win32ui
large, small = win32gui.ExtractIconEx(actual_path, 0)
if large:
icon = large[0]
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), icon)
hbmp.SaveBitmapFile(hdc, output_path)
for ic in large:
win32gui.DestroyIcon(ic)
for ic in small:
win32gui.DestroyIcon(ic)
return output_path
except Exception:
pass
return None
@staticmethod
def extract_system_icon_os(path: str, output_path: str = None) -> Optional[str]:
"""步骤④:调用 Windows 系统图标(SHGetFileInfo,适用于任意文件类型)"""
if not os.path.exists(path):
return None
if output_path is None:
output_dir = os.path.abspath(os.path.join(BASE_DIR, "temp_icons"))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
output_path = os.path.abspath(os.path.join(
output_dir, f"sysicon_{hash(path)}_{os.path.basename(path)}.ico"))
if os.path.exists(output_path):
return output_path
actual_path = path
if path.lower().endswith('.lnk'):
try:
actual_path = DynamicIconGenerator._resolve_lnk_path(path)
except Exception:
pass
# win32com.shell.SHGetFileInfo
try:
import pythoncom
from win32com.shell import shell, shellcon
flags = shellcon.SHGFI_ICON | shellcon.SHGFI_LARGEICON
ret, info = shell.SHGetFileInfo(actual_path, 0, flags)
if ret and len(info) > 0 and info[0]:
import win32ui
icon = info[0]
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), icon)
hbmp.SaveBitmapFile(hdc, output_path)
win32gui.DestroyIcon(icon)
return output_path
except Exception:
pass
# ctypes SHGetFileInfoW(兼容性最好)
try:
import ctypes
from ctypes import wintypes
SHGFI_ICON = 0x100
SHGFI_LARGEICON = 0
class SHFILEINFO(ctypes.Structure):
_fields_ = [
('hIcon', wintypes.HICON),
('iIcon', ctypes.c_int),
('dwAttributes', ctypes.c_uint),
('szDisplayName', ctypes.c_wchar * 260),
('szTypeName', ctypes.c_wchar * 80)
]
shell32 = ctypes.windll.shell32
info = SHFILEINFO()
result = shell32.SHGetFileInfoW(
actual_path, 0, ctypes.byref(info),
ctypes.sizeof(info), SHGFI_ICON | SHGFI_LARGEICON
)
if result and info.hIcon:
import win32ui
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), info.hIcon)
hbmp.SaveBitmapFile(hdc, output_path)
win32gui.DestroyIcon(info.hIcon)
return output_path
except Exception:
pass
return None
@staticmethod
def extract_system_icon(path: str, output_path: str = None) -> Optional[str]:
"""合并获取(兼容):⑤资源提取 → ④系统图标(原 extract_system_icon 行为)"""
r = DynamicIconGenerator.extract_icon_resource(path, output_path)
if r:
return r
return DynamicIconGenerator.extract_system_icon_os(path, output_path)
@staticmethod
def generate_default_icon(path: str, name: str = "", output_dir: str = None) -> str:
"""根据路径类型自动生成默认图标
- 目录: 黄色文件夹图标
- *.exe/*.com: 蓝色程序图标
- 其他文件: 根据扩展名生成不同颜色图标
"""
if output_dir is None:
output_dir = os.path.join(BASE_DIR, "icons", "auto")
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# 生成唯一文件名
icon_name = f"auto_{hash(path)}_{os.path.basename(path)}.ico"
output_path = os.path.join(output_dir, icon_name)
# 如果已经生成过,直接返回
if os.path.exists(output_path):
return output_path
size = (64, 64)
ext = os.path.splitext(path)[1].lower() if not os.path.isdir(path) else ""
# 根据文件类型选择颜色和标签
if os.path.isdir(path):
bg_color = (255, 200, 50) # 金黄色 - 文件夹
label = "DIR"
icon_symbol = "📁"
elif ext in ('.exe', '.com', '.bat', '.cmd', '.msi'):
bg_color = (52, 120, 220) # 蓝色 - 可执行程序
label = ext.upper().lstrip('.')[:3]
icon_symbol = "▶"
elif ext in ('.txt', '.md', '.doc', '.docx', '.pdf', '.xls', '.xlsx', '.ppt', '.pptx', '.csv', '.log'):
bg_color = (80, 80, 80) # 深灰色 - 文档
label = "DOC"
icon_symbol = "📄"
elif ext in ('.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.ico', '.webp', '.tiff'):
bg_color = (200, 80, 160) # 紫红色 - 图片
label = "IMG"
icon_symbol = "🖼"
elif ext in ('.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma', '.m4a'):
bg_color = (80, 180, 80) # 绿色 - 音频
label = "AUD"