-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram_Launcher.py
More file actions
1958 lines (1628 loc) · 76.2 KB
/
Program_Launcher.py
File metadata and controls
1958 lines (1628 loc) · 76.2 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
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 PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QLineEdit, QTabWidget, QMessageBox,
QFileDialog, QGroupBox, QScrollArea, QSizePolicy, QSpacerItem,
QMenu, QTableWidget, QTableWidgetItem, QDialog, QLayout,
QCheckBox, QAction, QComboBox, QInputDialog, QToolButton)
from PyQt5.QtCore import Qt, QSize, QSettings, QTimer, QRect, QPoint, pyqtSignal
from PyQt5.QtGui import QIcon, QColor, QTextCursor, QTextCharFormat, QFont, QPixmap, QKeySequence
from PIL import Image, ImageDraw, ImageFont
import sqlite3
import win32api
import win32con
import win32process
import win32gui
from typing import Optional, List, Tuple, Dict, Any
class ProjectInfo:
"""项目信息元数据(集中管理所有项目相关信息)"""
VERSION = "1.19.0"
BUILD_DATE = "2025-05-24"
AUTHOR = "杜玛"
LICENSE = "MIT"
COPYRIGHT = "© 永久 杜玛"
URL = "https://github.com/duma520"
MAINTAINER_EMAIL = "不提供"
NAME = "程序启动器"
DESCRIPTION = "程序启动器,基于PyQt5的桌面应用程序"
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()
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
print(f"[DEBUG] 开始提取图标: {exe_path}")
if not os.path.exists(exe_path):
print(f"[DEBUG] 错误: 文件不存在: {exe_path}")
return None
if not output_path:
# 使用绝对路径
output_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp_icons"))
if not os.path.exists(output_dir):
print(f"[DEBUG] 创建临时图标目录: {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"))
print(f"[DEBUG] 设置输出路径: {output_path}")
# 方法1: 使用win32gui.ExtractIconEx
try:
print("[DEBUG] 尝试方法1: win32gui.ExtractIconEx")
large, small = win32gui.ExtractIconEx(exe_path, 0)
print(f"[DEBUG] 方法1结果 - 大图标数: {len(large) if large else 0}, 小图标数: {len(small) if small else 0}")
if large:
print("[DEBUG] 方法1找到大图标,正在保存...")
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)
print(f"[DEBUG] 方法1成功保存图标到: {output_path}")
return output_path
except Exception as e:
print(f"[DEBUG] 方法1提取图标失败: {str(e)}")
import traceback
traceback.print_exc()
# 方法2: 使用Pillow提取
try:
print("[DEBUG] 尝试方法2: Pillow+win32gui.ExtractIcon")
from PIL import Image
ico_x = win32gui.ExtractIcon(exe_path, 0)
print(f"[DEBUG] 方法2结果 - 图标句柄: {bool(ico_x)}")
if ico_x:
print("[DEBUG] 方法2找到图标,正在保存...")
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)
print(f"[DEBUG] 方法2成功保存图标到: {output_path}")
return output_path
except Exception as e:
print(f"[DEBUG] 方法2提取图标失败: {str(e)}")
import traceback
traceback.print_exc()
# 方法3: 使用Shell API
try:
print("[DEBUG] 尝试方法3: Shell API (ctypes)")
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()
print(f"[DEBUG] 调用SHGetFileInfoW...")
res = shell32.SHGetFileInfoW(
exe_path, 0, ctypes.byref(info),
ctypes.sizeof(info),
SHGFI_ICON | SHGFI_LARGEICON
)
print(f"[DEBUG] SHGetFileInfoW返回: {res}, 图标句柄: {info.hIcon}")
if info.hIcon:
print("[DEBUG] 方法3找到图标,正在保存...")
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)
print(f"[DEBUG] 方法3成功保存图标到: {output_path}")
return output_path
except Exception as e:
print(f"[DEBUG] 方法3提取图标失败: {str(e)}")
import traceback
traceback.print_exc()
# 方法4: 使用系统默认图标
try:
print("[DEBUG] 尝试方法4: win32com.shell")
from win32com.shell import shell, shellcon
from win32com.shell.shell import SHGetFileInfo
flags = shellcon.SHGFI_ICON | shellcon.SHGFI_LARGEICON
print(f"[DEBUG] 调用SHGetFileInfo...")
info = SHGetFileInfo(exe_path, 0, flags)
print(f"[DEBUG] SHGetFileInfo返回: {info}")
if info[0]:
print("[DEBUG] 方法4找到图标,正在保存...")
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)
print(f"[DEBUG] 方法4成功保存图标到: {output_path}")
return output_path
except Exception as e:
print(f"[DEBUG] 方法4提取图标失败: {str(e)}")
import traceback
traceback.print_exc()
print(f"[DEBUG] 所有方法都无法提取 {exe_path} 的图标")
return None
except Exception as e:
print(f"[DEBUG] 提取图标过程中发生异常: {str(e)}")
import traceback
traceback.print_exc()
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
class DatabaseManager:
def __init__(self):
self.db_path = "launcher.db"
self._init_db() # 初始化数据库
self._init_backup_dir() # 初始化备份目录
self._init_icon_dir() # 初始化图标目录
self.conn = None # 添加连接对象引用
self.last_check_time = 0 # 添加最后检查时间
def check_connection(self):
"""检查并确保数据库连接正常"""
current_time = time.time()
if current_time - self.last_check_time < 60: # 每分钟最多检查一次
return True
try:
# 尝试执行一个简单的查询来测试连接
temp_conn = sqlite3.connect(self.db_path)
cursor = temp_conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
temp_conn.close()
self.last_check_time = current_time
return True
except sqlite3.Error as e:
print(f"数据库连接检查失败: {str(e)}")
return False
def _init_backup_dir(self):
"""初始化备份目录"""
if not os.path.exists("backups"):
os.makedirs("backups")
def backup_database(self):
"""备份数据库到backups目录(带频率限制检查)"""
try:
# 检查上次备份时间,避免过于频繁备份(调整为4.5分钟)
current_time = time.time()
if hasattr(self, 'last_backup_time') and current_time - self.last_backup_time < 270:
# 如果距离上次备份不到4.5分钟(270秒),跳过本次备份
return False
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = os.path.join("backups", f"launcher_backup_{timestamp}.db")
shutil.copy2(self.db_path, backup_path)
# 更新最后备份时间
self.last_backup_time = current_time
# 保留最多24个备份文件(因为现在是每5分钟备份,24个=2小时)
backups = sorted(glob.glob(os.path.join("backups", "launcher_backup_*.db")))
if len(backups) > 24:
for old_backup in backups[:-24]:
try:
os.remove(old_backup)
except Exception as e:
print(f"删除旧备份失败: {str(e)}")
return True
except Exception as e:
print(f"备份失败: {str(e)}")
return False
def _init_db(self):
"""初始化数据库"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# 创建分组表
cursor.execute("""
CREATE TABLE IF NOT EXISTS groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
position INTEGER DEFAULT 0,
is_favorite INTEGER DEFAULT 0
)
""")
# 创建按钮表
cursor.execute("""
CREATE TABLE IF NOT EXISTS buttons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
group_id INTEGER NOT NULL,
name TEXT NOT NULL,
path TEXT NOT NULL,
arguments TEXT DEFAULT '',
working_dir TEXT DEFAULT '',
run_as_admin INTEGER DEFAULT 0,
icon_path TEXT DEFAULT '',
position INTEGER DEFAULT 0,
is_favorite INTEGER DEFAULT 0,
FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE
)
""")
# 检查并添加可能缺失的列(兼容性处理)
columns_to_add = [
('groups', 'is_favorite', 'INTEGER DEFAULT 0'),
('buttons', 'arguments', 'TEXT DEFAULT \'\''),
('buttons', 'working_dir', 'TEXT DEFAULT \'\''),
('buttons', 'run_as_admin', 'INTEGER DEFAULT 0'),
('buttons', 'icon_path', 'TEXT DEFAULT \'\''),
('buttons', 'is_favorite', 'INTEGER DEFAULT 0')
]
for table, column, col_type in columns_to_add:
try:
cursor.execute(f"ALTER TABLE {table} ADD COLUMN {column} {col_type}")
except sqlite3.OperationalError:
pass # 列已存在
conn.commit()
def add_group(self, name: str, is_favorite: bool = False) -> int:
"""添加新分组"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# 获取当前最大position值
cursor.execute("SELECT MAX(position) FROM groups")
max_pos = cursor.fetchone()[0] or 0
cursor.execute(
"INSERT INTO groups (name, position, is_favorite) VALUES (?, ?, ?)",
(name, max_pos + 1, 1 if is_favorite else 0)
)
conn.commit()
return cursor.lastrowid
def get_groups(self) -> List[Tuple[int, str, int, int]]:
"""获取所有分组(带连接检查和重试)"""
max_retries = 3
for attempt in range(max_retries):
try:
if not self.check_connection():
if attempt == max_retries - 1:
return [] # 最后一次尝试失败返回空列表
time.sleep(0.5) # 短暂等待后重试
continue
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT id, name, position, is_favorite FROM groups ORDER BY is_favorite DESC, position")
return cursor.fetchall()
except sqlite3.Error as e:
print(f"获取分组失败(尝试 {attempt + 1}/{max_retries}): {str(e)}")
if attempt == max_retries - 1:
return [] # 最后一次尝试失败返回空列表
time.sleep(0.5) # 短暂等待后重试
def update_group_name(self, group_id: int, new_name: str):
"""更新分组名称"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE groups SET name = ? WHERE id = ?",
(new_name, group_id)
)
conn.commit()
def toggle_group_favorite(self, group_id: int, is_favorite: bool):
"""切换分组收藏状态"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE groups SET is_favorite = ? WHERE id = ?",
(1 if is_favorite else 0, group_id)
)
conn.commit()
def delete_group(self, group_id: int):
"""删除分组及其所有按钮"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM groups WHERE id = ?", (group_id,))
conn.commit()
def add_button(self, group_id: int, name: str, path: str,
arguments: str = '', working_dir: str = '',
run_as_admin: bool = False, icon_path: str = '',
is_favorite: bool = False) -> int:
"""添加新按钮"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# 获取当前最大position值
cursor.execute("SELECT MAX(position) FROM buttons WHERE group_id = ?", (group_id,))
max_pos = cursor.fetchone()[0] or 0
cursor.execute(
"""INSERT INTO buttons
(group_id, name, path, arguments, working_dir,
run_as_admin, icon_path, position, is_favorite)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(group_id, name, path, arguments, working_dir,
1 if run_as_admin else 0, icon_path, max_pos + 1,
1 if is_favorite else 0)
)
conn.commit()
return cursor.lastrowid
def get_buttons(self, group_id: int) -> List[Tuple[int, str, str, str, str, int, str, int, int]]:
"""获取指定分组的所有按钮"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""SELECT id, name, path, arguments, working_dir,
run_as_admin, icon_path, position, is_favorite
FROM buttons WHERE group_id = ?
ORDER BY is_favorite DESC, position""",
(group_id,)
)
return cursor.fetchall()
def get_all_buttons(self) -> List[Tuple[int, int, str, str, str, str, int, str, int, int]]:
"""获取所有按钮"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""SELECT id, group_id, name, path, arguments,
working_dir, run_as_admin, icon_path, position, is_favorite
FROM buttons
ORDER BY is_favorite DESC, position"""
)
return cursor.fetchall()
def update_button(self, button_id: int, name: str, path: str,
arguments: str = '', working_dir: str = '',
run_as_admin: bool = False, icon_path: str = ''):
"""更新按钮信息"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""UPDATE buttons SET
name = ?, path = ?, arguments = ?,
working_dir = ?, run_as_admin = ?, icon_path = ?
WHERE id = ?""",
(name, path, arguments, working_dir,
1 if run_as_admin else 0, icon_path, button_id)
)
conn.commit()
def toggle_button_favorite(self, button_id: int, is_favorite: bool):
"""切换按钮收藏状态"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"UPDATE buttons SET is_favorite = ? WHERE id = ?",
(1 if is_favorite else 0, button_id)
)
conn.commit()
def delete_button(self, button_id: int):
"""删除按钮"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM buttons WHERE id = ?", (button_id,))
conn.commit()
def move_buttons_to_group(self, button_ids: List[int], target_group_id: int):
"""将按钮移动到另一个分组"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# 获取目标组中当前最大的position值
cursor.execute("SELECT MAX(position) FROM buttons WHERE group_id = ?", (target_group_id,))
max_pos = cursor.fetchone()[0] or 0
# 更新每个按钮的group_id和position
for i, button_id in enumerate(button_ids, 1):
cursor.execute(
"UPDATE buttons SET group_id = ?, position = ? WHERE id = ?",
(target_group_id, max_pos + i, button_id)
)
conn.commit()
def reorder_groups(self, group_order: List[int]):
"""重新排序分组"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
for position, group_id in enumerate(group_order, 1):
cursor.execute(
"UPDATE groups SET position = ? WHERE id = ?",
(position, group_id)
)
conn.commit()
def reorder_buttons(self, button_order: List[int]):
"""重新排序按钮"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
for position, button_id in enumerate(button_order, 1):
cursor.execute(
"UPDATE buttons SET position = ? WHERE id = ?",
(position, button_id)
)
conn.commit()
def _init_icon_dir(self):
"""初始化图标目录"""
self.icon_dir = os.path.join(os.path.dirname(self.db_path), "icons")
if not os.path.exists(self.icon_dir):
os.makedirs(self.icon_dir)
def get_icon_path(self, original_path: str) -> str:
"""获取图标保存路径"""
if not original_path:
return ""
self._init_icon_dir()
filename = os.path.basename(original_path)
# 生成唯一文件名避免冲突
unique_name = f"{hash(original_path)}_{filename}"
return os.path.join(self.icon_dir, unique_name)
def copy_icon_to_storage(self, icon_path: str) -> str:
"""将图标复制到持久化存储"""
if not icon_path or not os.path.exists(icon_path):
return ""
target_path = self.get_icon_path(icon_path)
try:
shutil.copy2(icon_path, target_path)
return target_path
except Exception as e:
print(f"无法复制图标文件: {e}")
return icon_path # 返回原始路径作为回退
class HighlightTextEdit(QLineEdit):
"""支持高亮显示搜索关键字的文本框"""
def __init__(self, parent=None):
super().__init__(parent)
self.highlight_format = QTextCharFormat()
self.highlight_format.setBackground(QColor(255, 255, 0)) # 黄色背景高亮
def highlight_text(self, text: str):
"""高亮显示匹配的文本"""
if not text:
return
# 获取当前文本
current_text = self.text()
if not current_text:
return
# 创建高亮格式
palette = self.palette()
palette.setColor(QPalette.Highlight, QColor(255, 255, 0))
palette.setColor(QPalette.HighlightedText, Qt.black)
self.setPalette(palette)
# 查找所有匹配位置
start_pos = 0
while True:
pos = current_text.lower().find(text.lower(), start_pos)
if pos == -1:
break
self.setSelection(pos, len(text))
start_pos = pos + len(text)
class ButtonEditor(QDialog):
def __init__(self, button_id: Optional[int] = None, group_id: Optional[int] = None,
name: str = "", path: str = "", arguments: str = "",
working_dir: str = "", run_as_admin: bool = False,
icon_path: str = "", is_favorite: bool = False, parent=None):
super().__init__(parent)
self.button_id = button_id
self.group_id = group_id
self.parent = parent
self.icon_path = icon_path
self.setWindowTitle("编辑按钮" if button_id else "添加按钮")
self.setWindowModality(Qt.ApplicationModal)
self.resize(500, 300)
layout = QVBoxLayout()
# 按钮名称
name_layout = QHBoxLayout()
name_layout.addWidget(QLabel("按钮名称:"))
self.name_edit = QLineEdit(name)
name_layout.addWidget(self.name_edit)
# 收藏复选框
self.favorite_check = QCheckBox("收藏")
self.favorite_check.setChecked(is_favorite)
name_layout.addWidget(self.favorite_check)
layout.addLayout(name_layout)
# 程序路径
path_layout = QHBoxLayout()
path_layout.addWidget(QLabel("程序路径:"))
self.path_edit = QLineEdit(path)
path_layout.addWidget(self.path_edit)
self.browse_btn = QPushButton("浏览...")
self.browse_btn.clicked.connect(self.browse_path)
path_layout.addWidget(self.browse_btn)
layout.addLayout(path_layout)
# 启动参数
args_layout = QHBoxLayout()
args_layout.addWidget(QLabel("启动参数:"))
self.args_edit = QLineEdit(arguments)
args_layout.addWidget(self.args_edit)
layout.addLayout(args_layout)
# 工作目录
dir_layout = QHBoxLayout()
dir_layout.addWidget(QLabel("工作目录:"))
self.dir_edit = QLineEdit(working_dir)
dir_layout.addWidget(self.dir_edit)
self.browse_dir_btn = QPushButton("浏览...")
self.browse_dir_btn.clicked.connect(self.browse_working_dir)
dir_layout.addWidget(self.browse_dir_btn)
layout.addLayout(dir_layout)
# 管理员权限和图标设置
options_layout = QHBoxLayout()
# 管理员权限
self.admin_check = QCheckBox("以管理员权限运行")
self.admin_check.setChecked(run_as_admin)
options_layout.addWidget(self.admin_check)
# 图标设置
icon_btn_layout = QHBoxLayout()
icon_btn_layout.addWidget(QLabel("图标:"))
self.icon_btn = QPushButton()
self.update_icon_btn()
self.icon_btn.clicked.connect(self.change_icon)
icon_btn_layout.addWidget(self.icon_btn)
self.clear_icon_btn = QPushButton("清除")
self.clear_icon_btn.clicked.connect(self.clear_icon)
icon_btn_layout.addWidget(self.clear_icon_btn)
options_layout.addLayout(icon_btn_layout)
layout.addLayout(options_layout)
# 按钮区域
btn_layout = QHBoxLayout()
self.save_btn = QPushButton("保存")
self.save_btn.clicked.connect(self.save_button)
btn_layout.addWidget(self.save_btn)
self.cancel_btn = QPushButton("取消")
self.cancel_btn.clicked.connect(self.close)
btn_layout.addWidget(self.cancel_btn)
layout.addLayout(btn_layout)
self.setLayout(layout)
def update_icon_btn(self):
"""更新图标按钮的显示"""
if self.icon_path and os.path.exists(self.icon_path):
self.icon_btn.setIcon(QIcon(self.icon_path))
self.icon_btn.setText("更改图标")
else:
self.icon_btn.setIcon(QIcon())
self.icon_btn.setText("设置图标")
def browse_path(self):
"""浏览文件系统选择程序或目录"""
# 先检查剪贴板是否有文件或目录
clipboard = QApplication.clipboard()
if clipboard.mimeData().hasUrls():
urls = clipboard.mimeData().urls()
if urls and urls[0].isLocalFile():
path = urls[0].toLocalFile()
if os.path.exists(path): # 检查路径是否存在
reply = QMessageBox.question(
self, "使用剪贴板路径",
f"检测到剪贴板中有路径:\n{path}\n\n是否使用此路径?",
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
if reply == QMessageBox.Yes:
self.path_edit.setText(path)
# 如果没有选择图标,尝试获取图标
if not self.icon_path:
self.set_icon_from_path(path)
return
# 显示文件/目录选择对话框
dialog = QFileDialog(self)
dialog.setFileMode(QFileDialog.ExistingFile)
dialog.setOption(QFileDialog.DontUseNativeDialog, True)
# 添加"选择文件夹"按钮
dir_btn = QPushButton("选择文件夹")
dir_btn.clicked.connect(lambda: dialog.setFileMode(QFileDialog.Directory))
dialog.layout().addWidget(dir_btn)
# 添加"选择文件"按钮
file_btn = QPushButton("选择文件")
file_btn.clicked.connect(lambda: dialog.setFileMode(QFileDialog.ExistingFile))
dialog.layout().addWidget(file_btn)
if dialog.exec_():
paths = dialog.selectedFiles()
if paths:
path = paths[0]
self.path_edit.setText(path)
# 如果没有选择图标,尝试获取图标
if not self.icon_path:
self.set_icon_from_path(path)
def set_icon_from_path(self, path):
"""根据路径自动设置图标"""
if os.path.isdir(path): # 如果是目录
# 使用系统文件夹图标
from win32com.shell import shell, shellcon
try:
_, icon = shell.SHGetFileInfo(path, 0, shellcon.SHGFI_ICON | shellcon.SHGFI_LARGEICON)
icon_path = os.path.join(os.path.dirname(self.db_path), "folder_icon.ico")
icon.Save(icon_path)
self.icon_path = icon_path
self.update_icon_btn()
return
except:
pass
elif path.lower().endswith('.exe'): # 如果是EXE文件
icon_path = DynamicIconGenerator.extract_exe_icon(path)
if icon_path:
self.icon_path = icon_path
self.update_icon_btn()
return
# 在程序所在目录查找图标文件
program_dir = os.path.dirname(path) if os.path.isfile(path) else path
icon_path = DynamicIconGenerator.find_icon_in_directory(program_dir)
if icon_path:
self.icon_path = icon_path
self.update_icon_btn()
def browse_working_dir(self):
"""浏览工作目录"""
dir_path = QFileDialog.getExistingDirectory(self, "选择工作目录")
if dir_path:
self.dir_edit.setText(dir_path)
def change_icon(self):
"""更改图标"""
icon_path, _ = QFileDialog.getOpenFileName(
self, "选择图标文件", "", "图标文件 (*.ico *.png *.jpg);;所有文件 (*.*)")
if icon_path:
self.icon_path = icon_path
self.update_icon_btn()
def clear_icon(self):
"""清除图标"""
self.icon_path = ""
self.update_icon_btn()
def save_button(self):
"""保存按钮信息"""
name = self.name_edit.text().strip()
path = self.path_edit.text().strip()
args = self.args_edit.text().strip()
working_dir = self.dir_edit.text().strip()
run_as_admin = self.admin_check.isChecked()
is_favorite = self.favorite_check.isChecked()
if not name:
QMessageBox.warning(self, "警告", "按钮名称不能为空!")
return
if not path:
QMessageBox.warning(self, "警告", "程序路径不能为空!")
return
# 预处理路径
path = path.replace('/', '\\').strip('"\'')
if working_dir:
working_dir = working_dir.replace('/', '\\').strip('"\'')
# 验证路径
if not os.path.exists(path):
if not (path.startswith('\\\\') or ':/' in path or ':\\' in path):
QMessageBox.warning(self, "警告", "指定的路径不存在!")
return
db = DatabaseManager()
# 处理图标路径
icon_path = self.icon_path
if icon_path: # 如果有图标,确保它被保存到持久化存储
icon_path = db.copy_icon_to_storage(icon_path)
# 如果没有选择图标且路径是EXE文件,尝试自动提取图标
if not icon_path and path.lower().endswith('.exe'):
extracted_icon = DynamicIconGenerator.extract_exe_icon(path)
if extracted_icon:
icon_path = db.copy_icon_to_storage(extracted_icon)
try:
os.remove(extracted_icon) # 删除临时文件
except:
pass
if self.button_id is not None: