-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1571 lines (1376 loc) · 64.8 KB
/
main.py
File metadata and controls
1571 lines (1376 loc) · 64.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import json
import subprocess
import threading
import webbrowser
import platform
import ctypes
import colorsys
import time
from datetime import datetime as dt
from typing import List, Dict
if getattr(sys, "frozen", False):
try:
if sys.stdout is None:
sys.stdout = open(os.devnull, "w", encoding="utf-8")
if sys.stderr is None:
sys.stderr = open(os.devnull, "w", encoding="utf-8")
except Exception:
pass
import tkinter as tk
import tkinter.font as tkfont
from tkinter import ttk, messagebox, filedialog
from models import ScanOptions, ScanResult
from scanner import list_disks, scan_path
from treemap import build_treemap, TreemapNode
try:
from PIL import ImageGrab
except ImportError:
ImageGrab = None
# ── Theme ────────────────────────────────────────────────────────
THEME_DARK = {
"bg_deep": "#0b1622",
"bg_surface": "#132238",
"bg_header": "#1a3050",
"accent": "#4ecca3",
"accent_dim": "#2d8a72",
"accent_light":"#6ee7b7",
"text": "#e4e8ec",
"text_dim": "#8899aa",
"border": "#1e3a54",
"progress_bg": "#1a2a3a",
"canvas_bg": "#0e1a28",
"error": "#e74c3c",
}
THEME_LIGHT = {
"bg_deep": "#e8f4fc",
"bg_surface": "#f0f8ff",
"bg_header": "#b8d4e8",
"accent": "#1e88c4",
"accent_dim": "#1565a0",
"accent_light":"#42a5f5",
"text": "#1a237e",
"text_dim": "#5c6bc0",
"border": "#90caf9",
"progress_bg": "#bbdefb",
"canvas_bg": "#e3f2fd",
"error": "#c62828",
"button_fg": "#ffffff",
"combobox_fg": "#1a237e",
"combobox_select_fg": "#ffffff",
"header_hover_fg": "#1a237e", # 顶栏控件悬停时文字色(浅色底上深色更易读)
"menu_active_fg": "#ffffff", # 菜单项悬停时文字色(深蓝底上白色更易读)
}
THEME = dict(THEME_DARK) # 当前主题,切换时整体替换
_BASE_HUES = [162, 200, 30, 275, 345, 120, 75, 240, 50, 185]
# 自定义大圆点单选:圆点直径(像素)
_RADIO_DOT_SIZE = 28
_RADIO_DOT_RING = 2
_RADIO_DOT_INNER_R = 8 # 选中时内部实心圆半径
_EXPAND_THRESHOLD = 25 * 1024 ** 3 # 25 GB
_MAX_DEPTH_FULL = 5
_MAX_DEPTH_FAST = 2
_HEADER_HEIGHTS = [24, 21, 18, 16, 14]
_FONT_SIZES = [8, 7, 6, 6, 5]
_MIN_BLOCK_W = [60, 50, 40, 30, 24]
_MIN_BLOCK_H = [45, 38, 30, 24, 18]
_VERSION = "Alpha v0.3.5"
def _hsl_to_hex(h: float, s: float, l: float) -> str:
r, g, b = colorsys.hls_to_rgb(h / 360.0, l, s)
return f"#{int(r * 255):02x}{int(g * 255):02x}{int(b * 255):02x}"
def _init_dpi_awareness() -> None:
if platform.system() != "Windows":
return
try:
ctypes.windll.user32.SetProcessDPIAware()
except Exception:
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def _hide_console() -> None:
if platform.system() != "Windows":
return
try:
hwnd = ctypes.windll.kernel32.GetConsoleWindow()
if hwnd:
ctypes.windll.user32.ShowWindow(hwnd, 0)
except Exception:
pass
def _is_admin() -> bool:
if platform.system() != "Windows":
return False
try:
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
def _set_dark_title_bar(window: tk.Tk) -> None:
"""Windows 10/11: 将窗口标题栏设为深色。"""
if platform.system() != "Windows":
return
try:
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
hwnd = ctypes.windll.user32.GetParent(window.winfo_id())
value = ctypes.c_int(1)
ctypes.windll.dwmapi.DwmSetWindowAttribute(
hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE,
ctypes.byref(value), ctypes.sizeof(value),
)
except Exception:
pass
# ── Application ──────────────────────────────────────────────────
class App(tk.Tk):
def __init__(self) -> None:
super().__init__()
try:
current_scaling = float(self.tk.call("tk", "scaling"))
if current_scaling < 1.5:
self.tk.call("tk", "scaling", 1.5)
except Exception:
pass
self.withdraw()
self._create_splash()
self._update_splash_progress(0.05, "正在初始化...")
self.after(50, self._init_main_ui)
# ── Splash ───────────────────────────────────────────────────
def _create_splash(self) -> None:
splash = tk.Toplevel(self)
splash.overrideredirect(True)
splash.attributes("-topmost", True)
splash.configure(bg=THEME["bg_deep"])
sw, sh = 480, 300
scr_w = splash.winfo_screenwidth()
scr_h = splash.winfo_screenheight()
splash.geometry(f"{sw}x{sh}+{(scr_w - sw) // 2}+{(scr_h - sh) // 2}")
c = tk.Canvas(splash, width=sw, height=sh,
bg=THEME["bg_deep"], highlightthickness=0)
c.pack(fill=tk.BOTH, expand=True)
c.create_rectangle(0, 0, sw, sh,
outline=THEME["accent"], width=2)
c.create_text(sw // 2, 55, text="Green",
fill=THEME["accent"],
font=("Segoe UI", 26, "bold"))
c.create_text(sw // 2, 110, text="磁盘空间可视化工具",
fill=THEME["text"], font=("Segoe UI", 11))
c.create_text(sw // 2, 145, text=_VERSION,
fill=THEME["text_dim"], font=("Segoe UI", 8))
bar_x, bar_w = 60, sw - 120
bar_y, bar_h = 190, 14
c.create_rectangle(bar_x, bar_y, bar_x + bar_w, bar_y + bar_h,
fill=THEME["progress_bg"], outline=THEME["border"])
self._splash_bar_fill = c.create_rectangle(
bar_x + 1, bar_y + 1, bar_x + 1, bar_y + bar_h - 1,
fill=THEME["accent"], outline="")
self._splash_bar_info = (bar_x, bar_y, bar_w, bar_h)
self._splash_pct_id = c.create_text(
sw // 2, bar_y + bar_h + 20, text="0%",
fill=THEME["text_dim"], font=("Segoe UI", 7))
self._splash_status_id = c.create_text(
sw // 2, bar_y + bar_h + 44, text="",
fill=THEME["text_dim"], font=("Segoe UI", 7))
self._splash = splash
self._splash_canvas = c
splash.update()
def _update_splash_progress(self, ratio: float, text: str) -> None:
try:
if not self._splash.winfo_exists():
return
except (tk.TclError, AttributeError):
return
ratio = max(0.0, min(ratio, 1.0))
bx, by, bw, bh = self._splash_bar_info
self._splash_canvas.coords(
self._splash_bar_fill,
bx + 1, by + 1, bx + 1 + int(bw * ratio), by + bh - 1)
self._splash_canvas.itemconfig(
self._splash_pct_id, text=f"{int(ratio * 100)}%")
self._splash_canvas.itemconfig(
self._splash_status_id, text=text)
self._splash.update()
# ── Theme setup ──────────────────────────────────────────────
def _setup_theme(self) -> None:
style = ttk.Style(self)
style.theme_use("clam")
style.configure(".", background=THEME["bg_surface"],
foreground=THEME["text"],
fieldbackground=THEME["bg_header"],
bordercolor=THEME["border"],
darkcolor=THEME["bg_deep"],
lightcolor=THEME["bg_header"],
troughcolor=THEME["progress_bg"],
selectbackground=THEME["accent"],
selectforeground=THEME["bg_deep"],
focuscolor=THEME["accent"])
style.configure("TButton",
background=THEME["accent"],
foreground=THEME.get("button_fg", THEME["bg_deep"]),
padding=(16, 5),
font=("Segoe UI", 9, "bold"))
style.map("TButton",
background=[("active", THEME["accent_dim"]),
("pressed", THEME["accent_dim"])])
style.configure("TLabel",
background=THEME["bg_surface"],
foreground=THEME["text"],
font=("Segoe UI", 9))
style.configure("Header.TLabel",
background=THEME["bg_header"],
foreground=THEME["text"],
font=("Segoe UI", 9))
style.configure("TFrame", background=THEME["bg_surface"])
style.configure("Header.TFrame", background=THEME["bg_header"])
style.configure("TCombobox",
fieldbackground=THEME["bg_header"],
background=THEME["bg_header"],
foreground=THEME.get("combobox_fg", "#ffffff"),
arrowcolor=THEME["accent"],
selectbackground=THEME["accent"],
selectforeground=THEME.get("combobox_select_fg", THEME["bg_deep"]))
_cf = THEME.get("combobox_fg", "#ffffff")
style.map("TCombobox",
foreground=[("readonly", _cf), ("active", _cf)],
fieldbackground=[("readonly", THEME["bg_header"]), ("active", THEME["bg_header"])])
style.configure("TRadiobutton",
background=THEME["bg_surface"],
foreground=THEME["text"],
indicatorcolor=THEME["bg_header"],
font=("Segoe UI", 9))
style.map("TRadiobutton",
indicatorcolor=[("selected", THEME["accent"])])
style.configure("Header.TRadiobutton",
background=THEME["bg_header"],
foreground=THEME["text"],
indicatorcolor=THEME["bg_deep"],
font=("Segoe UI", 9),
indicatorsize=16)
style.map("Header.TRadiobutton",
indicatorcolor=[("selected", THEME["accent"])])
style.configure("Horizontal.TProgressbar",
background=THEME["accent"],
troughcolor=THEME["progress_bg"],
bordercolor=THEME["border"],
lightcolor=THEME["accent"],
darkcolor=THEME["accent_dim"])
style.configure("Status.TLabel",
background=THEME["bg_header"],
foreground=THEME["text_dim"],
font=("Segoe UI", 8),
anchor="w")
def _set_theme(self, name: str) -> None:
"""切换主题:name 为 'dark' 或 'light'。"""
if name not in ("dark", "light"):
return
self._theme_name = name
THEME.clear()
THEME.update(THEME_LIGHT if name == "light" else THEME_DARK)
self._setup_theme()
self._apply_theme()
def _apply_theme(self) -> None:
"""根据当前 THEME 重配置主窗口与已保存的控件,并刷新路径栏、模式点、画布。"""
self.configure(bg=THEME["bg_deep"])
top = getattr(self, "_top_frame", None)
if top is not None:
top.configure(bg=THEME["bg_header"])
path_f = getattr(self, "_path_bar_frame", None)
path_i = getattr(self, "_path_bar_inner", None)
if path_f is not None:
path_f.configure(bg=THEME["bg_surface"])
if path_i is not None:
path_i.configure(bg=THEME["bg_surface"])
if self.canvas is not None:
self.canvas.configure(bg=THEME["canvas_bg"])
status_bar = getattr(self, "_status_bar", None)
status_label = getattr(self, "_status_label", None)
if status_bar is not None:
status_bar.configure(bg=THEME["bg_header"])
if status_label is not None:
status_label.configure(bg=THEME["bg_header"], fg=THEME["text_dim"])
mode_frame = getattr(self, "_mode_frame", None)
if mode_frame is not None:
mode_frame.configure(bg=THEME["bg_header"])
for child in mode_frame.winfo_children():
child.configure(bg=THEME["bg_header"])
for sub in child.winfo_children():
if isinstance(sub, tk.Canvas):
sub.configure(bg=THEME["bg_header"])
elif isinstance(sub, tk.Label):
sub.configure(bg=THEME["bg_header"], fg=THEME["text"])
_menu_bg = THEME["bg_header"]
_menu_fg = THEME["text"]
_menu_afg = THEME.get("menu_active_fg", THEME["text"])
_menu_abg = THEME["accent_dim"]
menubar = getattr(self, "_menubar", None)
if menubar is not None:
menubar.configure(bg=_menu_bg, fg=_menu_fg,
activebackground=_menu_abg, activeforeground=_menu_afg)
for m in (getattr(self, "_menu_export", None), getattr(self, "_menu_new", None),
getattr(self, "_menu_theme", None)):
if m is not None:
m.configure(bg=THEME["bg_surface"], fg=_menu_fg,
activebackground=_menu_abg, activeforeground=_menu_afg)
self._refresh_path_bar()
self._draw_scan_mode_dots()
if self._path_stack:
_, hierarchy = self._path_stack[-1]
self._draw_treemap_from_hierarchy(hierarchy, is_live=False)
def _add_big_dot_radio(self, parent: tk.Frame, text: str, value: str,
padx: tuple) -> None:
"""在 parent 中增加一个「大圆点」单选:Canvas 画圆 + Label,可读性更好。"""
s = _RADIO_DOT_SIZE + 4
f = tk.Frame(parent, bg=THEME["bg_header"], cursor="hand2")
cnv = tk.Canvas(f, width=s, height=s, bg=THEME["bg_header"],
highlightthickness=0)
cnv.pack(side=tk.LEFT)
lbl = tk.Label(f, text=text, bg=THEME["bg_header"], fg=THEME["text"],
font=("Segoe UI", 9), cursor="hand2")
lbl.pack(side=tk.LEFT, padx=(6, 0))
def on_click(_e=None) -> None:
self.mode_var.set(value)
def on_enter(_e: tk.Event) -> None:
lbl.config(fg=THEME.get("header_hover_fg", "#ffffff"))
def on_leave(_e: tk.Event) -> None:
lbl.config(fg=THEME["text"])
for w in (f, cnv, lbl):
w.bind("<Button-1>", on_click)
w.bind("<Enter>", on_enter)
w.bind("<Leave>", on_leave)
f.pack(side=tk.LEFT, padx=padx)
self._scan_mode_canvases.append((value, cnv))
def _draw_scan_mode_dots(self) -> None:
"""根据 mode_var 重绘两个大圆点:选中为实心,未选为空心环。"""
current = self.mode_var.get()
cx = (_RADIO_DOT_SIZE + 4) / 2.0
r_outer = _RADIO_DOT_SIZE / 2.0 - 2
for value, cnv in self._scan_mode_canvases:
cnv.delete("all")
cnv.create_oval(
cx - r_outer, cx - r_outer, cx + r_outer, cx + r_outer,
outline=THEME["accent"] if value == current else THEME["text_dim"],
width=_RADIO_DOT_RING,
fill=THEME["bg_header"])
if value == current:
cnv.create_oval(
cx - _RADIO_DOT_INNER_R, cx - _RADIO_DOT_INNER_R,
cx + _RADIO_DOT_INNER_R, cx + _RADIO_DOT_INNER_R,
outline="", fill=THEME["accent"])
def _set_window_icon(self) -> None:
"""设置窗口图标为程序目录下的 icon.png(打包后从 _MEIPASS 读取)。"""
if getattr(sys, "frozen", False):
base = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(sys.executable)))
else:
base = os.path.dirname(os.path.abspath(__file__))
icon_png = os.path.join(base, "icon.png")
icon_ico = os.path.join(base, "icon.ico")
try:
if platform.system() == "Windows" and os.path.isfile(icon_ico):
self.iconbitmap(icon_ico)
elif os.path.isfile(icon_png):
self._icon_photo = tk.PhotoImage(file=icon_png)
self.iconphoto(True, self._icon_photo)
except Exception:
pass
# ── Main UI init ─────────────────────────────────────────────
def _init_main_ui(self) -> None:
self._update_splash_progress(0.10, "正在创建窗口...")
self.title(f"Green 磁盘空间可视化工具 {_VERSION}")
self.configure(bg=THEME["bg_deep"])
scr_w = self.winfo_screenwidth()
scr_h = self.winfo_screenheight()
win_w = max(1200, int(scr_w * 0.72))
win_h = max(820, int(scr_h * 0.80))
win_x = (scr_w - win_w) // 2
win_y = max(0, (scr_h - win_h) // 2 - 20)
self.geometry(f"{win_w}x{win_h}+{win_x}+{win_y}")
self._setup_theme()
self._set_window_icon()
self._is_admin: bool = _is_admin()
self._current_thread: threading.Thread | None = None
self._scan_result: ScanResult | None = None
self._resize_after_id: str | None = None
self._progress_files: int = 0
self._progress_folders: int = 0
self._progress_ratio: float = 0.0
self._progress_last_path: str = ""
self._scan_start_time: float = 0.0
self._progress_updater_running: bool = False
self._progress_history: list = []
self._live_hierarchy: dict = {}
self._last_live_draw: float = 0.0
self._scan_mode: str = "fast"
self._font_cache: dict = {}
self._block_regions: list = [] # 每块 {rect, full_path, data, label},绘制顺序追加
self._path_stack: list = [] # [(path, hierarchy), ...],栈顶为当前视图;空表示无数据
self._scan_result_from_import: bool = False # True 表示当前为导入的 .gfav,不再用磁盘 live 更新
self._theme_name: str = "dark" # "dark" | "light",供切换主题后重绘
self._update_splash_progress(0.25, "正在创建界面组件...")
# Menu bar(在 top_frame 之上,深色主题)
_menu_bg = THEME["bg_header"]
_menu_fg = THEME["text"]
_menu_abg = THEME["accent_dim"]
_menu_afg = THEME.get("menu_active_fg", THEME["text"])
menubar = tk.Menu(
self, tearoff=0,
bg=_menu_bg, fg=_menu_fg,
activebackground=_menu_abg, activeforeground=_menu_afg,
selectcolor=THEME["accent"],
)
self.config(menu=menubar)
menu_export = tk.Menu(menubar, tearoff=0, bg=THEME["bg_surface"], fg=_menu_fg,
activebackground=_menu_abg, activeforeground=_menu_afg)
menubar.add_cascade(label="导出(E)", menu=menu_export, underline=3)
menu_export.add_command(label="导出为图片(P)", command=self._menu_export_png, underline=6)
menu_export.add_command(label="导出为专用格式(G)", command=self._menu_export_gfav, underline=8)
menubar.add_command(label="导入(I)", command=self._menu_import_gfav, underline=3)
menu_new = tk.Menu(menubar, tearoff=0, bg=THEME["bg_surface"], fg=_menu_fg,
activebackground=_menu_abg, activeforeground=_menu_afg)
menubar.add_cascade(label="新建(N)", menu=menu_new, underline=3)
menu_new.add_command(label="新建一个窗口(W)", command=self._menu_new_window, underline=7)
menubar.add_command(label="关于(A)", command=self._menu_about, underline=3)
menu_theme = tk.Menu(menubar, tearoff=0, bg=THEME["bg_surface"], fg=_menu_fg,
activebackground=_menu_abg, activeforeground=_menu_afg)
menubar.add_cascade(label="切换主题(T)", menu=menu_theme, underline=5)
menu_theme.add_command(label="深色主题(D)", command=lambda: self._set_theme("dark"), underline=5)
menu_theme.add_command(label="浅色主题(L)", command=lambda: self._set_theme("light"), underline=5)
# Top toolbar
top_frame = tk.Frame(self, bg=THEME["bg_header"])
top_frame.pack(side=tk.TOP, fill=tk.X)
inner = ttk.Frame(top_frame, style="Header.TFrame")
inner.pack(fill=tk.BOTH, expand=True, padx=10, pady=8)
ttk.Label(inner, text="选择磁盘:",
style="Header.TLabel").pack(side=tk.LEFT)
self.disk_var = tk.StringVar()
self.disk_combo = ttk.Combobox(
inner, textvariable=self.disk_var,
state="readonly", width=22)
self.disk_combo.pack(side=tk.LEFT, padx=(4, 12))
self.scan_button = ttk.Button(
inner, text=" 扫描 ", command=self.on_scan_clicked)
self.scan_button.pack(side=tk.LEFT)
self.mode_var = tk.StringVar(value="fast")
self._scan_mode_canvases: List[tuple] = [] # [(value, canvas), ...]
mode_frame = tk.Frame(inner, bg=THEME["bg_header"])
mode_frame.pack(side=tk.LEFT, padx=(20, 0))
for text, value in [("快速扫描(F)", "fast"), ("完整扫描(C)", "full")]:
padx = (0, 12) if value == "fast" else (0, 0)
self._add_big_dot_radio(mode_frame, text, value, padx)
self.mode_var.trace_add("write", lambda *a: self._draw_scan_mode_dots())
self._draw_scan_mode_dots()
self._update_splash_progress(0.40, "正在创建界面组件...")
# Info + progress row
info_frame = ttk.Frame(self)
info_frame.pack(side=tk.TOP, fill=tk.X, padx=10, pady=(6, 0))
self.info_var = tk.StringVar(value='请选择磁盘并点击"扫描"。')
ttk.Label(info_frame, textvariable=self.info_var,
anchor="w").pack(side=tk.LEFT, fill=tk.X, expand=True)
self.progress = ttk.Progressbar(
self, mode="determinate", maximum=1000)
self.progress.pack(side=tk.TOP, fill=tk.X, padx=10, pady=(4, 2))
# 路径栏(类似资源管理器,单击任意段跳转)
self._path_bar_frame = tk.Frame(self, bg=THEME["bg_surface"], height=32)
self._path_bar_frame.pack(side=tk.TOP, fill=tk.X, padx=10, pady=(2, 4))
self._path_bar_frame.pack_propagate(False)
self._path_bar_inner = tk.Frame(self._path_bar_frame, bg=THEME["bg_surface"])
self._path_bar_inner.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# 内容由 _refresh_path_bar() 动态填充
# Canvas
self.canvas = tk.Canvas(
self, bg=THEME["canvas_bg"], highlightthickness=0,
width=800, height=500)
self.canvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True,
padx=10, pady=(4, 4))
self.canvas.bind("<Configure>", self._on_canvas_configure)
self.canvas.bind("<Motion>", self._on_canvas_motion)
self.canvas.bind("<Leave>", self._on_canvas_leave)
self.canvas.bind("<Button-1>", self._on_canvas_click)
self.canvas.bind("<Double-Button-1>", self._on_canvas_double_click)
self._tooltip_win: tk.Toplevel | None = None
self._tooltip_after_id: str | None = None
self._pending_click_id: str | None = None
# Status bar:用 tk.Label 避免 ttk 主题裁切,足够高度+居左
status_bar = tk.Frame(self, bg=THEME["bg_header"], height=48)
status_bar.pack(side=tk.BOTTOM, fill=tk.X)
status_bar.pack_propagate(False)
self.status_var = tk.StringVar(value="")
status_label = tk.Label(
status_bar,
textvariable=self.status_var,
bg=THEME["bg_header"],
fg=THEME["text_dim"],
font=("Segoe UI", 9),
anchor="w",
justify="left",
)
status_label.pack(side=tk.LEFT, fill=tk.BOTH, expand=True,
padx=(14, 14), pady=10)
# 保存供主题切换时重配置的引用
self._menubar = menubar
self._menu_export = menu_export
self._menu_new = menu_new
self._menu_theme = menu_theme
self._top_frame = top_frame
self._status_bar = status_bar
self._status_label = status_label
self._mode_frame = mode_frame
# Alt 快捷键
self.bind("<Alt-s>", lambda e: self.on_scan_clicked())
self.bind("<Alt-S>", lambda e: self.on_scan_clicked())
self.bind("<Alt-f>", lambda e: self.mode_var.set("fast"))
self.bind("<Alt-F>", lambda e: self.mode_var.set("fast"))
self.bind("<Alt-c>", lambda e: self.mode_var.set("full"))
self.bind("<Alt-C>", lambda e: self.mode_var.set("full"))
self.bind("<Alt-d>", lambda e: self.disk_combo.focus_set())
self.bind("<Alt-D>", lambda e: self.disk_combo.focus_set())
self._update_splash_progress(0.65, "正在检测磁盘信息...")
self.load_disks()
self._update_splash_progress(1.0, "启动完成")
self.after(300, self._close_splash)
def _close_splash(self) -> None:
try:
self._splash.destroy()
except Exception:
pass
self.deiconify()
_set_dark_title_bar(self)
if not self._is_admin:
self.info_var.set(
'提示:当前以非管理员权限运行,MFT加速扫描不可用,'
'部分系统目录可能无法读取。点击"扫描"使用标准模式。')
# ── Disk / scan logic ────────────────────────────────────────
def load_disks(self) -> None:
disks = list_disks()
display_items = [f"{device} ({mount})" for device, mount in disks]
self._disk_mounts = [mount for _, mount in disks]
self.disk_combo["values"] = display_items
if display_items:
self.disk_combo.current(0)
self.info_var.set('请选择磁盘并点击"扫描"。')
else:
self.info_var.set("未发现可扫描的磁盘。")
def _menu_export_png(self) -> None:
"""导出画布为 PNG,由 t3 实现。"""
if not self._scan_result:
messagebox.showinfo("导出", "请先完成扫描再导出。")
return
self._do_export_png()
def _do_export_png(self) -> None:
"""导出画布区域为 PNG。"""
if ImageGrab is None:
messagebox.showerror("导出", "未安装 Pillow,无法导出为图片。请安装:pip install Pillow")
return
disk_path = self._scan_result.stats.disk_path
drive = (disk_path.rstrip("\\").rstrip(":") or "disk").replace(":", "_")
default_name = f"{dt.now().strftime('%Y-%m-%d_%H%M%S')}_{drive}.png"
path = filedialog.asksaveasfilename(
title="导出为图片",
defaultextension=".png",
initialfile=default_name,
filetypes=[("PNG 图片", "*.png"), ("所有文件", "*.*")],
)
if not path:
return
self.canvas.update_idletasks()
x = self.canvas.winfo_rootx()
y = self.canvas.winfo_rooty()
w = self.canvas.winfo_width()
h = self.canvas.winfo_height()
if w <= 0 or h <= 0:
messagebox.showerror("导出", "画布区域无效,无法截取。")
return
try:
img = ImageGrab.grab(bbox=(x, y, x + w, y + h))
img.save(path)
messagebox.showinfo("导出", f"已保存:{path}")
except Exception as e:
messagebox.showerror("导出", f"保存失败:{e}")
def _menu_export_gfav(self) -> None:
"""导出为 .gfav,由 t4 实现。"""
if not self._scan_result:
messagebox.showinfo("导出", "请先完成扫描再导出。")
return
self._do_export_gfav()
def _do_export_gfav(self) -> None:
"""导出为 .gfav 专用格式。"""
disk_path = self._scan_result.stats.disk_path
drive = (disk_path.rstrip("\\").rstrip(":") or "disk").replace(":", "_")
ver_safe = _VERSION.replace(" ", "_").replace("\t", "_")
default_name = f"{dt.now().strftime('%Y-%m-%d_%H%M%S')}_{drive}_{ver_safe}.gfav"
path = filedialog.asksaveasfilename(
title="导出为专用格式",
defaultextension=".gfav",
initialfile=default_name,
filetypes=[("GFAV 专用格式", "*.gfav"), ("所有文件", "*.*")],
)
if not path:
return
try:
payload = self._scan_result.to_gfav_dict()
payload["export_version"] = _VERSION
with open(path, "w", encoding="utf-8") as f:
f.write("GFAV\t" + _VERSION + "\n")
f.write(json.dumps(payload, ensure_ascii=False))
messagebox.showinfo("导出", f"已保存:{path}")
except Exception as e:
messagebox.showerror("导出", f"保存失败:{e}")
def _menu_import_gfav(self) -> None:
"""导入 .gfav,由 t4 实现。"""
self._do_import_gfav()
def _do_import_gfav(self) -> None:
"""从 .gfav 文件导入并刷新画布。"""
path = filedialog.askopenfilename(
title="导入专用格式",
filetypes=[("GFAV 专用格式", "*.gfav"), ("所有文件", "*.*")],
)
if not path:
return
try:
with open(path, "r", encoding="utf-8") as f:
first = f.readline()
if not first.startswith("GFAV\t"):
messagebox.showerror("导入", "不是有效的 .gfav 文件(缺少 GFAV 头)。")
return
rest = f.read()
data = json.loads(rest)
except json.JSONDecodeError as e:
messagebox.showerror("导入", f"JSON 解析失败:{e}")
return
except Exception as e:
messagebox.showerror("导入", f"读取失败:{e}")
return
try:
self._scan_result = ScanResult.from_gfav_dict(data)
self._scan_result_from_import = True
self._live_hierarchy = {}
self._path_stack = [(self._scan_result.stats.disk_path, self._scan_result.hierarchy)]
self._draw_treemap_from_hierarchy(self._scan_result.hierarchy, is_live=False)
self._refresh_path_bar()
# 导入后展示扫描时间、导出版本(首行 GFAV\t 后为版本)
gfav_version = first[5:].strip() if first.startswith("GFAV\t") else ""
scan_time_str = ""
if data.get("stats") and data["stats"].get("scan_time"):
scan_time_str = self._format_import_time(data["stats"]["scan_time"])
parts = [f"已导入:{self._scan_result.stats.disk_path}"]
if scan_time_str:
parts.append(f"扫描时间:{scan_time_str}")
if gfav_version:
parts.append(f"导出版本:{gfav_version}")
self.info_var.set(" ".join(parts))
except Exception as e:
messagebox.showerror("导入", f"加载失败:{e}")
def _menu_new_window(self) -> None:
"""新建一个窗口,由 t5 实现。"""
self._do_new_window()
def _do_new_window(self) -> None:
"""启动新进程再开一个窗口。"""
try:
cmd = [sys.executable]
if not getattr(sys, "frozen", False):
cmd.append(__file__)
subprocess.Popen(cmd, cwd=os.getcwd())
except Exception as e:
messagebox.showerror("新建窗口", f"启动失败:{e}")
def _menu_about(self) -> None:
"""关于窗口,由 t6 实现。"""
self._do_about()
def _do_about(self) -> None:
"""关于窗口:按文档一字不差展示,居中于主窗口。"""
win = tk.Toplevel(self)
win.title("关于")
win.configure(bg=THEME["bg_surface"])
win.transient(self)
win.resizable(False, False)
pad = 26
f = tk.Frame(win, bg=THEME["bg_surface"])
f.pack(padx=pad, pady=pad, fill=tk.BOTH, expand=True)
font_title = ("Segoe UI", 11, "bold")
font_body = ("Segoe UI", 10)
font_small = ("Segoe UI", 9)
wraplen = 600
row_gap = 6
section_gap = 22
# 作者信息
tk.Label(f, text="作者信息", font=font_title,
fg=THEME["text"], bg=THEME["bg_surface"]).pack(anchor="w")
tk.Label(f, text="作者:Green233", font=font_body,
fg=THEME["text"], bg=THEME["bg_surface"]).pack(anchor="w", pady=(0, row_gap))
qq_num = "3559946768"
lb_qq = tk.Label(f, text=f"QQ:{qq_num}", font=font_body,
fg=THEME["accent"], bg=THEME["bg_surface"], cursor="hand2")
lb_qq.pack(anchor="w", pady=(0, row_gap))
def copy_qq(_e=None):
win.clipboard_clear()
win.clipboard_append(qq_num)
messagebox.showinfo("关于", "QQ号已复制到剪贴板。", parent=win)
lb_qq.bind("<Button-1>", copy_qq)
email = "green233@green233.com"
lb_email = tk.Label(f, text=f"电子邮箱:{email}", font=font_body,
fg=THEME["accent"], bg=THEME["bg_surface"], cursor="hand2")
lb_email.pack(anchor="w")
def copy_email(_e=None):
win.clipboard_clear()
win.clipboard_append(email)
messagebox.showinfo("关于", "邮箱已复制到剪贴板。", parent=win)
lb_email.bind("<Button-1>", copy_email)
# 项目信息
tk.Label(f, text="项目信息", font=font_title,
fg=THEME["text"], bg=THEME["bg_surface"]).pack(anchor="w", pady=(section_gap, 0))
url_repo = "https://github.com/Green233233/GreenDiskVisualizer"
row_repo = tk.Frame(f, bg=THEME["bg_surface"])
row_repo.pack(anchor="w", pady=(0, row_gap))
tk.Label(row_repo, text="本项目已在 GitHub 上开源 ", font=font_body,
fg=THEME["text"], bg=THEME["bg_surface"]).pack(side=tk.LEFT)
lb_repo = tk.Label(row_repo, text="项目地址", font=font_body,
fg=THEME["accent"], bg=THEME["bg_surface"], cursor="hand2")
lb_repo.pack(side=tk.LEFT)
lb_repo.bind("<Button-1>", lambda e: webbrowser.open(url_repo))
tk.Label(f, text="(所以如果你在哪里买到了这个软件一定要狠狠地给一个差评!!!)",
font=font_body, fg=THEME["text"], bg=THEME["bg_surface"],
wraplength=wraplen, justify=tk.LEFT).pack(anchor="w", pady=(0, row_gap))
tk.Label(f, text=" 项目部分代码使用AI辅助编写",
font=font_body, fg=THEME["text_dim"], bg=THEME["bg_surface"],
wraplength=wraplen, justify=tk.LEFT).pack(anchor="w")
# 反馈和帮助
tk.Label(f, text="反馈和帮助", font=font_title,
fg=THEME["text"], bg=THEME["bg_surface"]).pack(anchor="w", pady=(section_gap, 0))
tk.Label(f, text="如在使用中遇到问题 欢迎提交 issue 反馈",
font=font_body, fg=THEME["text"], bg=THEME["bg_surface"],
wraplength=wraplen, justify=tk.LEFT).pack(anchor="w", pady=(0, row_gap))
row_readme = tk.Frame(f, bg=THEME["bg_surface"])
row_readme.pack(anchor="w", pady=(0, row_gap))
tk.Label(row_readme, text="本软件的详细使用方法请参考 ", font=font_body,
fg=THEME["text"], bg=THEME["bg_surface"]).pack(side=tk.LEFT)
lb_readme = tk.Label(row_readme, text="项目的readme文档", font=font_body,
fg=THEME["accent"], bg=THEME["bg_surface"], cursor="hand2")
lb_readme.pack(side=tk.LEFT)
lb_readme.bind("<Button-1>", lambda e: webbrowser.open(url_repo))
tk.Label(f, text="满意请赏个 Star 哦",
font=font_body, fg=THEME["text"], bg=THEME["bg_surface"]).pack(anchor="w")
# 与上一句拉开约 1.5 行高
tk.Label(f, text="对了,你看《金牌得主》第二季了吗,超好看的!!!",
font=font_small, fg=THEME["text_dim"], bg=THEME["bg_surface"],
wraplength=wraplen, justify=tk.LEFT).pack(anchor="w", pady=(22, 0))
tk.Button(f, text="关闭", command=win.destroy,
bg=THEME["accent_dim"], fg=THEME["text"], relief=tk.FLAT,
padx=12, pady=4, cursor="hand2").pack(pady=(20, 0))
win.update_idletasks()
w = win.winfo_reqwidth()
h = win.winfo_reqheight()
mx = self.winfo_x()
my = self.winfo_y()
mw = self.winfo_width()
mh = self.winfo_height()
x = mx + max(0, (mw - w) // 2)
y = my + max(0, (mh - h) // 2)
win.geometry(f"+{x}+{y}")
def on_scan_clicked(self) -> None:
if self._current_thread and self._current_thread.is_alive():
messagebox.showinfo("扫描进行中",
"当前已有扫描任务在执行,请稍候。")
return
idx = self.disk_combo.current()
if idx < 0 or idx >= len(getattr(self, "_disk_mounts", [])):
messagebox.showwarning("请选择磁盘", "请先选择一个磁盘。")
return
mount = self._disk_mounts[idx]
mode = self.mode_var.get()
self._scan_mode = mode
if mode == "fast":
exclude = [
"$Recycle.Bin", "System Volume Information",
"\\Windows\\WinSxS", "\\Windows\\Temp",
"\\Windows\\Installer", "\\Program Files\\WindowsApps",
"\\AppData\\Local\\Temp",
".git", "node_modules", "__pycache__",
]
options = ScanOptions(
path=mount, recursive=True, follow_symlinks=False,
calculate_hash=False, exclude_patterns=exclude,
max_depth=None, collect_file_details=False)
self.info_var.set(
f"正在快速扫描:{mount}(智能聚合模式,排除系统/临时目录)...")
else:
exclude = ["$Recycle.Bin", "System Volume Information"]
options = ScanOptions(
path=mount, recursive=True, follow_symlinks=False,
calculate_hash=False, exclude_patterns=exclude,
max_depth=None)
self.info_var.set(
f"正在完整扫描:{mount}(可能耗时较长,请耐心等待)...")
self._scan_start_time = time.time()
self._progress_files = 0
self._progress_folders = 0
self._progress_ratio = 0.0
self._progress_last_path = ""
self._progress_phase_message = "" # MFT 阶段提示,如「正在读取MFT文件表...」
self._scan_result_from_import = False
self._progress_updater_running = True
self._progress_history = []
self._last_live_draw = 0.0
self.progress["value"] = 0
self.canvas.delete("all")
self.status_var.set("进度:0.0% 预计剩余时间:估算中...")
self._live_hierarchy = {}
self.after(200, self._update_progress_ui)
def worker():
try:
result = scan_path(
options,
progress_callback=self._on_scan_progress,
shared_hierarchy=self._live_hierarchy)
except Exception as e:
self.after(0, lambda: self.on_scan_failed(str(e)))
return
self.after(0, lambda: self.on_scan_finished(result))
t = threading.Thread(target=worker, daemon=True)
self._current_thread = t
t.start()
def on_scan_finished(self, result: ScanResult) -> None:
self._progress_updater_running = False
self.progress["value"] = self.progress["maximum"]
self._scan_result = result
self._path_stack = [(result.stats.disk_path, result.hierarchy)]
method_text = "MFT加速" if result.scan_method == "mft" else "标准"
self.info_var.set(
f"扫描完成({method_text}):"
f"文件 {result.stats.file_count} 个,"
f"文件夹 {result.stats.folder_count} 个,"
f"用时 {result.scan_duration_ms} ms。")
self.status_var.set(
f"总容量: {self._format_size(result.stats.total_size)} "
f"已用: {self._format_size(result.stats.used_size)} "
f"可用: {self._format_size(result.stats.free_size)}")
self._draw_treemap_from_hierarchy(result.hierarchy, is_live=False)
self._refresh_path_bar()
def on_scan_failed(self, message: str) -> None:
self._progress_updater_running = False
messagebox.showerror("扫描失败",
f"扫描过程中出现错误:\n{message}")
# ── Progress / progressive rendering ─────────────────────────
def _on_scan_progress(self, files: int, folders: int,
current_path: str, ratio: float) -> None:
self._progress_files = files
self._progress_folders = folders
self._progress_last_path = current_path
self._progress_ratio = max(0.0, min(ratio, 1.0))
# 阶段提示(如「正在读取MFT文件表...」)用于底栏显示
if current_path.startswith("正在") or current_path.startswith("开始"):
self._progress_phase_message = current_path
else:
self._progress_phase_message = ""
def _update_progress_ui(self) -> None:
if not self._progress_updater_running:
return
ratio = self._progress_ratio
self.progress["value"] = int(ratio * self.progress["maximum"])
now = time.time()
self._progress_history.append((now, ratio))
cutoff = now - 15
self._progress_history = [
(t, r) for t, r in self._progress_history if t >= cutoff]
eta = "估算中..."
# 仅在扫描进度达到一定比例且过去一段时间后才开始估算,
# 避免前期因为样本太少导致的严重高估。
if (len(self._progress_history) >= 2
and ratio >= 0.05):