Repository navigation
Expand file tree
/
Copy pathdeclutter_app.py
More file actions
1580 lines (1392 loc) · 57.5 KB
/
Copy pathdeclutter_app.py
File metadata and controls
1580 lines (1392 loc) · 57.5 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
from __future__ import annotations
import ctypes
import heapq
import json
import os
import queue
import subprocess
import sys
import threading
import time
from ctypes import wintypes
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from tkinter import (
BooleanVar,
Button,
Canvas,
Checkbutton,
END,
Entry,
Frame,
Label,
LabelFrame,
Listbox,
PanedWindow,
StringVar,
Tk,
Toplevel,
filedialog,
messagebox,
ttk,
)
from tkinter.constants import BOTH, BOTTOM, DISABLED, HORIZONTAL, LEFT, NORMAL, RIGHT, VERTICAL, X, Y
APP_NAME = "Declutter"
APP_VERSION = "1.0"
DECLUTTER_FOLDER_NAME = "Decluttered Desktop"
MANIFEST_DIR = Path(os.environ.get("LOCALAPPDATA", Path.home())) / "DeclutterApp" / "manifests"
PROJECT_ROOT = Path(__file__).resolve().parent
TREEMAP_CHILD_LIMIT = 10
TREEMAP_MAX_DEPTH = 4
LARGEST_LIST_LIMIT = 40
MOVE_TIMEOUT_SECONDS = 12
TREEMAP_LABEL_MIN_AREA = 18000
TREEMAP_LEAF_LABEL_MIN_AREA = 32000
RISKY_DELETE_MESSAGE = (
"This could very well corrupt your system... Are you sure?\n\n"
"Declutter is looking at this file with deep suspicion. It lives somewhere "
"system-ish or has a spicy extension, and deleting it may make Windows start "
"speaking in riddles.\n\n"
"Selected file:\n{path}\n\n"
"Why it looks bad:\n{reasons}"
)
EXTENSION_CATEGORIES = {
"Documents": {
".doc",
".docx",
".odt",
".rtf",
".txt",
".md",
".pages",
".epub",
},
"PDFs": {".pdf"},
"Spreadsheets": {".xls", ".xlsx", ".xlsm", ".csv", ".tsv", ".ods", ".numbers"},
"Presentations": {".ppt", ".pptx", ".key", ".odp"},
"Images": {
".png",
".jpg",
".jpeg",
".gif",
".bmp",
".webp",
".tif",
".tiff",
".heic",
".svg",
".ico",
},
"Videos": {".mp4", ".mov", ".mkv", ".avi", ".wmv", ".webm", ".m4v"},
"Audio": {".mp3", ".wav", ".aiff", ".aac", ".flac", ".m4a", ".ogg"},
"Archives": {".zip", ".rar", ".7z", ".tar", ".gz", ".bz2", ".xz"},
"Installers": {".exe", ".msi", ".dmg", ".pkg", ".appx", ".msix"},
"Code": {
".py",
".js",
".ts",
".tsx",
".jsx",
".html",
".css",
".json",
".xml",
".yaml",
".yml",
".java",
".cs",
".cpp",
".c",
".h",
".hpp",
".rs",
".go",
".php",
".rb",
".sql",
".sh",
".ps1",
".bat",
".cmd",
},
"Shortcuts": {".lnk", ".url", ".website"},
"Fonts": {".ttf", ".otf", ".woff", ".woff2"},
"Design": {".psd", ".ai", ".xd", ".fig", ".sketch", ".indd"},
}
NAME_RULES = {
"Screenshots": ("screenshot", "screen shot", "snip", "capture"),
"Receipts": ("receipt", "invoice", "bill", "statement"),
"Work": ("resume", "cv", "cover letter", "contract", "proposal"),
}
COLORS = [
"#2f6f73",
"#c45f4c",
"#6c7a2e",
"#715b94",
"#b4762f",
"#3f5f8f",
"#8b4f64",
"#447a4f",
"#936f39",
"#58666f",
"#9b6b89",
"#4d7570",
]
@dataclass
class DesktopItem:
path: Path
category: str
size: int
kind: str
target: Path
note: str = ""
@dataclass
class ScanNode:
path: Path
name: str
size: int = 0
files: int = 0
dirs: int = 0
children: list["ScanNode"] = field(default_factory=list)
error: str = ""
is_file: bool = False
@dataclass
class SkippedMove:
source: Path
category: str
reason: str
@dataclass
class OrganizeSummary:
manifest_path: Path
moved_count: int
skipped: list[SkippedMove]
def get_desktop_path() -> Path:
"""Return the current user's Desktop path, including OneDrive redirection when Windows reports it."""
try:
class GUID(ctypes.Structure):
_fields_ = [
("Data1", ctypes.c_ulong),
("Data2", ctypes.c_ushort),
("Data3", ctypes.c_ushort),
("Data4", ctypes.c_ubyte * 8),
]
desktop_guid = GUID(
0xB4BFCC3A,
0xDB2C,
0x424C,
(ctypes.c_ubyte * 8)(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41),
)
path_ptr = ctypes.c_void_p()
ctypes.windll.shell32.SHGetKnownFolderPath(
ctypes.byref(desktop_guid),
0,
None,
ctypes.byref(path_ptr),
)
if path_ptr.value:
desktop = ctypes.wstring_at(path_ptr.value)
ctypes.windll.ole32.CoTaskMemFree(path_ptr)
return Path(desktop)
except Exception:
pass
candidates = [
Path(os.environ.get("OneDrive", "")) / "Desktop",
Path.home() / "OneDrive" / "Desktop",
Path.home() / "Desktop",
]
for candidate in candidates:
if str(candidate) and candidate.exists():
return candidate
return Path.home() / "Desktop"
def human_size(size: int) -> str:
value = float(size)
for unit in ("B", "KB", "MB", "GB", "TB", "PB"):
if value < 1024 or unit == "PB":
if unit == "B":
return f"{int(value)} {unit}"
return f"{value:.1f} {unit}"
value /= 1024
return f"{size} B"
def folder_size_quick(path: Path, limit: int = 500) -> tuple[int, str]:
total = 0
seen = 0
try:
for root, dirs, files in os.walk(path):
dirs[:] = [name for name in dirs if not name.startswith(".")]
for file_name in files:
try:
total += (Path(root) / file_name).stat().st_size
except OSError:
continue
seen += 1
if seen >= limit:
return total, "estimated"
except OSError:
return 0, "permission denied"
return total, ""
def unique_destination(path: Path) -> Path:
if not path.exists():
return path
stem = path.stem
suffix = path.suffix
parent = path.parent
counter = 2
while True:
candidate = parent / f"{stem} ({counter}){suffix}"
if not candidate.exists():
return candidate
counter += 1
def move_with_timeout(source: Path, destination: Path, timeout_seconds: int = MOVE_TIMEOUT_SECONDS) -> tuple[bool, str]:
if not source.exists():
return False, "source no longer exists"
script = (
"import shutil, sys\n"
"shutil.move(sys.argv[1], sys.argv[2])\n"
)
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
try:
result = subprocess.run(
[sys.executable, "-c", script, str(source), str(destination)],
capture_output=True,
text=True,
timeout=timeout_seconds,
creationflags=creationflags,
)
except subprocess.TimeoutExpired:
if destination.exists() and not source.exists():
return True, "moved after timeout"
return False, f"timed out after {timeout_seconds}s"
if result.returncode == 0:
return True, ""
if destination.exists() and not source.exists():
return True, "moved with warning"
detail = (result.stderr or result.stdout or "move failed").strip().splitlines()
return False, detail[-1] if detail else "move failed"
def shorten_text(text: str, max_chars: int) -> str:
if len(text) <= max_chars:
return text
if max_chars <= 3:
return text[:max_chars]
return text[: max_chars - 3] + "..."
def delete_file_to_recycle_bin(path: Path) -> tuple[bool, str]:
if not path.exists():
return False, "file no longer exists"
if not path.is_file():
return False, "only files can be deleted from the visualizer"
if os.name != "nt":
path.unlink()
return True, "deleted"
class SHFILEOPSTRUCTW(ctypes.Structure):
_fields_ = [
("hwnd", wintypes.HWND),
("wFunc", wintypes.UINT),
("pFrom", wintypes.LPCWSTR),
("pTo", wintypes.LPCWSTR),
("fFlags", wintypes.USHORT),
("fAnyOperationsAborted", wintypes.BOOL),
("hNameMappings", wintypes.LPVOID),
("lpszProgressTitle", wintypes.LPCWSTR),
]
operation = SHFILEOPSTRUCTW()
operation.hwnd = None
operation.wFunc = 3 # FO_DELETE
operation.pFrom = str(path) + "\0\0"
operation.pTo = None
operation.fFlags = 0x0040 | 0x0010 | 0x0400 # recycle, no extra confirm dialog, no error UI
result = ctypes.windll.shell32.SHFileOperationW(ctypes.byref(operation))
if result != 0:
return False, f"Windows delete failed ({result})"
if operation.fAnyOperationsAborted:
return False, "delete canceled"
return True, "moved to Recycle Bin"
def risky_delete_reasons(path: Path) -> list[str]:
parts = [part.lower() for part in path.parts]
path_text = str(path).lower()
reasons: list[str] = []
risky_fragments = {
"windows": "inside the Windows folder",
"system32": "inside System32",
"syswow64": "inside SysWOW64",
"winsxs": "inside the Windows component store",
"program files": "inside Program Files",
"program files (x86)": "inside Program Files (x86)",
"programdata": "inside ProgramData",
"appdata": "inside AppData",
"system volume information": "inside System Volume Information",
"boot": "inside a boot-related folder",
}
for fragment, reason in risky_fragments.items():
if fragment in parts or f"\\{fragment}\\" in path_text:
reasons.append(reason)
risky_extensions = {
".sys": "system driver file",
".dll": "shared Windows/program library",
".drv": "driver file",
".ocx": "system component file",
".efi": "boot firmware file",
".mui": "Windows resource file",
".cat": "security catalog file",
".inf": "driver/install information file",
".exe": "executable program",
".msi": "installer package",
}
if path.suffix.lower() in risky_extensions:
reasons.append(risky_extensions[path.suffix.lower()])
if path.parent == Path(path.anchor):
reasons.append("sitting directly at the root of a drive")
return sorted(set(reasons))
class DesktopOrganizer:
def __init__(self, desktop_path: Path):
self.desktop_path = desktop_path
self.target_root = desktop_path / DECLUTTER_FOLDER_NAME
def category_for(self, path: Path) -> str:
if path.is_dir():
lowered = path.name.lower()
for category, tokens in NAME_RULES.items():
if any(token in lowered for token in tokens):
return category
return "Folders"
lowered_name = path.name.lower()
for category, tokens in NAME_RULES.items():
if any(token in lowered_name for token in tokens):
return category
extension = path.suffix.lower()
for category, extensions in EXTENSION_CATEGORIES.items():
if extension in extensions:
return category
return "Other"
def is_protected(self, path: Path) -> bool:
protected_names = {
"desktop.ini",
"$recycle.bin",
"recycle bin",
DECLUTTER_FOLDER_NAME.lower(),
}
if path.name.lower() in protected_names:
return True
try:
if path.resolve() == PROJECT_ROOT or PROJECT_ROOT in path.resolve().parents:
return True
except OSError:
pass
return False
def scan(self, include_folders: bool) -> list[DesktopItem]:
items: list[DesktopItem] = []
if not self.desktop_path.exists():
return items
for entry in sorted(self.desktop_path.iterdir(), key=lambda p: p.name.lower()):
if self.is_protected(entry):
continue
if entry.is_dir() and not include_folders:
continue
category = self.category_for(entry)
if entry.is_dir():
size, note = folder_size_quick(entry)
kind = "Folder"
else:
try:
size = entry.stat().st_size
note = ""
except OSError:
size = 0
note = "unreadable"
kind = entry.suffix.lower() or "File"
target = self.target_root / category / entry.name
items.append(DesktopItem(entry, category, size, kind, target, note))
return items
def organize(
self,
items: list[DesktopItem],
progress_callback=None,
timeout_seconds: int = MOVE_TIMEOUT_SECONDS,
) -> OrganizeSummary:
if not items:
raise ValueError("No items selected to organize.")
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
manifest = {
"app": APP_NAME,
"version": APP_VERSION,
"created_at": datetime.now().isoformat(timespec="seconds"),
"desktop": str(self.desktop_path),
"moves": [],
"skipped": [],
}
skipped: list[SkippedMove] = []
total = len(items)
for index, item in enumerate(items, start=1):
target_dir = item.target.parent
target_dir.mkdir(parents=True, exist_ok=True)
destination = unique_destination(item.target)
if progress_callback:
progress_callback(index - 1, total, item, destination, "moving", "")
moved, reason = move_with_timeout(item.path, destination, timeout_seconds=timeout_seconds)
if not moved:
skipped_item = SkippedMove(item.path, item.category, reason)
skipped.append(skipped_item)
manifest["skipped"].append(
{
"source": str(item.path),
"category": item.category,
"size": item.size,
"kind": item.kind,
"reason": reason,
}
)
if progress_callback:
progress_callback(index, total, item, destination, "skipped", reason)
continue
manifest["moves"].append(
{
"source": str(item.path),
"destination": str(destination),
"category": item.category,
"size": item.size,
"kind": item.kind,
}
)
if progress_callback:
progress_callback(index, total, item, destination, "moved", reason)
MANIFEST_DIR.mkdir(parents=True, exist_ok=True)
manifest_path = MANIFEST_DIR / f"declutter-{timestamp}.json"
manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
return OrganizeSummary(manifest_path, len(manifest["moves"]), skipped)
def latest_manifest(self) -> Path | None:
if not MANIFEST_DIR.exists():
return None
manifests = sorted(MANIFEST_DIR.glob("declutter-*.json"), key=lambda p: p.stat().st_mtime)
return manifests[-1] if manifests else None
def undo(self, manifest_path: Path, progress_callback=None) -> tuple[int, list[str]]:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
restored = 0
problems: list[str] = []
moves = list(reversed(manifest.get("moves", [])))
total = len(moves)
for index, move in enumerate(moves, start=1):
source = Path(move["source"])
destination = Path(move["destination"])
if not destination.exists():
problems.append(f"Missing: {destination}")
if progress_callback:
progress_callback(index, total, destination.name)
continue
source.parent.mkdir(parents=True, exist_ok=True)
restore_to = source if not source.exists() else unique_destination(source)
moved, reason = move_with_timeout(destination, restore_to)
if moved:
restored += 1
else:
problems.append(f"{destination.name}: {reason}")
if progress_callback:
progress_callback(index, total, destination.name)
return restored, problems
class DiskScanner:
def __init__(self, stop_event: threading.Event, progress: queue.Queue):
self.stop_event = stop_event
self.progress = progress
def scan(self, root: Path, max_depth: int = 5, max_children: int = 120) -> ScanNode:
return self._scan_dir(root, depth=0, max_depth=max_depth, max_children=max_children)
def _scan_dir(self, path: Path, depth: int, max_depth: int, max_children: int) -> ScanNode:
node = ScanNode(path=path, name=path.name or str(path))
if self.stop_event.is_set():
return node
try:
entries = list(os.scandir(path))
except OSError as exc:
node.error = str(exc)
return node
child_nodes: list[ScanNode] = []
for entry in entries:
if self.stop_event.is_set():
break
try:
if entry.is_symlink():
continue
if entry.is_dir(follow_symlinks=False):
node.dirs += 1
if depth < max_depth:
child = self._scan_dir(Path(entry.path), depth + 1, max_depth, max_children)
node.size += child.size
node.files += child.files
node.dirs += child.dirs
child_nodes.append(child)
else:
size, files = self._estimate_dir(Path(entry.path))
node.size += size
node.files += files
child_nodes.append(
ScanNode(
path=Path(entry.path),
name=entry.name,
size=size,
files=files,
dirs=0,
error="depth limit",
)
)
elif entry.is_file(follow_symlinks=False):
size = entry.stat(follow_symlinks=False).st_size
node.size += size
node.files += 1
if depth < 2:
child_nodes.append(
ScanNode(path=Path(entry.path), name=entry.name, size=size, files=1, is_file=True)
)
except OSError:
continue
child_nodes.sort(key=lambda item: item.size, reverse=True)
if len(child_nodes) > max_children:
kept = child_nodes[:max_children]
remainder = child_nodes[max_children:]
kept.append(
ScanNode(
path=path,
name=f"Other {len(remainder)} items",
size=sum(item.size for item in remainder),
files=sum(item.files for item in remainder),
dirs=sum(item.dirs for item in remainder),
)
)
child_nodes = kept
node.children = child_nodes
if depth <= 1:
self.progress.put(("progress", f"Scanned {path} ({human_size(node.size)})"))
return node
def _estimate_dir(self, path: Path, limit: int = 300) -> tuple[int, int]:
total = 0
files = 0
try:
for root, dirs, names in os.walk(path):
if self.stop_event.is_set():
break
dirs[:] = [name for name in dirs if not name.startswith("$")]
for name in names:
try:
total += (Path(root) / name).stat().st_size
except OSError:
continue
files += 1
if files >= limit:
return total, files
except OSError:
return total, files
return total, files
class DeclutterApp(Tk):
def __init__(self) -> None:
super().__init__()
self.title(f"{APP_NAME} {APP_VERSION}")
self.geometry("1180x760")
self.minsize(980, 640)
self.desktop_path = get_desktop_path()
self.organizer = DesktopOrganizer(self.desktop_path)
self.desktop_items: list[DesktopItem] = []
self.organizer_busy = False
self.organizer_thread: threading.Thread | None = None
self.scan_root = StringVar(value=str(self.desktop_path.anchor or self.desktop_path))
self.desktop_var = StringVar(value=str(self.desktop_path))
self.include_folders = BooleanVar(value=False)
self.status_var = StringVar(value="Ready")
self.disk_status_var = StringVar(value="Choose a drive or folder, then scan.")
self.progress_queue: queue.Queue = queue.Queue()
self.stop_event = threading.Event()
self.scan_thread: threading.Thread | None = None
self.disk_root_node: ScanNode | None = None
self.hover_node: ScanNode | None = None
self.selected_node: ScanNode | None = None
self.delete_in_progress = False
self.largest_nodes_cache: list[ScanNode] = []
self.rect_nodes: list[tuple[float, float, float, float, ScanNode, int]] = []
self.configure(bg="#f5f4f0")
self._configure_styles()
self._build_ui()
self._poll_queue()
def _configure_styles(self) -> None:
style = ttk.Style()
try:
style.theme_use("clam")
except Exception:
pass
style.configure("TNotebook", background="#f5f4f0", borderwidth=0)
style.configure("TNotebook.Tab", padding=(18, 10), font=("Segoe UI", 10))
style.configure("Treeview", rowheight=26, font=("Segoe UI", 10), fieldbackground="#ffffff")
style.configure("Treeview.Heading", font=("Segoe UI Semibold", 10))
style.configure("TLabelframe", background="#f5f4f0")
style.configure("TLabelframe.Label", background="#f5f4f0", font=("Segoe UI Semibold", 10))
style.configure("TButton", padding=(10, 7), font=("Segoe UI", 10))
def _build_ui(self) -> None:
shell = Frame(self, bg="#f5f4f0", padx=16, pady=14)
shell.pack(fill=BOTH, expand=True)
header = Frame(shell, bg="#f5f4f0")
header.pack(fill=X, pady=(0, 12))
Label(header, text="Declutter", bg="#f5f4f0", fg="#1d2428", font=("Segoe UI Semibold", 20)).pack(side=LEFT)
Label(
header,
text="Smart desktop folders and drive space maps",
bg="#f5f4f0",
fg="#5d666b",
font=("Segoe UI", 10),
).pack(side=LEFT, padx=(14, 0), pady=(7, 0))
notebook = ttk.Notebook(shell)
notebook.pack(fill=BOTH, expand=True)
organizer_tab = Frame(notebook, bg="#f5f4f0")
visualizer_tab = Frame(notebook, bg="#f5f4f0")
notebook.add(organizer_tab, text="Desktop Organizer")
notebook.add(visualizer_tab, text="Drive Graph")
self._build_organizer_tab(organizer_tab)
self._build_visualizer_tab(visualizer_tab)
status = Label(shell, textvariable=self.status_var, anchor="w", bg="#f5f4f0", fg="#5d666b", font=("Segoe UI", 9))
status.pack(fill=X, pady=(10, 0))
def _build_organizer_tab(self, parent: Frame) -> None:
top = LabelFrame(parent, text="Desktop source", padx=12, pady=10)
top.pack(fill=X, pady=(8, 12))
Entry(top, textvariable=self.desktop_var, font=("Segoe UI", 10)).pack(side=LEFT, fill=X, expand=True, padx=(0, 10))
self.browse_button = Button(top, text="Browse", command=self.choose_desktop)
self.browse_button.pack(side=LEFT, padx=(0, 8))
self.analyze_button = Button(top, text="Analyze", command=self.analyze_desktop)
self.analyze_button.pack(side=LEFT)
self.include_folders_check = Checkbutton(
top,
text="Include folders",
variable=self.include_folders,
bg="#f5f4f0",
font=("Segoe UI", 10),
)
self.include_folders_check.pack(side=LEFT, padx=(12, 0))
body = PanedWindow(parent, orient=HORIZONTAL, sashwidth=8, bg="#f5f4f0", bd=0)
body.pack(fill=BOTH, expand=True)
table_frame = Frame(body, bg="#f5f4f0")
body.add(table_frame, stretch="always")
columns = ("name", "category", "kind", "size", "target", "note")
self.desktop_tree = ttk.Treeview(table_frame, columns=columns, show="headings", selectmode="extended")
headings = {
"name": "Name",
"category": "Folder",
"kind": "Type",
"size": "Size",
"target": "Destination",
"note": "Note",
}
widths = {"name": 220, "category": 120, "kind": 90, "size": 90, "target": 300, "note": 110}
for column in columns:
self.desktop_tree.heading(column, text=headings[column])
self.desktop_tree.column(column, width=widths[column], anchor="w")
self.desktop_tree.pack(side=LEFT, fill=BOTH, expand=True)
scrollbar = ttk.Scrollbar(table_frame, orient=VERTICAL, command=self.desktop_tree.yview)
scrollbar.pack(side=RIGHT, fill=Y)
self.desktop_tree.configure(yscrollcommand=scrollbar.set)
side = Frame(body, bg="#f5f4f0", padx=12)
body.add(side, width=280)
summary = LabelFrame(side, text="Summary", padx=12, pady=10)
summary.pack(fill=X)
self.summary_label = Label(
summary,
text="Analyze your desktop to see suggested folders.",
justify=LEFT,
bg="#f5f4f0",
fg="#293238",
font=("Segoe UI", 10),
wraplength=235,
)
self.summary_label.pack(anchor="w")
actions = LabelFrame(side, text="Actions", padx=12, pady=10)
actions.pack(fill=X, pady=(12, 0))
self.organize_selected_button = Button(actions, text="Organize selected", command=self.organize_selected)
self.organize_selected_button.pack(fill=X, pady=(0, 8))
self.organize_all_button = Button(actions, text="Organize all", command=self.organize_all)
self.organize_all_button.pack(fill=X, pady=(0, 8))
self.undo_button = Button(actions, text="Undo last run", command=self.undo_last)
self.undo_button.pack(fill=X)
self.organizer_progress = ttk.Progressbar(actions, mode="determinate", maximum=100)
self.organizer_progress.pack(fill=X, pady=(12, 0))
notes = LabelFrame(side, text="Rules", padx=12, pady=10)
notes.pack(fill=BOTH, expand=True, pady=(12, 0))
Label(
notes,
text=(
"Items are grouped by file type and helpful name clues like "
"screenshot, invoice, receipt, resume, and proposal. Existing folders "
"stay put unless you enable Include folders."
),
justify=LEFT,
bg="#f5f4f0",
fg="#4d585f",
font=("Segoe UI", 9),
wraplength=235,
).pack(anchor="w")
def _build_visualizer_tab(self, parent: Frame) -> None:
top = LabelFrame(parent, text="Scan target", padx=12, pady=10)
top.pack(fill=X, pady=(8, 12))
Entry(top, textvariable=self.scan_root, font=("Segoe UI", 10)).pack(side=LEFT, fill=X, expand=True, padx=(0, 10))
Button(top, text="Drive", command=self.choose_drive).pack(side=LEFT, padx=(0, 8))
Button(top, text="Folder", command=self.choose_scan_folder).pack(side=LEFT, padx=(0, 8))
self.scan_button = Button(top, text="Scan", command=self.start_disk_scan)
self.scan_button.pack(side=LEFT, padx=(0, 8))
self.stop_button = Button(top, text="Stop", command=self.stop_disk_scan, state=DISABLED)
self.stop_button.pack(side=LEFT)
body = PanedWindow(parent, orient=HORIZONTAL, sashwidth=8, bg="#f5f4f0", bd=0)
body.pack(fill=BOTH, expand=True)
graph_panel = Frame(body, bg="#f5f4f0")
body.add(graph_panel, stretch="always")
self.disk_canvas = Canvas(graph_panel, bg="#ffffff", highlightthickness=1, highlightbackground="#d8d5cb")
self.disk_canvas.pack(fill=BOTH, expand=True)
self.disk_canvas.bind("<Configure>", lambda _event: self.draw_treemap())
self.disk_canvas.bind("<Motion>", self.on_canvas_motion)
self.disk_canvas.bind("<Button-1>", self.on_canvas_click)
self.disk_canvas.bind("<Leave>", lambda _event: self.set_hover(None))
disk_status = Label(
graph_panel,
textvariable=self.disk_status_var,
anchor="w",
bg="#f5f4f0",
fg="#5d666b",
font=("Segoe UI", 9),
)
disk_status.pack(fill=X, pady=(8, 0))
side = Frame(body, bg="#f5f4f0", padx=12)
body.add(side, width=315)
detail = LabelFrame(side, text="Selected area", padx=12, pady=10)
detail.pack(fill=X)
self.hover_label = Label(
detail,
text="Select an item in the chart or largest list.",
justify=LEFT,
bg="#f5f4f0",
fg="#293238",
font=("Segoe UI", 10),
wraplength=260,
)
self.hover_label.pack(anchor="w")
self.delete_selected_button = Button(
detail,
text="Delete selected file",
command=self.delete_selected_file,
state=DISABLED,
fg="#8a2d24",
)
self.delete_selected_button.pack(fill=X, pady=(10, 0))
largest = LabelFrame(side, text="Largest items", padx=12, pady=10)
largest.pack(fill=BOTH, expand=True, pady=(12, 0))
self.largest_list = Listbox(largest, font=("Segoe UI", 10), activestyle="none", height=18)
self.largest_list.pack(side=LEFT, fill=BOTH, expand=True)
largest_scroll = ttk.Scrollbar(largest, orient=VERTICAL, command=self.largest_list.yview)
largest_scroll.pack(side=RIGHT, fill=Y)
self.largest_list.configure(yscrollcommand=largest_scroll.set)
self.largest_list.bind("<<ListboxSelect>>", self.on_largest_select)
def choose_desktop(self) -> None:
selected = filedialog.askdirectory(initialdir=str(self.desktop_path), title="Choose desktop or folder to organize")
if selected:
self.desktop_path = Path(selected)
self.desktop_var.set(selected)
self.organizer = DesktopOrganizer(self.desktop_path)
self.status_var.set(f"Desktop source set to {selected}")
def analyze_desktop(self) -> None:
if self.organizer_busy:
self.status_var.set("Desktop work is already running.")
return
self.desktop_path = Path(self.desktop_var.get()).expanduser()
if not self.desktop_path.exists():
messagebox.showerror(APP_NAME, f"{self.desktop_path} does not exist.")
return
desktop_path = self.desktop_path
self.organizer = DesktopOrganizer(self.desktop_path)
include_folders = self.include_folders.get()
self.desktop_items = []
self._clear_desktop_tree()
self.summary_label.configure(text="Analyzing your desktop...")
self._set_organizer_busy(True, "Analyzing desktop...", mode="indeterminate")
def worker() -> None:
try:
organizer = DesktopOrganizer(desktop_path)
items = organizer.scan(include_folders=include_folders)
except Exception as exc:
self.progress_queue.put(("desktop_analysis_error", exc))
else:
self.progress_queue.put(("desktop_analysis_done", desktop_path, items))
self.organizer_thread = threading.Thread(target=worker, daemon=True)
self.organizer_thread.start()
def _clear_desktop_tree(self) -> None:
for row in self.desktop_tree.get_children():
self.desktop_tree.delete(row)
def _render_desktop_items(self, items: list[DesktopItem]) -> None:
self._clear_desktop_tree()
for index, item in enumerate(items):
self.desktop_tree.insert(
"",
END,
iid=str(index),
values=(
item.path.name,
item.category,
item.kind,
human_size(item.size),
str(item.target.parent),
item.note,
),
)
categories: dict[str, int] = {}
total_size = 0
for item in items:
categories[item.category] = categories.get(item.category, 0) + 1
total_size += item.size
if items:
category_text = ", ".join(f"{name}: {count}" for name, count in sorted(categories.items()))
self.summary_label.configure(
text=f"{len(items)} movable items found ({human_size(total_size)}).\n\n{category_text}"
)
self.status_var.set("Analysis complete. Select rows to organize a subset, or organize all.")
else:
self.summary_label.configure(text="No movable desktop items found with the current settings.")
self.status_var.set("No movable items found.")
def _set_organizer_busy(
self,
busy: bool,
message: str = "",
mode: str = "determinate",
maximum: int = 100,
) -> None:
self.organizer_busy = busy
state = DISABLED if busy else NORMAL
for control in (
self.browse_button,
self.analyze_button,
self.include_folders_check,
self.organize_selected_button,
self.organize_all_button,
self.undo_button,
):
control.configure(state=state)
self.organizer_progress.stop()
if busy:
self.organizer_progress.configure(mode=mode, maximum=max(1, maximum), value=0)
if mode == "indeterminate":
self.organizer_progress.start(12)
else:
self.organizer_progress.configure(mode="determinate", maximum=100, value=0)
if message:
self.status_var.set(message)
def selected_items(self) -> list[DesktopItem]:
selected = self.desktop_tree.selection()
if not selected:
return []
return [self.desktop_items[int(item_id)] for item_id in selected]
def organize_selected(self) -> None:
items = self.selected_items()
if not items:
messagebox.showinfo(APP_NAME, "Select one or more rows first.")
return
self._organize_items(items)