-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortanything.py
More file actions
2249 lines (1889 loc) · 101 KB
/
sortanything.py
File metadata and controls
2249 lines (1889 loc) · 101 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
#!/usr/bin/env python3
"""
SortAnything Application
A comprehensive GUI tool for manual file and folder sorting with multiple phases.
Dark theme version with optimized code structure.
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, colorchooser
from PIL import Image, ImageTk
import os
import json
import shutil
import fnmatch
from pathlib import Path
import csv
from typing import List, Any, Optional
import subprocess
import sys
from datetime import datetime
import random
# Constants
DARK_COLORS = {
'bg': "#2b2b2b", 'fg': "#ffffff", 'select': "#404040", 'tab': "#858585",
'active': "#505050", 'entry_bg': "#404040", 'success': "#D2ED64", 'danger': "#D2ED64"}
COLOR_PALETTE = [
'#d6a5c9', # muted lavender
'#a6dcef', # soft cyan
'#fbc4ab', # muted peach
'#b5c9b8', # muted sage green
'#f6eac2', # soft cream
'#a8a3d1', # soft periwinkle
'#dbb0b0', # muted rose
'#c5d1d8', # muted blue-gray
'#f2c6b3', # muted coral
'#c3d9c8' # soft green
]
ABOUT_TEXT = """SortAnything v1.0
A versatile tool designed to help you organize files and folders efficiently.
• Interactive file selection with advanced filtering options
• Customizable sorting categories (buckets) for personalized organization
• Keyboard shortcuts to speed up manual sorting
• Options to save sorted lists or physically move files
• Session saving and loading for resuming work later
• Detailed reports on sorting activities
GitHub: [Mohsyn](https://github.com/mohsyn)"""
type_map = {
'image': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp', '.svg'],
'text': ['.txt', '.md', '.py', '.js', '.html', '.css', '.json', '.xml', '.b4a','.b4j','.b4i','.log','.nfo','.java', '.c', '.cpp', '.h', '.hpp', '.cs', '.go', '.rb', '.php', '.swift', '.kt', '.kts'],
'documents': ['.pdf','.doc','.docx','.dot','.ppt','.pptx','.xls','.xlsx','.xlsm','.xlst', '.csv', '.odt', '.ods', '.odp'],
'compressed': ['.zip', '.rar', '.tar', '.gzip', '.iso', '.7z', '.arc', '.lhz', '.gz'],
'video': ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm'],
'audio': ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.wma'],
'executable': ['.exe', '.msi', '.deb', '.rpm', '.dmg', '.app', '.bat', '.sh', '.cmd', '.com', '.run'],
'font': ['.ttf', '.otf', '.woff', '.woff2'],
'database': ['.db', '.sqlite', '.sqlite3', '.sql', '.accdb', '.mdb'],
'ebook': ['.epub', '.mobi', '.azw', '.azw3'],
'virtualization': ['.vdi', '.vmdk', '.ova', '.ovf'],
'configuration': ['.ini', '.cfg', '.conf', '.yml', '.yaml', '.toml'],
'script': ['.ps1', '.vbs', '.sh', '.bash', '.zsh', '.bat', '.cmd'],
'system': ['.dll', '.sys', '.drv',]
}
def get_random_color(): return random.choice(COLOR_PALETTE)
def configure_dark_theme(root):
"""Configure dark theme for the application."""
style = ttk.Style()
style.theme_use('clam')
# Configure all ttk styles at once
configs = {
'TNotebook': {'background': DARK_COLORS['bg'], 'borderwidth': 0},
'TNotebook.Tab': {'background': DARK_COLORS['bg'], 'foreground': DARK_COLORS['fg'], 'padding': (8,8), 'borderwidth': 1, 'font': ('Arial', 10, 'normal')},
'TFrame': {'background': DARK_COLORS['bg'], 'borderwidth': 0},
'TLabelframe': {'background': DARK_COLORS['bg'], 'foreground': DARK_COLORS['fg'], 'borderwidth': 1},
'TLabelframe.Label': {'background': DARK_COLORS['bg'], 'foreground': DARK_COLORS['fg']},
'TLabel': {'background': DARK_COLORS['bg'], 'foreground': DARK_COLORS['fg']},
'TButton': {'background': DARK_COLORS['select'], 'foreground': DARK_COLORS['fg'], 'borderwidth': 1},
'TEntry': {'background': DARK_COLORS['active'], 'foreground': DARK_COLORS['fg'], 'fieldbackground': DARK_COLORS['entry_bg'], 'borderwidth': 1, 'font': ('Arial', 12)},
'TCheckbutton': {'background': DARK_COLORS['bg'], 'foreground': DARK_COLORS['fg'], 'borderwidth': 0},
'TRadiobutton': {'background': DARK_COLORS['bg'], 'foreground': DARK_COLORS['fg'], 'borderwidth': 0},
'TProgressbar': {'background': DARK_COLORS['success'], 'borderwidth': 0},
'Treeview': {'background': DARK_COLORS['entry_bg'], 'foreground': DARK_COLORS['fg'], 'fieldbackground': DARK_COLORS['entry_bg'], 'borderwidth': 0, 'font': ('Arial', 12)},
'Treeview.Heading': {'background': DARK_COLORS['select'], 'foreground': DARK_COLORS['fg'], 'borderwidth': 1},
'Vertical.TScrollbar': {'background': DARK_COLORS['select'], 'borderwidth': 0, 'arrowcolor': DARK_COLORS['fg'], 'troughcolor': DARK_COLORS['bg']},
'Horizontal.TScrollbar': {'background': DARK_COLORS['select'], 'borderwidth': 0, 'arrowcolor': DARK_COLORS['fg'], 'troughcolor': DARK_COLORS['bg']} }
for widget, config in configs.items():
style.configure(widget, **config)
# Nav buttons
style.configure('Nav.TButton', font=('Arial', 14, 'bold'), padding=(6, 4), borderwidth=0)
style.map('TNotebook.Tab',
background=[('selected', DARK_COLORS['select']), ('active', DARK_COLORS['select'])],
foreground=[('selected', DARK_COLORS['fg'])],
#borderwidth=[('selected', 3),('active', 6)],
font=[('selected', ("Segoe UI", 12, "bold"))],
padding=[('selected', (10, 8))])
style.map('TButton', background=[('active', DARK_COLORS['active'])])
style.map('Treeview', background=[('selected', DARK_COLORS['active'])])
# Ensure checkbutton text remains visible on hover/active
style.map('TCheckbutton',
foreground=[('active', DARK_COLORS['fg']), ('selected', DARK_COLORS['fg'])],
background=[('active', DARK_COLORS['bg']), ('selected', DARK_COLORS['bg'])])
# Ensure radiobutton text remains visible on hover/active
style.map('TRadiobutton',
foreground=[('active', DARK_COLORS['fg']), ('selected', DARK_COLORS['fg'])],
background=[('active', DARK_COLORS['bg']), ('selected', DARK_COLORS['bg'])])
# Ensure treeview headings remain visible on hover/active
style.map('Treeview.Heading',
foreground=[('active', DARK_COLORS['fg']), ('selected', DARK_COLORS['fg'])],
background=[('active', DARK_COLORS['select']), ('selected', DARK_COLORS['select'])])
root.configure(bg=DARK_COLORS['bg'])
class FileItem:
def __init__(self, path):
self.name = path
self.path = path
self.is_file = False
self.size = 0
self.modified = datetime.now()
self.extension = ""
self.selected = False
self.bucket = None
self.attributes = {}
self.skipped = False
self._populate_metadata()
def _populate_metadata(self):
"""Populate metadata from actual file if path exists."""
try:
path = Path(self.path)
if path.exists():
self.name = path.name
self.is_file = path.is_file()
if self.is_file:
self.size = path.stat().st_size
self.extension = path.suffix.lower()
self.modified = datetime.fromtimestamp(path.stat().st_mtime)
except (OSError, PermissionError, ValueError):
pass
def __str__(self):
return f"{self.name} ({self.size} bytes, {self.modified.strftime('%Y-%m-%d %H:%M')})"
class Bucket:
"""Represents a sorting bucket."""
def __init__(self, number: int, name: str = "", color: Optional[str] = None):
self.number = number
self.name = name or f"Bucket {number}"
self.color = color or get_random_color()
self.items: List[FileItem] = []
self.hotkey = str(number) if number < 10 else "0"
class FileSorterApp:
"""Main application class for the SortAnything."""
def __init__(self, root):
self.root = root
self.root.title("SortAnything")
self.root.geometry("1200x800")
configure_dark_theme(root)
# Application state
self.current_phase = 1
self.files: List[FileItem] = []
self.buckets: List[Bucket] = []
self.current_file_index = 0
self.output_mode = "list"
self.output_directory = ""
self.session_data = {}
self.list_mode = False
self.current_list_items = []
self.csv_headers = None
self.current_columns = []
self.columns_mode = 'folder'
self._detail_value_labels = []
self.bucket_button_map = {}
self.bucket_indicator_map = {}
self._preview_images = []
self._resizing_image = False # Flag to prevent recursive resizes
self._current_image_dimensions = None
# Create main notebook
self.notebook = ttk.Notebook(root)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Initialize phases
self.init_phase1()
self.init_phase2()
self.init_phase3()
self.init_phase4()
# Bind hotkeys
self.root.bind('<KeyPress>', self.handle_hotkey)
self.root.focus_set()
# Focus skip button when entering sorting tab
self.notebook.bind('<<NotebookTabChanged>>', self._on_tab_change)
def _on_tab_change(self, event=None):
try:
if self.notebook.index(self.notebook.select()) == 2 and hasattr(self, 'skip_btn'):
self.skip_btn.focus_set()
except Exception:
pass
def create_button_frame(self, parent, buttons):
"""Helper to create standardized button frames."""
frame = ttk.Frame(parent)
frame.pack(fill=tk.X, padx=5, pady=5)
for i, (text, command, side) in enumerate(buttons):
if text == "SEPARATOR":
continue
btn_config = {'text': text, 'command': command}
if text in ["Proceed to Configuration", "Start Sorting", "Complete Sorting"]:
btn = tk.Button(frame, bg=DARK_COLORS['success'], fg="black",
activebackground="#45a049", font=('Arial', 10, 'bold'), **btn_config)
else:
btn = ttk.Button(frame, **btn_config)
btn.pack(side=side, padx=2)
return frame
# Replace your helper with this version
def create_tree_with_scrollbars(self, parent, columns, show='headings',
need_v=True, need_h=True, auto_hide_h=True):
frame = ttk.Frame(parent)
tree = ttk.Treeview(frame, columns=columns, show=show)
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
v_scroll = None
h_scroll = None
if need_v:
v_scroll = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=tree.yview)
tree.configure(yscrollcommand=v_scroll.set)
v_scroll.pack(side=tk.RIGHT, fill=tk.Y)
if need_h and not auto_hide_h:
h_scroll = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
tree.configure(xscrollcommand=h_scroll.set)
h_scroll.pack(side=tk.BOTTOM, fill=tk.X)
if need_h and auto_hide_h:
h_scroll = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=tree.xview)
# Don't pack initially - only pack when needed
tree.configure(xscrollcommand=h_scroll.set)
def toggle_hscroll(event=None):
try:
tree.update_idletasks()
total_width = sum(int(tree.column(c, 'width')) for c in columns)
needs_scroll = total_width > int(tree.winfo_width())
except Exception:
needs_scroll = False
mapped = h_scroll.winfo_ismapped()
if needs_scroll and not mapped:
h_scroll.pack(side=tk.BOTTOM, fill=tk.X)
elif not needs_scroll and mapped:
h_scroll.pack_forget()
tree.bind('<Configure>', toggle_hscroll)
frame.after(50, toggle_hscroll)
return frame, tree
def init_phase1(self):
"""Initialize Phase 1: Input Selection Interface."""
self.phase1_frame = ttk.Frame(self.notebook)
self.notebook.add(self.phase1_frame, text="1. Input Selection")
main_frame = ttk.PanedWindow(self.phase1_frame, orient=tk.HORIZONTAL)
main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Left panel
left_frame = ttk.Frame(main_frame)
main_frame.add(left_frame, weight=1)
ttk.Label(left_frame, text="Input Mode", font=('Arial', 12, 'bold')).pack(pady=5)
# Mode selection
mode_frame = ttk.Frame(left_frame)
mode_frame.pack(fill=tk.X, padx=5, pady=5)
self.input_mode_var = tk.StringVar(value="folder")
rb_folder = ttk.Radiobutton(mode_frame, text="Folder Mode", variable=self.input_mode_var,
value="folder", command=self.toggle_input_mode)
rb_folder.pack(side=tk.LEFT, anchor=tk.W, padx=(0, 10))
self._add_tooltip(rb_folder, "Select if you want to organize files into folders")
rb_list = ttk.Radiobutton(mode_frame, text="List Mode", variable=self.input_mode_var,
value="list", command=self.toggle_input_mode)
rb_list.pack(side=tk.LEFT, anchor=tk.W, padx=(0, 10))
self._add_tooltip(rb_list, "Select this if you want to sort list from csv/text/clipboard")
# Folder controls
self.folder_controls = ttk.Frame(left_frame)
self.folder_controls.pack(fill=tk.BOTH, expand=True)
btn_frame_1 = self.create_button_frame(self.folder_controls, [])
add_dir_btn = ttk.Button(btn_frame_1, width=15, text="Add Directory", command=self._add_directory)
add_dir_btn.pack(side=tk.LEFT, padx=2, pady=20)
self._add_tooltip(add_dir_btn, "Browse for and add a folder to the list of sources")
remove_dir_btn = ttk.Button(btn_frame_1,width=20, text="Remove Selected", command=self.remove_directory)
remove_dir_btn.pack(side=tk.LEFT, padx=20)
self._add_tooltip(remove_dir_btn, "Removes the selected folder(s) from list below")
# Create listbox with scrollbar
listbox_frame = ttk.Frame(self.folder_controls)
listbox_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
self.dir_listbox = tk.Listbox(listbox_frame, selectmode=tk.MULTIPLE,
bg=DARK_COLORS['entry_bg'], fg='white',
selectbackground=DARK_COLORS['active'], font=('Arial', 12))
self.dir_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Add vertical scrollbar
listbox_scrollbar = ttk.Scrollbar(listbox_frame, orient=tk.VERTICAL, command=self.dir_listbox.yview)
self.dir_listbox.configure(yscrollcommand=listbox_scrollbar.set)
listbox_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.dir_listbox.bind('<<ListboxSelect>>', self.on_dir_select)
# List controls
self.list_controls = ttk.Frame(left_frame)
list_buttons = [
("Import from Clipboard", self.paste_from_clipboard, tk.TOP),
("Import CSV", self.import_csv, tk.TOP),
("Import Text", self.import_text, tk.TOP)
]
list_btn_frame = ttk.Frame(self.list_controls)
list_btn_frame.pack(fill=tk.Y, padx=5, pady=5)
btn_clipboard = ttk.Button(list_btn_frame, text="From Clipboard", command=self.paste_from_clipboard)
btn_clipboard.pack(fill=tk.X, pady=22)
self._add_tooltip(btn_clipboard, "Import a list of items by pasting from the clipboard")
btn_csv = ttk.Button(list_btn_frame, text="Import CSV", command=self.import_csv)
btn_csv.pack(fill=tk.X, pady=12)
self._add_tooltip(btn_csv, "Import items from a CSV file (First row will be used as headers)")
btn_text = ttk.Button(list_btn_frame, text="Import Text", command=self.import_text)
btn_text.pack(fill=tk.X, pady=12)
self._add_tooltip(btn_text, "Import items from a text file (one item per line)")
# Right panel
right_frame = ttk.Frame(main_frame)
main_frame.add(right_frame, weight=2)
ttk.Label(right_frame, text="Items", font=('Arial', 12, 'bold')).pack(pady=5)
# Filter controls
filter_frame = ttk.Frame(right_frame)
filter_frame.pack(fill=tk.X, padx=5, pady=5)
ttk.Label(filter_frame, text="Filter:").pack(side=tk.LEFT)
self.filter_var = tk.StringVar(value="*")
self.filter_var.trace('w', self.apply_filter)
filter_entry = ttk.Entry(filter_frame, textvariable=self.filter_var, font=('Arial', 16), width=16)
filter_entry.pack(side=tk.LEFT, padx=5)
btn_select_matching = ttk.Button(filter_frame, text="Select Matching", command=self.select_matching)
btn_select_matching.pack(side=tk.LEFT, padx=5)
self._add_tooltip(btn_select_matching, "Select all items that match the filter (wildcards supported)")
btn_clear_selection = ttk.Button(filter_frame, text="Clear Selection", command=self.clear_selection)
btn_clear_selection.pack(side=tk.LEFT, padx=5)
self._add_tooltip(btn_clear_selection, "Deselect all currently selected items.")
btn_clear_all = ttk.Button(filter_frame, text="Clear All", command=self.clear_all_action)
btn_clear_all.pack(side=tk.LEFT, padx=5)
self._add_tooltip(btn_clear_all, "Remove all items from the list below while retaining sources")
btn_refresh = ttk.Button(filter_frame, text="Refresh", command=self.refresh_button_action)
btn_refresh.pack(side=tk.LEFT, padx=5)
self._add_tooltip(btn_refresh, "Refresh list to show changes made to selection")
self.show_selected_only = tk.BooleanVar()
cb_show_selected = ttk.Checkbutton(filter_frame, text="Show Selected Only",
variable=self.show_selected_only, command=self.toggle_show_selected)
cb_show_selected.pack(side=tk.LEFT, padx=5)
self._add_tooltip(cb_show_selected, "Toggle to show only the items that are currently selected")
# Item tree
item_tree_frame, self.item_tree = self.create_tree_with_scrollbars(
right_frame, ('checkbox', 'Filename', 'Size', 'Modified', 'Type'))
item_tree_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Configure tree columns
col_configs = {
'checkbox': {'text': '✓', 'width': 40, 'stretch': False, 'anchor': 'center'},
'Filename': {'text': 'Filename', 'width': 300, 'stretch': True, 'anchor': 'w'},
'Size': {'text': 'Size', 'width': 100, 'stretch': False},
'Modified': {'text': 'Modified', 'width': 150, 'stretch': False},
'Type': {'text': 'Type', 'width': 80, 'stretch': False}
}
for col, config in col_configs.items():
self.item_tree.heading(col, text=config['text'], anchor=config.get('anchor', 'w'))
self.item_tree.column(col, width=config['width'], stretch=config['stretch'])
self.item_tree.column('#0', width=0, stretch=tk.NO)
self.item_tree.bind('<Button-1>', self.toggle_item_selection)
# Bottom controls
bottom_frame = ttk.Frame(right_frame)
bottom_frame.pack(fill=tk.X, padx=5, pady=5)
self.selection_label = ttk.Label(bottom_frame, text="0 of 0 items selected")
self.selection_label.pack(side=tk.LEFT)
btn_proceed1 = tk.Button(bottom_frame, text="Proceed to Configuration", command=self.proceed_to_phase2,
bg=DARK_COLORS['success'], fg="black", activebackground="#45a049",
font=('Arial', 10, 'bold'))
btn_proceed1.pack(side=tk.RIGHT, padx=2)
self._add_tooltip(btn_proceed1, "Continue to the next step to configure sorting buckets.")
self.list_controls.pack_forget()
def _add_directory(self):
"""Add a directory to the selection list."""
directory = filedialog.askdirectory(title="Select Directory to Sort")
if directory and directory not in self.dir_listbox.get(0, tk.END):
self.dir_listbox.insert(tk.END, directory)
self.refresh_items()
def remove_directory(self):
"""Remove selected directories from the list."""
for index in reversed(self.dir_listbox.curselection()):
self.dir_listbox.delete(index)
self.refresh_items()
def configure_item_tree_columns(self, columns, headers_mapping=None):
"""Configure the item tree columns dynamically."""
self.current_columns = columns
self.item_tree.configure(columns=columns, show='headings')
self.item_tree.column('#0', width=0, stretch=tk.NO)
for col in columns:
if col == 'checkbox':
self.item_tree.heading('checkbox', text='✓', anchor='center')
self.item_tree.column('checkbox', width=40, stretch=tk.NO, anchor='center')
else:
label = headers_mapping.get(col, col) if headers_mapping else col
self.item_tree.heading(col, text=label, anchor='w')
width = 300 if col in ('Filename', 'Item') else 150 if col == 'Modified' else 100
self.item_tree.column(col, width=width, stretch=tk.YES)
def toggle_input_mode(self):
"""Switch between folder mode and list mode."""
# Warn if there is existing data
has_data = bool(self.dir_listbox.size()) or bool(self.files)
if has_data:
if not messagebox.askyesno("Switch Mode",
"Switching modes will reset current data and sorting. Continue?"):
# Revert selection
self.input_mode_var.set('list' if self.input_mode_var.get() == 'folder' else 'folder')
return
# Reset all
for bucket in self.buckets:
bucket.items.clear()
self.buckets.clear()
self.files.clear()
self.dir_listbox.delete(0, tk.END)
self.current_file_index = 0
if self.input_mode_var.get() == "folder":
self.folder_controls.pack(fill=tk.BOTH, expand=True)
self.list_controls.pack_forget()
else:
self.folder_controls.pack_forget()
self.list_controls.pack(fill=tk.BOTH, expand=True)
self.refresh_display()
def paste_from_clipboard(self):
"""Paste items from clipboard."""
try:
content = self.root.clipboard_get()
lines = [line.strip() for line in content.strip().split('\n') if line.strip()]
self.csv_headers = None
self.files.clear()
for line in lines:
file_item = FileItem(line)
file_item.name = line
file_item.is_file = False
self.files.append(file_item)
self.columns_mode = 'list'
self.configure_item_tree_columns(['checkbox', 'Item'])
self.refresh_display()
except Exception as e:
messagebox.showerror("Error", f"Failed to paste from clipboard: {e}")
def import_csv(self):
"""Import CSV file containing items."""
filename = filedialog.askopenfilename(
title="Select CSV File", filetypes=[("CSV files", "*.csv")])
if not filename:
return
try:
with open(filename, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
headers = [h.strip() for h in next(reader)]
self.csv_headers = headers
self.files.clear()
for row in reader:
if not row:
continue
first_val = row[0].strip() if len(row) > 0 else ""
file_item = FileItem(first_val)
file_item.name = first_val
file_item.is_file = False
for i, header in enumerate(self.csv_headers):
value = row[i].strip() if i < len(row) else ""
if header:
file_item.attributes[header] = value
self.files.append(file_item)
self.columns_mode = 'list'
self.configure_item_tree_columns(['checkbox'] + self.csv_headers)
self.refresh_display()
except Exception as e:
messagebox.showerror("Error", f"Failed to import CSV: {e}")
def import_text(self):
"""Import plain text file where each line represents an item."""
filename = filedialog.askopenfilename(
title="Select Text File", filetypes=[("Text files", "*.txt *.text")])
if not filename:
return
try:
with open(filename, 'r', encoding='utf-8') as f:
lines = [line.strip() for line in f.readlines() if line.strip()]
self.csv_headers = None
self.files.clear()
for line in lines:
file_item = FileItem(line)
file_item.name = line
file_item.is_file = False
self.files.append(file_item)
self.configure_item_tree_columns(['checkbox', 'Item'])
self.columns_mode = 'list'
self.refresh_display()
except Exception as e:
messagebox.showerror("Error", f"Failed to import text file: {e}")
def get_filtered_items(self):
"""Get items matching the current filter."""
filter_pattern = self.filter_var.get().strip()
if not filter_pattern:
return self.files
return [f for f in self.files if fnmatch.fnmatch(f.name.lower(), filter_pattern.lower())]
def refresh_display(self):
"""Refresh the item tree display."""
for item_id in self.item_tree.get_children():
self.item_tree.delete(item_id)
filtered_items = self.get_filtered_items()
# Configure columns based on current mode
if self.columns_mode == 'list':
expected_cols = ['checkbox'] + (self.csv_headers if self.csv_headers else ['Item'])
else:
expected_cols = ['checkbox', 'Filename', 'Size', 'Modified', 'Type']
if getattr(self, 'current_columns', []) != expected_cols:
self.configure_item_tree_columns(expected_cols, {'checkbox': '✓'} if self.columns_mode != 'list' else None)
# Populate rows
for file_item in filtered_items:
if self.show_selected_only.get() and not file_item.selected:
continue
checkbox_symbol = "✓" if file_item.selected else ""
if self.input_mode_var.get() == 'list':
if self.csv_headers:
row_values = [checkbox_symbol] + [file_item.attributes.get(h, "") for h in self.csv_headers]
else:
row_values = [checkbox_symbol, file_item.name]
else:
size_str = f"{file_item.size:,} bytes" if file_item.is_file else "N/A"
modified_str = file_item.modified.strftime("%Y-%m-%d %H:%M")
type_str = self._get_file_type(file_item)
row_values = [checkbox_symbol, file_item.name, size_str, modified_str, type_str]
self.item_tree.insert('', 'end', values=row_values,
tags=('selected' if file_item.selected else 'unselected'))
self.item_tree.tag_configure('selected', background=DARK_COLORS['active'])
# Update selection counter
selected_count = sum(1 for f in self.files if f.selected)
total_count = len(filtered_items)
self.selection_label.config(text=f"{selected_count} of {total_count} items selected")
def _get_file_type(self, file_item):
"""Determine file type display string."""
if not file_item.is_file:
return "Folder"
for type_name, extensions in type_map.items():
if file_item.extension in extensions:
return type_name.title()
return file_item.extension.upper().replace('.', '') + " File" if file_item.extension else "File"
def on_dir_select(self, event=None):
"""Handle directory selection change."""
self.refresh_items()
def toggle_item_selection(self, event):
"""Toggle item selection when clicked."""
item = self.item_tree.selection()[0] if self.item_tree.selection() else None
if not item:
return
values = self.item_tree.item(item, 'values')
if not values or len(values) < 2:
return
key_value = values[1]
if self.input_mode_var.get() == 'folder':
match_fn = lambda fi: fi.name == key_value
else:
if self.csv_headers:
first_col = self.csv_headers[0]
match_fn = lambda fi: fi.attributes.get(first_col, fi.name) == key_value
else:
match_fn = lambda fi: fi.name == key_value
for file_item in self.files:
if match_fn(file_item):
file_item.selected = not file_item.selected
break
self.refresh_display()
def proceed_to_phase2(self):
"""Move to Phase 2: Bucket Configuration."""
selected_items = [f for f in self.files if f.selected]
if not selected_items:
messagebox.showwarning("No Selection", "Please select at least one item to sort.")
return
self.output_mode_var.set('folder' if self.input_mode_var.get() == 'folder' else 'list')
self.on_output_mode_change()
self.notebook.select(1)
def refresh_items(self):
"""Refresh the item list based on selected directories."""
# Preserve current selections by path
previously_selected_paths = {str(f.path) for f in self.files if getattr(f, 'selected', False)}
self.files.clear()
for directory in self.dir_listbox.get(0, tk.END):
try:
path = Path(directory)
if path.exists() and path.is_dir():
for item in path.iterdir():
if not item.name.startswith('.'):
fi = FileItem(str(item))
if str(fi.path) in previously_selected_paths:
fi.selected = True
self.files.append(fi)
except PermissionError:
messagebox.showwarning("Permission Error", f"Cannot access directory: {directory}")
self.columns_mode = 'folder'
self.configure_item_tree_columns(['checkbox', 'Filename', 'Size', 'Modified', 'Type'],
headers_mapping={'checkbox': '✓'})
self.refresh_display()
def refresh_button_action(self):
"""Refresh action depending on current mode."""
if self.input_mode_var.get() == 'folder':
self.refresh_items()
else:
self.refresh_display()
def clear_all_action(self):
"""Clear list items and selections, reset filter."""
for f in self.files:
f.selected = False
self.files.clear()
self.filter_var.set("*")
self.show_selected_only.set(False)
self.csv_headers = None
if self.input_mode_var.get() == 'list':
self.configure_item_tree_columns(['checkbox', 'Item'])
self.refresh_display()
def select_matching(self):
"""Select all files matching the current filter."""
filter_pattern = self.filter_var.get().strip()
if filter_pattern:
for file_item in self.files:
if fnmatch.fnmatch(file_item.name.lower(), filter_pattern.lower()):
file_item.selected = True
self.refresh_display()
def clear_selection(self):
"""Clear all file selections."""
for file_item in self.files:
file_item.selected = False
self.refresh_display()
def toggle_show_selected(self):
"""Toggle showing only selected items."""
self.refresh_display()
def apply_filter(self, *args):
"""Apply the current filter to the item display."""
self.refresh_display()
def init_phase2(self):
"""Initialize Phase 2: Bucket Configuration."""
self.phase2_frame = ttk.Frame(self.notebook)
self.notebook.add(self.phase2_frame, text="2. Bucket Configuration")
main_frame = ttk.Frame(self.phase2_frame)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
ttk.Label(main_frame, text="Customize your Buckets (Collections / Categories / Types / Folders)", font=('Arial', 14, 'bold')).pack(pady=10)
# Header with add button
header_frame = ttk.Frame(main_frame)
header_frame.pack(fill=tk.X, pady=5)
btn_add_bucket = ttk.Button(header_frame, text="Add New Bucket", command=self.add_new_bucket)
btn_add_bucket.pack(side=tk.LEFT, padx=10)
self._add_tooltip(btn_add_bucket, "Add a new category/folder to sort items into (max 10).")
btn_reset_buckets = ttk.Button(header_frame, text="Reset All", command=self.reset_all_buckets)
btn_reset_buckets.pack(side=tk.LEFT, padx=(10, 0))
self._add_tooltip(btn_reset_buckets, "Remove all custom buckets and restore the defaults.")
# Scrollable bucket config
canvas = tk.Canvas(main_frame, bg=DARK_COLORS['bg'], highlightthickness=0)
scrollbar = ttk.Scrollbar(main_frame, orient="vertical", command=canvas.yview)
self.bucket_config_frame = ttk.Frame(canvas)
self.bucket_config_frame.bind("<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=self.bucket_config_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# Output mode selection
mode_frame = ttk.Frame(main_frame, width=50)
mode_frame.pack(fill=tk.X, pady=10)
ttk.Label(mode_frame, text="Output Mode:").pack(side=tk.LEFT)
self.output_mode_var = tk.StringVar(value="list")
rb_list_out = ttk.Radiobutton(mode_frame, text="List Mode", variable=self.output_mode_var,
value="list", command=self.on_output_mode_change)
rb_list_out.pack(side=tk.LEFT, padx=10)
self._add_tooltip(rb_list_out, "Output the sorting results as a file (e.g., CSV, JSON).")
rb_folder_out = ttk.Radiobutton(mode_frame, text="Folder Mode (Move Files)", variable=self.output_mode_var,
value="folder", command=self.on_output_mode_change)
rb_folder_out.pack(side=tk.LEFT, padx=10)
self._add_tooltip(rb_folder_out, "Use this mode if you want to work with files and move them into folders")
# Output directory selection (for folder mode)
self.output_frame = ttk.Frame(main_frame)
self.output_label = ttk.Label(self.output_frame, text="Output Directory:")
self.output_label.pack(side=tk.LEFT)
self.output_dir_var = tk.StringVar()
self.output_entry = ttk.Entry(self.output_frame, textvariable=self.output_dir_var, width=50)
self.output_entry.pack(side=tk.LEFT, padx=5)
self.output_browse_btn = ttk.Button(self.output_frame, text="Browse", command=self.browse_output_directory)
self.output_browse_btn.pack(side=tk.LEFT, padx=2)
self._add_tooltip(self.output_browse_btn, "Select Output folder where files will be moved (create folders yourself)")
# Always pack the frame to maintain consistent layout
self.output_frame.pack(fill=tk.X, pady=10)
self.update_bucket_config()
self.add_new_bucket() # Add second default bucket
# Bottom buttons (keep a handle to ensure order relative to output_frame)
self.phase2_buttons_frame = ttk.Frame(main_frame)
self.phase2_buttons_frame.pack(fill=tk.X, padx=5, pady=5)
# Set initial state based on output mode
self.on_output_mode_change()
btn_back1 = ttk.Button(self.phase2_buttons_frame, text="Back to selection", command=self.back_to_phase1)
btn_back1.pack(side=tk.LEFT, padx=2)
self._add_tooltip(btn_back1, "Return to the previous step to change item selection.")
btn_start_sorting = tk.Button(self.phase2_buttons_frame, text="Start Sorting", command=self.proceed_to_phase3, bg=DARK_COLORS['success'], fg="black", activebackground="#45a049", font=('Arial', 10, 'bold'))
btn_start_sorting.pack(side=tk.RIGHT, padx=2)
self._add_tooltip(btn_start_sorting, "Proceed to the next step to begin sorting the selected items.")
def init_phase3(self):
"""Initialize Phase 3: Interactive Sorting."""
self.phase3_frame = ttk.Frame(self.notebook)
self.notebook.add(self.phase3_frame, text="3. Interactive Sorting")
main_frame = ttk.Frame(self.phase3_frame)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
self.progress_var = tk.DoubleVar()
item_display_frame = ttk.Frame(main_frame)
item_display_frame.pack(fill=tk.BOTH, expand=True, pady=15)
self.current_filename_label = ttk.Label(item_display_frame, text="",
font=('Arial', 20, 'bold'),
anchor='center', wraplength=1000)
self.current_filename_label.pack(pady=12, ipady=8, fill=tk.X)
self.side_by_side_frame = tk.PanedWindow(item_display_frame, orient=tk.HORIZONTAL,sashwidth=2, sashrelief='flat')
self.side_by_side_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
self.info_frame = ttk.LabelFrame(self.side_by_side_frame, text=" File Information")
self.side_by_side_frame.add(self.info_frame, width=400)
# Details Treeview
self.details_tree = ttk.Treeview(self.info_frame, columns=('Property', 'Value'), show='headings')
self.details_tree.heading('Property', text='Property')
self.details_tree.heading('Value', text='Value')
self.details_tree.column('Property', width=100, stretch=False)
self.details_tree.column('Value', width=120, stretch=True)
self.details_tree.pack(pady=4, padx=4, fill=tk.BOTH, expand=True)
self.preview_frame = ttk.LabelFrame(self.side_by_side_frame, text=" Preview (Click to Open)")
self.side_by_side_frame.add(self.preview_frame)
self.preview_label = ttk.Label(self.preview_frame, text="No preview available", anchor='center' , cursor="hand2")
self.preview_label.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
self.preview_label.bind("<Button-1>", self.on_preview_click)
self.preview_frame.pack_propagate(False)
self.bucket_buttons_frame = ttk.Frame(main_frame)
self.bucket_buttons_frame.pack(pady=10)
nav_frame = ttk.Frame(main_frame)
nav_frame.pack(fill=tk.X, pady=5)
self.progress_bar = ttk.Progressbar(nav_frame, variable=self.progress_var, maximum=100, length=300)
self.progress_label = ttk.Label(nav_frame, text="Ready to sort...")
# Navigation with icon-like labels and tooltips
self.first_btn = ttk.Button(nav_frame, text="⏮", width=4, style='Nav.TButton', command=lambda: self._jump_to_item(0))
self.prev_btn = ttk.Button(nav_frame, text="⏪", width=4, style='Nav.TButton', command=self.previous_file)
self.skip_btn = ttk.Button(nav_frame, text=">>", width=4, style='Nav.TButton', command=self.skip_file)
self.next_btn = ttk.Button(nav_frame, text="⏩", width=4, style='Nav.TButton', command=self.next_file)
self.last_btn = ttk.Button(nav_frame, text="⏭", width=4, style='Nav.TButton', command=lambda: self._jump_to_item(-1))
self.save_btn = ttk.Button(nav_frame, text="💾", width=4, style='Nav.TButton', command=self.pause_sorting)
self.complete_btn = tk.Button(nav_frame, text="Complete Sorting", command=self.proceed_to_phase4,
bg=DARK_COLORS['success'], fg="black", activebackground="#45a049", font=('Arial', 10, 'bold'))
for btn in [self.first_btn, self.prev_btn, self.skip_btn, self.next_btn, self.last_btn]:
btn.pack(side=tk.LEFT, padx=3)
self.save_btn.pack(side=tk.LEFT, padx=3, pady=1)
self.complete_btn.pack(side=tk.RIGHT, padx=5)
self._add_tooltip(self.complete_btn, "Finish sorting and proceed to the final review step.")
# Skip sorted checkbox
self.skip_sorted_var = tk.BooleanVar(value=False)
skip_sorted_cb = ttk.Checkbutton(nav_frame, text="Skip Sorted",
variable=self.skip_sorted_var)
skip_sorted_cb.pack(side=tk.LEFT, pady=5, padx=8)
self._add_tooltip(skip_sorted_cb, "Skip items already sorted or skipped")
# Place progress bar and label in nav_frame
self.progress_bar.pack(side=tk.LEFT, padx=5)
self.progress_label.pack(side=tk.LEFT, padx=8)
# Progress bar and label already packed earlier
discard_btn = tk.Button(nav_frame, text="Discard Sorting", bg=DARK_COLORS['danger'], fg="black",
activebackground="#d32f2f", font=('Arial', 10, 'bold'), command=self.discard_sorting)
discard_btn.pack(side=tk.RIGHT, padx=5)
self._add_tooltip(discard_btn, "Reset all sorting progress for the current session.")
self.add_new_bucket()
# Tooltips
self._add_tooltip(self.first_btn, "First item")
self._add_tooltip(self.prev_btn, "Previous item")
self._add_tooltip(self.skip_btn, "Skip: Mark item as skipped")
self._add_tooltip(self.next_btn, "Next item")
self._add_tooltip(self.last_btn, "Last item")
self._add_tooltip(self.save_btn, "Save current progress")
def init_phase4(self):
"""Initialize Phase 4: Review and Finalization."""
self.phase4_frame = ttk.Frame(self.notebook)
self.notebook.add(self.phase4_frame, text="4. Review & Finalize")
main_frame = ttk.Frame(self.phase4_frame)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# ttk.Label(main_frame, text="Review and Finalization", font=('Arial', 14, 'bold')).pack(pady=10)
# Bucket review area
self.review_notebook = ttk.Notebook(main_frame)
self.review_notebook.pack(fill=tk.BOTH, expand=True, pady=10)
# Statistics frame
stats_frame = ttk.LabelFrame(main_frame, text="Statistics")
stats_frame.pack(fill=tk.X, pady=10)
self.stats_label = ttk.Label(stats_frame, text="Sorting not over")
self.stats_label.pack(pady=10)
# Final action buttons
self.phase4_action_frame = ttk.Frame(main_frame)
self.phase4_action_frame.pack(fill=tk.X, pady=10)
btn_export = ttk.Button(self.phase4_action_frame, text="Export Results", command=self.export_results)
btn_export.pack(side=tk.LEFT, padx=5)
self._add_tooltip(btn_export, "Save the sorted lists to a file (JSON, CSV, TXT, HTML).")
btn_save_session = ttk.Button(self.phase4_action_frame, text="Save Session", command=self.save_session)
btn_save_session.pack(side=tk.LEFT, padx=5)
self._add_tooltip(btn_save_session, "Save the entire session (selections, buckets, progress) to a file to resume later.")
btn_refresh_review = ttk.Button(self.phase4_action_frame, text="Refresh", command=self.refresh_review)
btn_refresh_review.pack(side=tk.LEFT, padx=5)
self._add_tooltip(btn_refresh_review, "Update the review tabs with the latest sorting status.")
# Add Discard Sorting button
self.discard_phase4_btn = tk.Button(self.phase4_action_frame, text="Discard Sorting", bg=DARK_COLORS['danger'], fg="black",
activebackground="#d32f2f", font=('Arial', 10, 'bold'), command=self.discard_sorting)
self.discard_phase4_btn.pack(side=tk.RIGHT, padx=10)
self._add_tooltip(self.discard_phase4_btn, "Reset all sorting progress for the current session.")
# Always create Move Files button; control visibility/state later (match style with discard)
self.move_files_btn = tk.Button(self.phase4_action_frame, text="Move Files", command=self.execute_file_moves,
bg=DARK_COLORS['success'], fg="black", activebackground="#45a049", font=('Arial', 10, 'bold'))
self.move_files_btn.pack(side=tk.RIGHT, padx=5)
self._add_tooltip(self.move_files_btn, "Physically move all sorted files to their corresponding bucket folders.")
def handle_hotkey(self, event):
"""Handle hotkey presses for bucket selection and navigation."""
if self.notebook.index(self.notebook.select()) != 2: # Only in sorting phase
return
key_actions = {
'Left': self.previous_file, 'Right': self.next_file,
'Up': lambda: self._jump_to_item(0),
'Down': lambda: self._jump_to_item(-1),
'\x1b': self.previous_file, '\x08': self.previous_file, '\x7f': self.previous_file, # Esc, Backspace, Delete
' ': self.skip_file # Space
}
if event.keysym in key_actions:
key_actions[event.keysym]()
elif event.char.isdigit():
bucket_num = int(event.char) if event.char != '0' else 10
bucket = next((b for b in self.buckets if b.number == bucket_num), None)
if bucket:
self.sort_to_bucket(bucket)
def _jump_to_item(self, index):
"""Jump to specific item index."""
selected_files = [f for f in self.files if f.selected]
if selected_files:
self.current_file_index = index if index >= 0 else len(selected_files) - 1
self.show_current_file()
def previous_file(self):
"""Go back to the previous file."""
if self.current_file_index > 0:
self.current_file_index -= 1
self.show_current_file()
def next_file(self):
"""Go to next file without changing any association."""
selected_files = [f for f in self.files if f.selected]
if self.current_file_index < len(selected_files) - 1:
self.current_file_index += 1
else:
self.current_file_index = len(selected_files)
self.show_current_file()
def skip_file(self):
"""Skip the current file without sorting."""
selected_files = [f for f in self.files if f.selected]
if self.current_file_index < len(selected_files):
current = selected_files[self.current_file_index]
# Remove any existing bucket association
if current.bucket: