-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJAV-code-Purifier_beta.py
2892 lines (2379 loc) · 123 KB
/
JAV-code-Purifier_beta.py
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 re
import json
import pyperclip
import configparser
import webbrowser
from tkinter import filedialog, simpledialog, messagebox, ttk, font as tkfont
from PIL import Image, ImageTk
import subprocess
import shutil
import winreg
import logging
from datetime import datetime
import threading
import concurrent.futures
import atexit
import asyncio
import io
import base64
import queue
import warnings
import cv2
import time
from functools import lru_cache
from concurrent.futures import ThreadPoolExecutor
import tkinter as tk
import random
import psutil
import win32security
import win32file
import win32api
import win32con
import pywintypes
from datetime import datetime
import importlib
# 常量定义
CONFIG_FILE = 'config.ini'
HISTORY_FILE = 'history.json'
STATE_FILE = 'state.json'
CUSTOM_RULES_FILE = 'custom_rules.json'
VERSION = "v1.6.0"
# 配置日志和警告
logging.basicConfig(filename='renamer.log', level=logging.DEBUG)
warnings.filterwarnings("ignore", category=UserWarning)
sys.setrecursionlimit(5000) # 增加递归限制,默认是100
class LoadingAnimation(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
self.title("Loading")
self.geometry("400x320")
self.configure(bg='black')
self.attributes('-alpha', 0.9)
self.overrideredirect(True)
self.attributes('-topmost', True)
self.canvas = tk.Canvas(self, width=400, height=320, bg='black', highlightthickness=0)
self.canvas.pack(expand=True)
self.particles = []
self.create_particles()
self.text = "JAV code Purifier"
self.current_text = ""
self.text_id = self.canvas.create_text(200, 140, text="", fill="#00FFFF", font=("Arial", 24, "bold"))
# 添加版本号
self.version_text = self.canvas.create_text(200, 180, text=VERSION, fill="#80FFFF", font=("Arial", 16))
# 添加当前任务显示
self.task_text = self.canvas.create_text(200, 220, text="", fill="#80FFFF", font=("Arial", 12))
# 添加 powered by 文本
self.credit_text = self.canvas.create_text(200, 300, text="powered by naomi032",
fill="#80FFFF", font=("Arial", 10))
self.animate()
self.animate_text()
def set_task(self, task):
self.canvas.itemconfig(self.task_text, text=f"当前任务: {task}")
def create_particles(self):
for _ in range(50):
x = random.randint(0, 400)
y = random.randint(0, 300)
size = random.randint(1, 3)
particle = self.canvas.create_oval(x, y, x + size, y + size, fill='#00FFFF', outline='')
speed = random.uniform(0.5, 2)
self.particles.append((particle, x, y, speed))
def animate(self):
for i, (particle, x, y, speed) in enumerate(self.particles):
y = (y + speed) % 300
self.canvas.moveto(particle, x, y)
self.particles[i] = (particle, x, y, speed)
if random.random() < 0.1:
opacity = random.randint(50, 255)
color = '#{:02x}{:02x}{:02x}'.format(0, opacity, opacity)
self.canvas.itemconfig(particle, fill=color)
self.after(30, self.animate)
def animate_text(self):
if len(self.current_text) < len(self.text):
self.current_text += self.text[len(self.current_text)]
self.canvas.itemconfig(self.text_id, text=self.current_text)
glow_effect = self.canvas.create_text(200, 140, text=self.current_text, fill="#80FFFF",
font=("Arial", 24, "bold"))
self.after(50, lambda: self.canvas.delete(glow_effect))
self.after(100, self.animate_text)
else:
self.pulse_text()
def pulse_text(self):
current_color = self.canvas.itemcget(self.text_id, "fill")
if current_color == "#00FFFF":
new_color = "#80FFFF"
else:
new_color = "#00FFFF"
self.canvas.itemconfig(self.text_id, fill=new_color)
self.after(500, self.pulse_text)
class DarkElvenTheme:
def __init__(self, root):
self.root = root
self.style = ttk.Style()
# 定义暗黑精灵风格的颜色方案
self.colors = {
'bg_dark': (26, 26, 46), # 深邃的夜空蓝
'bg_medium': (22, 33, 62), # 稍微亮一点的深蓝
'bg_light': (15, 52, 96), # 深蓝色调的高光
'accent': (233, 69, 96), # 神秘的红色作为强调色
'text': (212, 236, 221), # 柔和的浅绿色文字
'button': (74, 14, 78), # 深紫色按钮
'button_hover': (123, 51, 125), # 亮紫色按钮悬停效果
'entry': (31, 31, 31), # 几乎纯黑的输入框背景
'treeview_bg': (22, 33, 62), # 树状视图背景
'treeview_fg': (212, 236, 221), # 树状视图文字颜色
'treeview_selected': (83, 52, 131) # 树状视图选中项颜色
}
self.apply_theme()
def apply_theme(self):
self.root.configure(bg=self.rgb_to_hex(self.colors['bg_dark']))
# 配置通用样式
self.style.configure('TFrame', background=self.rgb_to_hex(self.colors['bg_dark']))
self.style.configure('TLabel', background=self.rgb_to_hex(self.colors['bg_dark']),
foreground=self.rgb_to_hex(self.colors['text']))
self.style.configure('TEntry', fieldbackground=self.rgb_to_hex(self.colors['entry']),
foreground=self.rgb_to_hex(self.colors['text']))
# 配置树状视图
self.style.configure('Treeview',
background=self.rgb_to_hex(self.colors['treeview_bg']),
foreground=self.rgb_to_hex(self.colors['treeview_fg']),
fieldbackground=self.rgb_to_hex(self.colors['treeview_bg']))
self.style.map('Treeview', background=[('selected', self.rgb_to_hex(self.colors['treeview_selected']))])
# 配置其他控件
self.style.configure('TCheckbutton', background=self.rgb_to_hex(self.colors['bg_dark']),
foreground=self.rgb_to_hex(self.colors['text']))
self.style.configure('TRadiobutton', background=self.rgb_to_hex(self.colors['bg_dark']),
foreground=self.rgb_to_hex(self.colors['text']))
@staticmethod
def rgb_to_hex(rgb):
return '#{:02x}{:02x}{:02x}'.format(rgb[0], rgb[1], rgb[2])
class ElvenButton(tk.Canvas):
def __init__(self, master, text, command=None, width=160, height=40, corner_radius=20,
bg_color="#4a0e4e", hover_color="#7b337d", text_color="#e0d0ff", **kwargs):
super().__init__(master, width=width, height=height, highlightthickness=0,
bg=ttk.Style().lookup('TFrame', 'background'), **kwargs)
self.command = command
self.width = width
self.height = height
self.corner_radius = corner_radius
self.bg_color = bg_color
self.hover_color = hover_color
self.text_color = text_color
# 创建主要形状
self.shape = self.create_rounded_rect(0, 0, width, height, corner_radius, fill=self.bg_color, outline="")
# 创建微妙的光泽效果
self.highlight = self.create_rounded_rect(1, 1, width - 1, height - 1, corner_radius - 1,
fill="", outline="#ffffff", width=1, stipple="gray50")
self.font = tkfont.Font(family="Palatino Linotype", size=12, weight="bold")
self.text_item = self.create_text(width // 2, height // 2, text=text, fill=self.text_color, font=self.font)
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<ButtonPress-1>", self._on_press)
self.bind("<ButtonRelease-1>", self._on_release)
def set_state(self, state):
if state == 'normal':
self.config(state=tk.NORMAL)
elif state == 'disabled':
self.config(state=tk.DISABLED)
def create_rounded_rect(self, x1, y1, x2, y2, radius, **kwargs):
points = [
x1 + radius, y1,
x2 - radius, y1,
x2, y1,
x2, y1 + radius,
x2, y2 - radius,
x2, y2,
x2 - radius, y2,
x1 + radius, y2,
x1, y2,
x1, y2 - radius,
x1, y1 + radius,
x1, y1
]
return self.create_polygon(points, **kwargs, smooth=True)
def _on_enter(self, event):
self.itemconfig(self.shape, fill=self.hover_color)
self.itemconfig(self.highlight, stipple="gray75")
def _on_leave(self, event):
self.itemconfig(self.shape, fill=self.bg_color)
self.itemconfig(self.highlight, stipple="gray50")
def _on_press(self, event):
self.itemconfig(self.text_item, fill="#ffd700") # 金色
self.itemconfig(self.highlight, stipple="gray25")
def _on_release(self, event):
self.itemconfig(self.text_item, fill=self.text_color)
self.itemconfig(self.highlight, stipple="gray50")
if self.command:
self.command()
def update_text(self, new_text):
self.itemconfig(self.text_item, text=new_text)
def config(self, **kwargs):
if 'text' in kwargs:
self.update_text(kwargs['text'])
def create_icon(png_path, icon_sizes=[(16, 16), (32, 32), (48, 48), (64, 64)]):
with Image.open(png_path) as img:
icon_images = []
for size in icon_sizes:
resized_img = img.copy()
resized_img.thumbnail(size, Image.Resampling.LANCZOS)
icon_images.append(resized_img)
with io.BytesIO() as icon_bytes:
icon_images[0].save(icon_bytes, format='ICO', sizes=icon_sizes)
return icon_bytes.getvalue()
def set_icon_from_png(window, png_path):
icon_data = create_icon(png_path)
icon_data_base64 = base64.b64encode(icon_data)
window.tk.call('wm', 'iconphoto', window._w, tk.PhotoImage(data=icon_data_base64))
def load_custom_rules():
if os.path.exists(CUSTOM_RULES_FILE):
with open(CUSTOM_RULES_FILE, 'r') as f:
return json.load(f)
return []
def save_custom_rules(rules):
with open(CUSTOM_RULES_FILE, 'w') as f:
json.dump(rules, f)
def load_last_path():
config = configparser.ConfigParser()
if os.path.exists(CONFIG_FILE):
config.read(CONFIG_FILE)
return config.get('Settings', 'last_path', fallback=None)
return None
def save_last_path(path):
config = configparser.ConfigParser()
config['Settings'] = {'last_path': path}
with open(CONFIG_FILE, 'w') as configfile:
config.write(configfile)
def load_state_from_file():
if os.path.exists(STATE_FILE):
with open(STATE_FILE, 'r') as file:
return json.load(file)
return {}
def save_state_to_file(state):
with open(STATE_FILE, 'w') as file:
json.dump(state, file, indent=4)
class OptimizedFileRenamerUI:
def __init__(self, master):
self.master = master
self.master.withdraw()
self.loading_animation = self.show_loading_animation()
self.loading_animation.set_task("初始化程序...")
self.master.after(100, self.delayed_initialization)
self.rename_history = {}
self.rename_history = self.load_history()
self.create_menu()
self.preview_cancel_event = threading.Event()
if not os.path.exists('rename_rules.py'):
with open('rename_rules.py', 'w') as f:
f.write('''
import re
def process_filename(base_name, self):
# 在这里添加你的重命名规则
return base_name
''')
messagebox.showinfo("提示", "已创建默认的 'rename_rules.py' 文件。您可以编辑此文件来自定义重命名规则。")
def delayed_initialization(self):
try:
logging.debug("开始延迟初始化")
self.loading_animation.set_task("创建用户界面...")
self.setup_main_ui()
self.loading_animation.set_task("加载状态...")
self.load_state()
self.loading_animation.set_task("完成初始化...")
self.master.after(3000, self.finish_initialization)
except Exception as e:
logging.error(f"初始化过程中出错: {e}")
messagebox.showerror("初始化错误", f"程序初始化过程中发生错误:{e}")
self.master.quit()
def show_loading_animation(self):
loading_animation = LoadingAnimation(self.master)
loading_animation.update_idletasks()
width = loading_animation.winfo_width()
height = loading_animation.winfo_height()
x = (loading_animation.winfo_screenwidth() // 2) - (width // 2)
y = (loading_animation.winfo_screenheight() // 2) - (height // 2)
loading_animation.geometry('{}x{}+{}+{}'.format(width, height, x, y))
return loading_animation
def finish_initialization(self):
logging.debug("完成初始化")
self.hide_loading_animation()
self.master.deiconify()
self.master.after(100, self.prompt_restore_last_folder)
def hide_loading_animation(self):
if hasattr(self, 'loading_animation'):
self.loading_animation.destroy()
self.master.deiconify()
def setup_main_ui(self):
logging.debug("设置主UI")
self.master.title('JAV-code-Purifier')
self.master.geometry('1300x1000')
self.master.configure(bg='#1e1e1e') # 设置初始背景色
self.style = ttk.Style(self.master)
self.style.theme_use('clam')
self.create_menu()
self.rename_mode = tk.StringVar(value="files")
self.rename_mode.trace('w', self.on_rename_mode_change)
self.all_items = []
self.current_theme = 'light'
self.executor = ThreadPoolExecutor(max_workers=5)
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.preview_task = None
self.preview_cancel_event = threading.Event()
self.video_playing = False
self.style = ttk.Style(self.master)
self.style.theme_use('clam')
self.executor = concurrent.futures.ThreadPoolExecutor()
atexit.register(self.executor.shutdown)
self.is_shutting_down = False
self.selected_folder = None
self.file_paths = {}
self.is_dark_mode = False
self.rename_history = {}
self.file_types_to_delete = {}
self.context_menu = None # Initialize context_menu as None
self.create_context_menu() # Create the context menu
if not self.context_menu:
print("Context menu failed to initialize") # 用于调试
self.replace_00_var = tk.BooleanVar(value=True)
self.remove_prefix_var = tk.BooleanVar(value=True)
self.remove_hhb_var = tk.BooleanVar(value=True)
self.retain_digits_var = tk.BooleanVar(value=True)
self.retain_format_var = tk.BooleanVar(value=True)
self.custom_prefix = tk.StringVar()
self.custom_suffix = tk.StringVar()
self.custom_rules = load_custom_rules()
self.preview_canvas = None
self.preview_label = None
self.setup_ui()
self.apply_dark_theme() # 在设置 UI 后应用暗黑主题
self.load_state()
self.style.configure("Custom.TCheckbutton", background="#f0f0f0", foreground="#000000")
self.style.map("Custom.TCheckbutton",
background=[('active', '#e5e5e5')],
foreground=[('disabled', '#a3a3a3')])
self.last_resize_time = 0
self.master.bind("<Configure>", self.on_window_configure)
def prompt_restore_last_folder(self):
logging.debug("提示恢复上次文件夹")
last_path = load_last_path()
if last_path and os.path.exists(last_path):
prompt_window = tk.Toplevel(self.master)
prompt_window.title("恢复上次文件夹")
prompt_window.geometry("400x150")
prompt_window.transient(self.master)
prompt_window.grab_set()
prompt_window.focus_set()
message = f"是否要恢复上次选择的文件夹?\n{last_path}"
tk.Label(prompt_window, text=message, wraplength=380).pack(pady=10)
def on_yes():
self.selected_folder = last_path
self.folder_label.config(text=f'选择文件夹: {self.selected_folder}')
self.preview_files()
self.start_button.config(state="normal")
prompt_window.destroy()
def on_no():
prompt_window.destroy()
self.select_new_folder()
tk.Button(prompt_window, text="是", command=on_yes).pack(side=tk.LEFT, expand=True, pady=10)
tk.Button(prompt_window, text="否", command=on_no).pack(side=tk.RIGHT, expand=True, pady=10)
prompt_window.update_idletasks()
width = prompt_window.winfo_width()
height = prompt_window.winfo_height()
x = (prompt_window.winfo_screenwidth() // 2) - (width // 2)
y = (prompt_window.winfo_screenheight() // 2) - (height // 2)
prompt_window.geometry('{}x{}+{}+{}'.format(width, height, x, y))
else:
self.select_new_folder()
def select_new_folder(self):
logging.debug("选择新文件夹")
self.selected_folder = filedialog.askdirectory()
if self.selected_folder:
self.folder_label.config(text=f"选择文件夹: {self.selected_folder}")
self.preview_files()
self.start_button.config(state="normal")
save_last_path(self.selected_folder)
else:
logging.debug("没有选择文件夹")
self.folder_label.config(text="未选择文件夹")
self.start_button.config(state="disabled")
def on_window_configure(self, event):
if event.widget == self.master:
current_time = time.time()
if current_time - self.last_resize_time > 0.2: # 减少延迟以提高响应性
self.last_resize_time = current_time
self.master.after(100, self.update_layout)
def update_layout(self):
# 只更新布局,不更新颜色
# 这里可以添加任何需要在窗口大小变化时更新的布局代码
pass
def apply_dark_theme(self):
dark_theme = {
'bg': '#1e1e1e', # 深灰色背景
'fg': '#e0e0e0', # 浅灰色文字
'button_bg': '#3a3a3a', # 按钮背景色
'button_fg': '#ffffff', # 按钮文字颜色
'active_bg': '#4a4a4a', # 稍亮的灰色用于激活状态
'disabled_fg': '#6c6c6c', # 中灰色用于禁用状态
'changed_fg': '#ffd700', # 金黄色用于更改的项目
'accent': '#4a90e2', # 蓝色作为强调色
'error': '#e74c3c', # 红色用于错误
'success': '#2ecc71', # 绿色用于成功
'border': '#404040', # 银色边框(更暗一些)
'menu_bg': '#2d2d2d', # 菜单栏背景色
}
# 更新 ttk 样式
self.style.configure('TFrame', background=dark_theme['bg'], bordercolor=dark_theme['border'])
self.style.configure('TLabel', background=dark_theme['bg'], foreground=dark_theme['fg'])
self.style.configure('TButton', background=dark_theme['button_bg'], foreground=dark_theme['button_fg'])
self.style.configure('Treeview', background=dark_theme['bg'], foreground=dark_theme['fg'],
fieldbackground=dark_theme['bg'], bordercolor=dark_theme['border'])
self.style.configure('Treeview.Heading', background=dark_theme['active_bg'], foreground=dark_theme['fg'])
self.style.configure('Custom.TCheckbutton', background=dark_theme['bg'], foreground=dark_theme['fg'])
self.style.configure('TProgressbar', background=dark_theme['accent'])
self.style.configure('TEntry', fieldbackground=dark_theme['bg'], foreground=dark_theme['fg'],
bordercolor=dark_theme['border'])
self.style.configure('TCombobox', fieldbackground=dark_theme['bg'], foreground=dark_theme['fg'],
selectbackground=dark_theme['active_bg'])
# 更新映射
self.style.map('TButton',
background=[('active', dark_theme['active_bg'])],
foreground=[('active', dark_theme['fg'])])
self.style.map('Custom.TCheckbutton',
background=[('active', dark_theme['active_bg'])],
foreground=[('disabled', dark_theme['disabled_fg'])])
self.style.map('Treeview',
background=[('selected', dark_theme['accent'])],
foreground=[('selected', dark_theme['fg'])])
# 更新非 ttk 小部件
self.master.configure(bg=dark_theme['bg'])
if hasattr(self, 'preview_canvas'):
self.preview_canvas.configure(bg=dark_theme['bg'])
# 更新所有小部件的颜色
self.update_all_widgets(self.master, dark_theme)
# 设置 Treeview 的标签颜色
self.tree.tag_configure("changed", foreground=dark_theme['changed_fg'])
self.tree.tag_configure("error", foreground=dark_theme['error'])
self.tree.tag_configure("success", foreground=dark_theme['success'])
# 更新菜单颜色
self.update_menu_colors(dark_theme)
# 设置窗口背景色
self.master.configure(bg=dark_theme['bg'])
def update_all_widgets(self, parent, theme):
widgets_to_update = [parent]
while widgets_to_update:
widget = widgets_to_update.pop(0)
try:
if isinstance(widget, (tk.Frame, tk.LabelFrame)):
widget.configure(bg=theme['bg'], highlightbackground=theme['border'],
highlightcolor=theme['border'])
elif isinstance(widget, (tk.Label, tk.Button, tk.Entry, tk.Text, tk.Listbox, tk.Canvas)):
widget.configure(bg=theme['bg'], fg=theme['fg'])
if isinstance(widget, (tk.Entry, tk.Text)):
widget.configure(insertbackground=theme['fg']) # 设置光标颜色
elif isinstance(widget, ttk.Widget):
widget_name = widget.winfo_class()
self.style.configure(f'{widget_name}', background=theme['bg'], foreground=theme['fg'])
except tk.TclError:
pass
widgets_to_update.extend(widget.winfo_children())
def update_other_widgets(self):
# 更新状态栏
self.statusbar.configure(background=self.style.lookup('TFrame', 'background'),
foreground=self.style.lookup('TLabel', 'foreground'))
# 更新自定义规则框架
for widget in self.custom_rule_frame.winfo_children():
if isinstance(widget, ttk.Entry):
widget.configure(style='TEntry')
elif isinstance(widget, tk.Listbox):
widget.configure(background=self.style.lookup('TFrame', 'background'),
foreground=self.style.lookup('TLabel', 'foreground'),
selectbackground=self.style.lookup('Treeview', 'selectbackground'),
selectforeground=self.style.lookup('Treeview', 'selectforeground'))
# 更新预览框架
self.preview_canvas.configure(background=self.style.lookup('TFrame', 'background'))
self.preview_label.configure(style='TLabel')
# 在 apply_dark_theme 方法的末尾调用此函数
self.update_other_widgets()
def update_menu_colors(self, theme):
def recursive_color_set(menu):
menu.config(bg=theme['menu_bg'], fg=theme['fg'], activebackground=theme['active_bg'],
activeforeground=theme['fg'])
for item in menu.winfo_children():
if isinstance(item, tk.Menu):
recursive_color_set(item)
main_menu = self.master.nametowidget(self.master.cget("menu"))
recursive_color_set(main_menu)
def update_widget_colors(self, widget, theme):
try:
if isinstance(widget, (ttk.Button, ttk.Checkbutton, ttk.Radiobutton)):
pass # 这些 ttk 小部件的颜色由 style 控制
elif isinstance(widget, ttk.Entry):
widget.configure(style='TEntry')
elif isinstance(widget, tk.Text):
widget.config(bg=theme['bg'], fg=theme['fg'], insertbackground=theme['fg'])
elif isinstance(widget, tk.Listbox):
widget.config(bg=theme['bg'], fg=theme['fg'], selectbackground=theme['accent'],
selectforeground=theme['fg'])
else:
widget.config(bg=theme['bg'], fg=theme['fg'])
except tk.TclError:
pass # 忽略不支持颜色设置的小部件
for child in widget.winfo_children():
self.update_widget_colors(child, theme)
def apply_theme(self):
if not hasattr(self, 'last_theme') or self.last_theme != self.current_theme:
theme = self.themes[self.current_theme]
style_updates = {
'TFrame': {'background': theme['bg']},
'TLabel': {'background': theme['bg'], 'foreground': theme['fg']},
'TButton': {'background': theme['bg'], 'foreground': theme['fg']},
'Treeview': {'background': theme['bg'], 'foreground': theme['fg'], 'fieldbackground': theme['bg']},
'Treeview.Heading': {'background': theme['bg'], 'foreground': theme['fg']},
'Custom.TCheckbutton': {'background': theme['bg'], 'foreground': theme['fg']},
}
for style, options in style_updates.items():
self.style.configure(style, **options)
self.style.map('Custom.TCheckbutton',
background=[('active', theme['active_bg'])],
foreground=[('disabled', theme['disabled_fg'])])
self.master.config(bg=theme['bg'])
for widget in self.master.winfo_children():
self.update_widget_colors(widget, theme)
self.last_theme = self.current_theme
def update_widget_colors(self, widget, theme):
try:
widget.config(bg=theme['bg'], fg=theme['fg'])
except tk.TclError:
pass # 忽略不支持颜色设置的小部件
if isinstance(widget, tk.Text):
widget.config(bg=theme['bg'], fg=theme['fg'])
for child in widget.winfo_children():
self.update_widget_colors(child, theme)
def update_ui(self):
# 移除对 update_colors 的直接调用
pass
def setup_ui(self):
# 创建一个容器框架,将所有内容放在这个框架内
container = ttk.Frame(self.master)
container.pack(fill=tk.BOTH, expand=True)
# 创建一个Canvas
canvas = tk.Canvas(container)
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# 创建一个滚动条,并将其绑定到Canvas
scrollbar = ttk.Scrollbar(container, orient=tk.VERTICAL, command=canvas.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 将Canvas与滚动条连接
canvas.configure(yscrollcommand=scrollbar.set)
# 创建一个Frame在Canvas内
self.content_frame = ttk.Frame(canvas)
canvas_window = canvas.create_window((0, 0), window=self.content_frame, anchor="nw")
# 绑定配置事件以调整滚动区域大小
self.content_frame.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
# 使content_frame随Canvas调整大小
canvas.bind("<Configure>", lambda e: canvas.itemconfig(canvas_window, width=e.width))
# 在content_frame内添加所有的UI组件
left_frame = ttk.Frame(self.content_frame)
left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.create_folder_frame(left_frame)
self.create_treeview(left_frame)
self.create_options_frame(left_frame)
bottom_frame = ttk.Frame(left_frame)
bottom_frame.pack(fill=tk.BOTH, expand=True)
self.create_custom_rule_frame(bottom_frame)
self.create_preview_frame(bottom_frame)
self.create_buttons_frame(left_frame)
self.create_statusbar()
# 确保主窗口可以调整大小
self.master.resizable(True, True)
# 设置最小窗口大小
self.master.minsize(600, 400)
# 绑定窗口大小变化事件
self.master.bind("<Configure>", self.on_window_configure)
def add_rename_history(self, original_path, new_path):
if original_path != new_path:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if original_path not in self.rename_history:
self.rename_history[original_path] = []
self.rename_history[original_path].append((timestamp, new_path))
self.save_history() # 立即保存历史记录
return True
return False
def load_history(self):
if os.path.exists(HISTORY_FILE):
try:
with open(HISTORY_FILE, 'r', encoding='utf-8') as file:
return json.load(file)
except json.JSONDecodeError:
logging.error(f"Error decoding JSON from {HISTORY_FILE}")
except Exception as e:
logging.error(f"Unexpected error loading history from {HISTORY_FILE}: {e}")
return {}
def save_history(self):
try:
with open(HISTORY_FILE, 'w', encoding='utf-8') as file:
json.dump(self.rename_history, file, ensure_ascii=False, indent=4)
except Exception as e:
logging.error(f"Error saving history to {HISTORY_FILE}: {e}")
def safe_rename(self, src, dst, max_attempts=3, delay=1):
for attempt in range(max_attempts):
try:
if not os.path.exists(src):
raise FileNotFoundError(f"源文件不存在: {src}")
# 确保目标文件夹存在
dst_dir = os.path.dirname(dst)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
os.rename(src, dst)
return True
except PermissionError as e:
if attempt == max_attempts - 1:
using_processes = self.find_processes_using_file(src)
error_message = f"文件 '{os.path.basename(src)}' 被以下进程占用:\n"
for proc in using_processes:
error_message += f"- {proc.name()} (PID: {proc.pid})\n"
error_message += "\n是否重试重命名?"
if messagebox.askyesno("文件被占用", error_message):
return self.safe_rename(src, dst, max_attempts, delay * 2)
else:
return False
time.sleep(delay)
except FileNotFoundError as e:
messagebox.showerror("错误", str(e))
return False
except Exception as e:
messagebox.showerror("错误", f"重命名失败: {str(e)}")
return False
return False
def load_rename_history(self):
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'r') as f:
self.rename_history = json.load(f)
def save_rename_history(self):
with open(HISTORY_FILE, 'w') as f:
json.dump(self.rename_history, f)
def copy_name(self, name_type):
selected_items = self.tree.selection()
if not selected_items:
messagebox.showwarning("警告", "请选择一个文件或文件夹")
return
item = selected_items[0]
values = self.tree.item(item, 'values')
if len(values) < 8:
messagebox.showerror("错误", f"意外的数据结构: {values}")
return
original_name, preview_name, final_name, item_type, size, relative_path, status, tag = values[:8]
cdx_info = values[8] if len(values) > 8 else ''
if name_type == 'original':
name = values[0] # 原始名称
else:
name = values[2] # 新名称
pyperclip.copy(name)
messagebox.showinfo("复制成功", f"已复制{'原始' if name_type == 'original' else '新'}名称到剪贴板")
def show_rename_logic(self):
selected_items = self.tree.selection()
if not selected_items:
messagebox.showwarning("警告", "请选择一个文件或文件夹")
return
item = selected_items[0]
values = self.tree.item(item, 'values')
if len(values) < 3:
messagebox.showerror("错误", f"意外的数据结构: {values}")
return
original_name, _, final_name, *_ = values
logic_explanation = self.explain_rename_logic(original_name, final_name)
logic_window = tk.Toplevel(self.master)
logic_window.title("改名逻辑说明")
logic_window.geometry("600x400")
text_widget = tk.Text(logic_window, wrap=tk.WORD)
text_widget.pack(expand=True, fill=tk.BOTH)
text_widget.insert(tk.END, logic_explanation)
text_widget.config(state=tk.DISABLED)
def explain_rename_logic(self, original_name, final_name):
explanation = f"原始名称: {original_name}\n新名称: {final_name}\n\n改名逻辑说明:\n\n"
if original_name == final_name:
explanation += "文件名没有发生变化,可能是因为以下原因:\n"
explanation += "1. 原名称已符合所有规则要求。\n"
explanation += "2. 没有启用任何会改变此文件名的规则。\n"
else:
explanation += "应用了以下规则:\n"
explanation += "1. 移除了特殊字符 (<>:\"/\\|?*)\n"
if self.remove_prefix_var.get():
explanation += "2. 删除了特定前缀 (如 'hhd800.com@' 或 'www.98T.la@')\n"
if self.replace_00_var.get():
explanation += "3. 将字母后面的 '00' 替换为 '-'\n"
if self.remove_hhb_var.get():
explanation += "4. 删除了 'hhb' 及其后续内容\n"
if self.retain_digits_var.get():
explanation += "5. 保留了横杠后的三位数字\n"
if self.retain_format_var.get():
explanation += "6. 保留了 xxx-yyy 格式(其中 xxx 为2-6个字母,yyy 为3位数字)\n"
explanation += "7. 应用了自定义规则(如果有)\n"
explanation += "8. 提取了产品代码并转换为'字母-数字'的格式\n"
if '_001_' in original_name or '_002_' in original_name or '_003_' in original_name:
explanation += "9. 根据文件序号添加了 cdX 后缀\n"
if original_name.endswith(os.path.splitext(final_name)[1]):
explanation += "10. 保留了原有的文件扩展名\n"
else:
explanation += "10. 移除了文件扩展名\n"
if self.custom_rules:
explanation += "应用了以下自定义规则:\n"
for rule in self.custom_rules:
if rule[0] == "PREFIX":
explanation += f"- 添加前缀: '{rule[1]}'\n"
elif rule[0] == "SUFFIX":
explanation += f"- 添加后缀: '{rule[1]}'\n"
else:
explanation += f"- 将 '{rule[0]}' 替换为 '{rule[1]}'\n"
return explanation
def open_file(self, file_path):
if os.path.exists(file_path):
try:
if sys.platform == "win32":
os.startfile(file_path)
elif sys.platform == "darwin": # macOS
subprocess.call(["open", file_path])
else: # linux variants
subprocess.call(["xdg-open", file_path])
except Exception as e:
messagebox.showerror("错误", f"无法打开文件: {e}")
else:
messagebox.showerror("错误", "文件不存在")
def open_file_safely(self, file_path):
if not os.path.exists(file_path):
messagebox.showerror("错误", f"文件不存在: {file_path}")
return
try:
if sys.platform == "win32":
os.startfile(file_path)
elif sys.platform == "darwin": # macOS
subprocess.run(["open", file_path], check=True)
else: # linux variants
subprocess.run(["xdg-open", file_path], check=True)
except Exception as e:
messagebox.showerror("错误", f"无法打开文件: {str(e)}")
def open_file_location_safely(self, folder_path):
if not os.path.exists(folder_path):
messagebox.showerror("错误", f"文件夹不存在: {folder_path}")
return
try:
if sys.platform == "win32":
os.startfile(folder_path)
elif sys.platform == "darwin": # macOS
subprocess.run(["open", folder_path], check=True)
else: # linux variants
subprocess.run(["xdg-open", folder_path], check=True)
except Exception as e:
messagebox.showerror("错误", f"无法打开文件位置: {str(e)}")
def open_selected_file(self):
selected_items = self.tree.selection()
if not selected_items:
messagebox.showwarning("警告", "请选择一个文件或文件夹")
return
item = selected_items[0]
values = self.tree.item(item, 'values')
if len(values) < 6:
messagebox.showerror("错误", f"意外的数据结构: {values}")
return
original_name, *_, relative_path = values[:6]
file_path = os.path.join(self.selected_folder, relative_path, original_name)
self.open_file(file_path)
def open_file_location(self, folder_path=None):
if folder_path is None:
selected_items = self.tree.selection()
if not selected_items:
messagebox.showwarning("警告", "请选择一个文件或文件夹")
return
item = selected_items[0]
values = self.tree.item(item, 'values')
if len(values) < 6:
messagebox.showerror("错误", f"意外的数据结构: {values}")
return
original_name, *_, relative_path = values[:6]
file_path = os.path.join(self.selected_folder, relative_path, original_name)
folder_path = os.path.dirname(file_path)
# Use a thread to open the file location
threading.Thread(target=self._open_file_location_thread, args=(folder_path,)).start()
def _open_file_location_thread(self, folder_path):
try:
if sys.platform == 'win32':
os.startfile(folder_path)
elif sys.platform == 'darwin': # macOS
subprocess.Popen(['open', folder_path])
else: # linux variants
subprocess.Popen(['xdg-open', folder_path])
except Exception as e:
self.master.after(0, lambda: messagebox.showerror("错误", f"无法打开文件位置: {e}"))
def create_custom_rule_frame(self, parent):
self.custom_rule_frame = ttk.LabelFrame(parent, text="自定义规则")
self.custom_rule_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=10)
# 现有的替换规则部分
ttk.Label(self.custom_rule_frame, text="要替换的内容:").grid(row=0, column=0, padx=5, pady=5)
self.old_content_entry = ttk.Entry(self.custom_rule_frame)
self.old_content_entry.grid(row=0, column=1, padx=5, pady=5)
ttk.Label(self.custom_rule_frame, text="新内容:").grid(row=1, column=0, padx=5, pady=5)
self.new_content_entry = ttk.Entry(self.custom_rule_frame)
self.new_content_entry.grid(row=1, column=1, padx=5, pady=5)
ttk.Button(self.custom_rule_frame, text="创建替换规则", command=self.create_custom_rule).grid(row=2, column=0,
columnspan=2,
pady=5)
# 新增前缀和后缀部分
ttk.Label(self.custom_rule_frame, text="自定义前缀:").grid(row=3, column=0, padx=5, pady=5)
self.prefix_entry = ttk.Entry(self.custom_rule_frame, textvariable=self.custom_prefix)
self.prefix_entry.grid(row=3, column=1, padx=5, pady=5)
ttk.Label(self.custom_rule_frame, text="自定义后缀:").grid(row=4, column=0, padx=5, pady=5)
self.suffix_entry = ttk.Entry(self.custom_rule_frame, textvariable=self.custom_suffix)
self.suffix_entry.grid(row=4, column=1, padx=5, pady=5)
ttk.Button(self.custom_rule_frame, text="应用前缀/后缀", command=self.apply_prefix_suffix).grid(row=5, column=0,