-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1538 lines (1271 loc) · 64.2 KB
/
Copy pathmain.py
File metadata and controls
1538 lines (1271 loc) · 64.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tkinter as tk
import customtkinter as ctk
from tkinter import filedialog, messagebox
import logging
from pathlib import Path
from data_manager_enhanced import DataManager
from image_manager import ImageManager, ImageWidget, ImageViewerWindow
from list_screen import ListScreen
# Configure enhanced logging
def setup_logging():
"""Setup comprehensive logging configuration."""
# Create logs directory if it doesn't exist
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
# Configure root logger
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s',
handlers=[
logging.FileHandler(log_dir / 'lineup_debug.log'),
logging.FileHandler(log_dir / 'lineup_info.log', mode='w'),
logging.StreamHandler()
]
)
# Set different levels for different handlers
handlers = logging.getLogger().handlers
if len(handlers) >= 3:
handlers[0].setLevel(logging.DEBUG) # Debug log file
handlers[1].setLevel(logging.INFO) # Info log file
handlers[2].setLevel(logging.WARNING) # Console (warnings and errors only)
# Create application logger
app_logger = logging.getLogger('lineup')
app_logger.setLevel(logging.DEBUG)
return app_logger
# Setup logging
logger = setup_logging()
class LineupApp:
def __init__(self):
# Set appearance mode and color theme
ctk.set_appearance_mode("system") # Modes: system, light, dark
ctk.set_default_color_theme("blue") # Themes: blue, green, dark-blue
# Create main window
self.root = ctk.CTk()
self.root.title("Lineup - Photo Duplicate Manager")
self.root.geometry("1200x800")
self.root.minsize(800, 600)
# Initialize data
self.data_manager = DataManager()
self.image_manager = ImageManager()
self.current_csv_file = None # Track current CSV file for reload
self.current_database_file = None # Track current database file
self.current_group = None
self.selected_images = set()
self.image_widgets = []
self.move_to_directory = None
self.active_image_viewers = [] # Track open image viewers
self.group_buttons = {} # Track group buttons for visual feedback
self.auto_select_enabled = True # Auto-select non-masters by default
self.hide_single_groups = True # Hide groups with 1 or fewer images
self.setup_ui()
logger.info("Lineup application initialized successfully")
logger.debug(f"Window geometry: {self.root.geometry()}")
logger.debug(f"Appearance mode: system, Color theme: blue")
def setup_ui(self):
# Create main frame
self.main_frame = ctk.CTkFrame(self.root)
self.main_frame.pack(fill="both", expand=True, padx=10, pady=10)
# Top toolbar
self.toolbar = ctk.CTkFrame(self.main_frame)
self.toolbar.pack(fill="x", padx=5, pady=5)
# Load CSV button
self.load_btn = ctk.CTkButton(
self.toolbar,
text="Load CSV File",
command=self.load_csv_file,
width=120
)
self.load_btn.pack(side="left", padx=5)
# Database menu
self.database_menu = ctk.CTkOptionMenu(
self.toolbar,
values=["Load Database...", "Browse for Database..."],
command=self.handle_database_selection,
width=140
)
self.database_menu.pack(side="left", padx=5)
self.database_menu.set("Load Database...")
# Initialize recent databases
self.recent_databases = []
self.load_recent_databases()
# Reload button
self.reload_btn = ctk.CTkButton(
self.toolbar,
text="Reload",
command=self.reload_csv_file,
width=80,
state="disabled"
)
self.reload_btn.pack(side="left", padx=5)
# Views dropdown menu
self.views_menu = ctk.CTkOptionMenu(
self.toolbar,
values=["Select View...", "📋 List View", "📊 Statistics", "🔍 Search"],
command=self.handle_view_selection,
width=120,
state="disabled"
)
self.views_menu.pack(side="left", padx=5)
self.views_menu.set("Select View...")
# Status label
self.status_label = ctk.CTkLabel(
self.toolbar,
text="No CSV file loaded"
)
self.status_label.pack(side="left", padx=20)
# Operation status label
self.operation_status_label = ctk.CTkLabel(
self.toolbar,
text="",
font=ctk.CTkFont(size=11, weight="bold"),
text_color="green"
)
self.operation_status_label.pack(side="left", padx=10)
# Move To directory selector
self.moveto_frame = ctk.CTkFrame(self.toolbar)
self.moveto_frame.pack(side="right", padx=5)
# Move To label
self.moveto_label = ctk.CTkLabel(
self.moveto_frame,
text="Move To:",
font=ctk.CTkFont(size=12)
)
self.moveto_label.pack(side="left", padx=(5, 0))
# Selected directory display
self.moveto_display = ctk.CTkLabel(
self.moveto_frame,
text="No directory selected",
font=ctk.CTkFont(size=10),
text_color="gray",
width=200
)
self.moveto_display.pack(side="left", padx=5)
# Browse button for Move To directory
self.moveto_btn = ctk.CTkButton(
self.moveto_frame,
text="Browse...",
command=self.select_move_directory,
width=80
)
self.moveto_btn.pack(side="left", padx=5)
# Clear button for Move To directory
self.moveto_clear_btn = ctk.CTkButton(
self.moveto_frame,
text="Clear",
command=self.clear_move_directory,
width=60
)
self.moveto_clear_btn.pack(side="left", padx=(0, 5))
# Group navigation buttons
self.nav_frame = ctk.CTkFrame(self.toolbar)
self.nav_frame.pack(side="left", padx=20)
self.prev_group_btn = ctk.CTkButton(
self.nav_frame,
text="◀ Previous Group (P)",
command=self.go_to_previous_group,
width=130,
state="disabled"
)
self.prev_group_btn.pack(side="left", padx=2)
self.next_group_btn = ctk.CTkButton(
self.nav_frame,
text="Next Group ▶ (N)",
command=self.go_to_next_group,
width=130,
state="disabled"
)
self.next_group_btn.pack(side="left", padx=2)
# Hide single groups toggle
self.hide_single_switch = ctk.CTkSwitch(
self.toolbar,
text="Hide Single Groups",
command=self.toggle_hide_single_groups
)
self.hide_single_switch.pack(side="right", padx=5)
self.hide_single_switch.select() # Default to enabled
# Auto-select toggle
self.auto_select_switch = ctk.CTkSwitch(
self.toolbar,
text="Auto-select Duplicates",
command=self.toggle_auto_select
)
self.auto_select_switch.pack(side="right", padx=5)
self.auto_select_switch.select() # Default to enabled
# Dark mode toggle
self.dark_mode_switch = ctk.CTkSwitch(
self.toolbar,
text="Dark Mode",
command=self.toggle_dark_mode
)
self.dark_mode_switch.pack(side="right", padx=5)
# Main content area (will be populated when CSV is loaded)
self.content_frame = ctk.CTkFrame(self.main_frame)
self.content_frame.pack(fill="both", expand=True, padx=5, pady=5)
# Welcome message
self.welcome_label = ctk.CTkLabel(
self.content_frame,
text="Welcome to Lineup\n\nLoad a CSV file to begin managing your photo duplicates",
font=ctk.CTkFont(size=16)
)
self.welcome_label.pack(expand=True)
def load_csv_file(self):
logger.debug("Opening CSV file selection dialog")
file_path = filedialog.askopenfilename(
title="Select CSV File",
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
)
if file_path:
try:
logger.info(f"Loading CSV file: {file_path}")
logger.debug(f"File size: {Path(file_path).stat().st_size} bytes")
# Load data using DataManager
if self.data_manager.load_csv(file_path):
self.current_csv_file = file_path # Store for reload functionality
summary = self.data_manager.get_overall_summary()
# Update status
status_text = f"Loaded: {Path(file_path).name} ({summary['total_groups']} groups, {summary['total_images']} images)"
self.status_label.configure(text=status_text)
# Enable reload and list view buttons
self.reload_btn.configure(state="normal")
self.views_menu.configure(state="normal")
logger.info(f"CSV loaded successfully: {summary['total_groups']} groups, {summary['total_images']} images, {summary['missing_images']} missing")
logger.debug(f"Summary: {summary}")
# Update UI
self.setup_content_ui()
# Show warning if there are missing files
if summary['missing_images'] > 0:
logger.warning(f"Found {summary['missing_images']} missing image files")
messagebox.showwarning(
"Missing Files",
f"Warning: {summary['missing_images']} image files could not be found.\n"
f"These will be marked as unavailable."
)
except Exception as e:
logger.error(f"Error loading CSV file: {e}", exc_info=True)
messagebox.showerror("Error", f"Failed to load CSV file:\n{str(e)}")
else:
logger.debug("CSV file selection cancelled by user")
def reload_csv_file(self):
"""Reload the currently loaded CSV file and refresh all screens."""
if not self.current_csv_file:
logger.warning("No CSV file to reload")
messagebox.showwarning("No File", "No CSV file is currently loaded to reload.")
return
try:
logger.info(f"Reloading CSV file: {self.current_csv_file}")
# Check if file still exists
if not Path(self.current_csv_file).exists():
logger.error(f"CSV file no longer exists: {self.current_csv_file}")
messagebox.showerror("File Not Found", f"The CSV file no longer exists:\n{self.current_csv_file}")
return
# Store current group for restoration if possible
previous_group = self.current_group
# Close any active image viewers
for viewer in self.active_image_viewers.copy():
if hasattr(viewer, 'window') and viewer.window.winfo_exists():
viewer.close()
self.active_image_viewers.clear()
# Reload data using DataManager
if self.data_manager.load_csv(self.current_csv_file):
summary = self.data_manager.get_overall_summary()
# Update status
status_text = f"Reloaded: {Path(self.current_csv_file).name} ({summary['total_groups']} groups, {summary['total_images']} images)"
self.status_label.configure(text=status_text)
logger.info(f"CSV reloaded successfully: {summary['total_groups']} groups, {summary['total_images']} images, {summary['missing_images']} missing")
# Update UI
self.setup_content_ui()
# Try to restore previous group selection if it still exists
if previous_group and previous_group in self.data_manager.get_group_list():
# Check if group should be displayed with current filters
group_summary = self.data_manager.get_group_summary(previous_group)
if not (self.hide_single_groups and group_summary['existing_images'] <= 1):
self.select_group(previous_group)
logger.debug(f"Restored selection to group {previous_group}")
else:
logger.debug(f"Previous group {previous_group} now hidden by filters")
# Show operation status
self.show_operation_status("CSV file reloaded successfully", "green")
# Show warning if there are missing files
if summary['missing_images'] > 0:
logger.warning(f"Found {summary['missing_images']} missing image files after reload")
messagebox.showwarning(
"Missing Files",
f"Warning: {summary['missing_images']} image files could not be found.\n"
f"These will be marked as unavailable."
)
else:
logger.error(f"Failed to reload CSV file: {self.current_csv_file}")
messagebox.showerror("Reload Error", f"Failed to reload the CSV file:\n{self.current_csv_file}")
except Exception as e:
logger.error(f"Error reloading CSV file: {e}", exc_info=True)
messagebox.showerror("Reload Error", f"Failed to reload CSV file:\n{str(e)}")
def load_database_file(self):
"""Load a previously created database file to resume work."""
from tkinter import filedialog
try:
logger.info("User requested to load database file")
# Select database file
db_file = filedialog.askopenfilename(
title="Select Lineup Database",
filetypes=[
("Lineup Database", "*.db"),
("SQLite Database", "*.sqlite"),
("All files", "*.*")
],
defaultextension=".db"
)
if db_file:
logger.info(f"Loading database file: {db_file}")
# Close any active image viewers
for viewer in self.active_image_viewers.copy():
if hasattr(viewer, 'window') and viewer.window.winfo_exists():
viewer.close()
self.active_image_viewers.clear()
# Clear current data
self.clear_current_data()
# Initialize data manager with the selected database
self.data_manager = DataManager(use_database=True)
# Update the database manager to use the selected file
if self.data_manager.db_manager:
# Disconnect from current database
self.data_manager.db_manager.disconnect()
# Update database path and reconnect
self.data_manager.db_manager.db_path = Path(db_file)
self.data_manager.db_manager.connect()
# Update legacy attributes for backward compatibility
self.data_manager._update_legacy_attributes()
# Check if database has data
if self.data_manager.has_data():
# Get database summary
summary = self.data_manager.get_overall_summary()
# Update UI state
self.current_csv_file = None # No CSV file, using database
self.current_database_file = db_file
# Add to recent databases
self.add_to_recent_databases(db_file)
# Enable controls
self.views_menu.configure(state="normal")
self.auto_select_switch.configure(state="normal")
self.hide_single_switch.configure(state="normal")
# Update status
self.status_label.configure(
text=f"Database: {Path(db_file).name} - {summary.get('total_groups', 0)} groups, "
f"{summary.get('total_images', 0)} images"
)
# Load first group
groups = self.data_manager.get_group_list()
if groups:
self.current_group = groups[0]
self.load_group(self.current_group)
self.show_operation_status(f"Database loaded successfully", "green")
# Show summary with any missing files
if summary.get('missing_images', 0) > 0:
messagebox.showwarning(
"Missing Files",
f"Database loaded successfully!\n\n"
f"Total groups: {summary['total_groups']}\n"
f"Total images: {summary['total_images']}\n\n"
f"Warning: {summary['missing_images']} image files could not be found.\n"
f"These will be filtered out from the display."
)
else:
messagebox.showinfo(
"Database Loaded",
f"Database loaded successfully!\n\n"
f"Total groups: {summary['total_groups']}\n"
f"Total images: {summary['total_images']}"
)
else:
messagebox.showwarning("Empty Database", "The selected database contains no image groups.")
self.status_label.configure(text="Database loaded but contains no data")
else:
messagebox.showerror("Invalid Database",
"The selected database appears to be empty or invalid.")
self.status_label.configure(text="Failed to load database")
else:
messagebox.showerror("Database Error", "Failed to initialize database manager.")
else:
logger.debug("Database file selection cancelled by user")
except Exception as e:
logger.error(f"Error loading database file: {e}", exc_info=True)
messagebox.showerror("Database Error", f"Failed to load database file:\n{str(e)}")
self.status_label.configure(text="Failed to load database")
def clear_current_data(self):
"""Clear current data and reset UI state."""
self.current_group = None
self.selected_images.clear()
self.image_widgets.clear()
# Clear the image display area
for widget in self.image_scroll_frame.winfo_children():
widget.destroy()
# Reset UI state
self.views_menu.configure(state="disabled")
self.reload_btn.configure(state="disabled")
self.auto_select_switch.configure(state="disabled")
self.hide_single_switch.configure(state="disabled")
def handle_database_selection(self, selection):
"""Handle database menu selection."""
if selection == "Browse for Database...":
self.load_database_file()
elif selection.endswith(".db") or selection.endswith(".sqlite"):
# Direct database file selection
self.load_specific_database(selection)
# Reset menu to default
self.database_menu.set("Load Database...")
def load_recent_databases(self):
"""Load the list of recent databases."""
try:
recent_file = Path.home() / ".lineup_recent_databases.txt"
if recent_file.exists():
with open(recent_file, 'r') as f:
self.recent_databases = [line.strip() for line in f.readlines() if line.strip()]
# Keep only existing files
self.recent_databases = [db for db in self.recent_databases if Path(db).exists()]
# Limit to 5 most recent
self.recent_databases = self.recent_databases[:5]
self.update_database_menu()
except Exception as e:
logger.warning(f"Failed to load recent databases: {e}")
def save_recent_databases(self):
"""Save the list of recent databases."""
try:
recent_file = Path.home() / ".lineup_recent_databases.txt"
with open(recent_file, 'w') as f:
for db in self.recent_databases:
f.write(f"{db}\n")
except Exception as e:
logger.warning(f"Failed to save recent databases: {e}")
def add_to_recent_databases(self, db_path):
"""Add a database to the recent list."""
db_path = str(Path(db_path).resolve())
# Remove if already in list
if db_path in self.recent_databases:
self.recent_databases.remove(db_path)
# Add to front
self.recent_databases.insert(0, db_path)
# Keep only 5 most recent
self.recent_databases = self.recent_databases[:5]
# Update UI and save
self.update_database_menu()
self.save_recent_databases()
def update_database_menu(self):
"""Update the database menu with recent databases."""
menu_items = ["Load Database...", "Browse for Database..."]
if self.recent_databases:
menu_items.append("──────────────") # Separator
for db_path in self.recent_databases:
display_name = Path(db_path).name
if len(display_name) > 25:
display_name = display_name[:22] + "..."
menu_items.append(display_name)
self.database_menu.configure(values=menu_items)
def load_specific_database(self, db_name):
"""Load a specific database from the recent list."""
# Find the full path
full_path = None
for db_path in self.recent_databases:
if Path(db_path).name == db_name or db_name in db_path:
full_path = db_path
break
if full_path and Path(full_path).exists():
self.load_database_file_direct(full_path)
else:
messagebox.showerror("Database Not Found", f"The database '{db_name}' could not be found.")
def load_database_file_direct(self, db_file):
"""Load a database file directly without file dialog."""
try:
logger.info(f"Loading database file directly: {db_file}")
# Close any active image viewers
for viewer in self.active_image_viewers.copy():
if hasattr(viewer, 'window') and viewer.window.winfo_exists():
viewer.close()
self.active_image_viewers.clear()
# Clear current data
self.clear_current_data()
# Initialize data manager with the selected database
self.data_manager = DataManager(use_database=True)
# Update the database manager to use the selected file
if self.data_manager.db_manager:
# Disconnect from current database
self.data_manager.db_manager.disconnect()
# Update database path and reconnect
self.data_manager.db_manager.db_path = Path(db_file)
self.data_manager.db_manager.connect()
# Update legacy attributes for backward compatibility
self.data_manager._update_legacy_attributes()
# Check if database has data
if self.data_manager.has_data():
# Get database summary
summary = self.data_manager.get_overall_summary()
# Update UI state
self.current_csv_file = None # No CSV file, using database
self.current_database_file = db_file
# Add to recent databases
self.add_to_recent_databases(db_file)
# Enable controls
self.views_menu.configure(state="normal")
self.auto_select_switch.configure(state="normal")
self.hide_single_switch.configure(state="normal")
# Update status
self.status_label.configure(
text=f"Database: {Path(db_file).name} - {summary.get('total_groups', 0)} groups, "
f"{summary.get('total_images', 0)} images"
)
# Load first group
groups = self.data_manager.get_group_list()
if groups:
self.current_group = groups[0]
self.load_group(self.current_group)
self.show_operation_status(f"Database loaded successfully", "green")
else:
messagebox.showwarning("Empty Database", "The selected database contains no image groups.")
self.status_label.configure(text="Database loaded but contains no data")
else:
messagebox.showerror("Invalid Database",
"The selected database appears to be empty or invalid.")
self.status_label.configure(text="Failed to load database")
else:
messagebox.showerror("Database Error", "Failed to initialize database manager.")
except Exception as e:
logger.error(f"Error loading database file: {e}", exc_info=True)
messagebox.showerror("Database Error", f"Failed to load database file:\n{str(e)}")
self.status_label.configure(text="Failed to load database")
def open_list_view(self):
"""Open the advanced list view screen."""
try:
logger.info("Opening list view screen")
# Create and show the list screen
list_screen = ListScreen(
parent=self.root,
data_manager=self.data_manager,
image_manager=self.image_manager,
main_app=self
)
list_screen.show()
except Exception as e:
logger.error(f"Error opening list view: {e}", exc_info=True)
messagebox.showerror("Error", f"Failed to open list view:\n{str(e)}")
def setup_content_ui(self):
"""Setup the main content UI after CSV is loaded."""
logger.debug("Setting up content UI after CSV load")
# Clear all existing content from content_frame
widget_count = len(self.content_frame.winfo_children())
for widget in self.content_frame.winfo_children():
widget.destroy()
logger.debug(f"Cleared {widget_count} existing UI widgets")
# Reset UI state
self.current_group = None
self.selected_images.clear()
self.image_widgets.clear()
self.group_buttons.clear()
logger.debug("Reset UI state for new CSV data")
# Create group navigation panel
self.nav_frame = ctk.CTkFrame(self.content_frame)
self.nav_frame.pack(side="left", fill="y", padx=(0, 5))
# Group list
nav_title = ctk.CTkLabel(self.nav_frame, text="Photo Groups", font=ctk.CTkFont(size=14, weight="bold"))
nav_title.pack(pady=10)
# Scrollable frame for groups
self.group_list_frame = ctk.CTkScrollableFrame(self.nav_frame, width=200)
self.group_list_frame.pack(fill="both", expand=True, padx=5, pady=5)
# Populate group list
self.populate_group_list()
# Main display area
self.display_frame = ctk.CTkFrame(self.content_frame)
self.display_frame.pack(side="right", fill="both", expand=True)
# Default message
self.select_message = ctk.CTkLabel(
self.display_frame,
text="Select a group from the left to view images",
font=ctk.CTkFont(size=14)
)
self.select_message.pack(expand=True)
# Setup keyboard shortcuts
self.setup_keyboard_shortcuts()
def setup_keyboard_shortcuts(self):
"""Setup keyboard shortcuts for the main application."""
# Bind keyboard events to the root window
self.root.bind('<KeyPress-d>', lambda e: self.keyboard_delete())
self.root.bind('<KeyPress-D>', lambda e: self.keyboard_delete())
self.root.bind('<KeyPress-m>', lambda e: self.keyboard_move())
self.root.bind('<KeyPress-M>', lambda e: self.keyboard_move())
self.root.bind('<KeyPress-n>', lambda e: self.keyboard_next_group())
self.root.bind('<KeyPress-N>', lambda e: self.keyboard_next_group())
self.root.bind('<KeyPress-p>', lambda e: self.keyboard_previous_group())
self.root.bind('<KeyPress-P>', lambda e: self.keyboard_previous_group())
# Make sure the window can receive focus for keyboard events
self.root.focus_set()
logger.debug("Keyboard shortcuts initialized: D=Delete, M=Move, N=Next Group, P=Previous Group")
def keyboard_delete(self):
"""Handle keyboard shortcut for delete."""
if hasattr(self, 'delete_btn') and self.delete_btn.cget('state') == 'normal':
logger.info("Keyboard shortcut: Delete (D) pressed")
self.delete_selected_images()
def keyboard_move(self):
"""Handle keyboard shortcut for move."""
if hasattr(self, 'move_btn') and self.move_btn.cget('state') == 'normal':
logger.info("Keyboard shortcut: Move (M) pressed")
self.move_selected_images()
def keyboard_next_group(self):
"""Handle keyboard shortcut for next group."""
if hasattr(self, 'next_group_btn') and self.next_group_btn.cget('state') == 'normal':
logger.info("Keyboard shortcut: Next Group (N) pressed")
self.go_to_next_group()
def keyboard_previous_group(self):
"""Handle keyboard shortcut for previous group."""
if hasattr(self, 'prev_group_btn') and self.prev_group_btn.cget('state') == 'normal':
logger.info("Keyboard shortcut: Previous Group (P) pressed")
self.go_to_previous_group()
def populate_group_list(self):
"""Populate the group list with buttons."""
logger.debug("Populating group list")
# Clear existing buttons
self.group_buttons.clear()
for widget in self.group_list_frame.winfo_children():
widget.destroy()
groups = self.data_manager.get_group_list()
logger.debug(f"Processing {len(groups)} total groups")
displayed_groups = 0
for group_id in groups:
summary = self.data_manager.get_group_summary(group_id)
# Skip groups with 1 or fewer images if hiding is enabled
if self.hide_single_groups and summary['existing_images'] <= 1:
logger.debug(f"Hiding group {group_id} with {summary['existing_images']} image(s)")
continue
# Create group button
btn_text = f"Group {group_id}\n{summary['existing_images']}/{summary['total_images']} images"
group_btn = ctk.CTkButton(
self.group_list_frame,
text=btn_text,
command=lambda gid=group_id: self.select_group(gid),
height=50,
fg_color="gray25", # Default unselected color
hover_color="gray35"
)
group_btn.pack(fill="x", pady=2)
# Store button reference
self.group_buttons[group_id] = group_btn
displayed_groups += 1
logger.debug(f"Displayed {displayed_groups} groups (hiding single groups: {self.hide_single_groups})")
# Update navigation button states
self.update_navigation_buttons()
def update_group_selection_visual(self, selected_group_id: str):
"""Update visual feedback for group selection."""
logger.debug(f"Updating group visual feedback for selected group: {selected_group_id}")
for group_id, button in self.group_buttons.items():
if group_id == selected_group_id:
# Highlight selected group
button.configure(
fg_color="#1f538d", # Blue for selected
hover_color="#14375e"
)
else:
# Reset other groups to default
button.configure(
fg_color="gray25",
hover_color="gray35"
)
def select_group(self, group_id: str):
"""Select and display a specific group."""
logger.info(f"Selecting group: {group_id}")
# Update visual feedback for group buttons
self.update_group_selection_visual(group_id)
self.current_group = group_id
# Get group info for logging
summary = self.data_manager.get_group_summary(group_id)
logger.debug(f"Group {group_id} summary: {summary}")
# Pre-load adjacent groups for faster navigation
self.preload_adjacent_groups(group_id)
# Clear display area
for widget in self.display_frame.winfo_children():
widget.destroy()
# Show group info
summary = self.data_manager.get_group_summary(group_id)
info_label = ctk.CTkLabel(
self.display_frame,
text=f"Group {group_id} - {summary['existing_images']}/{summary['total_images']} images available\n"
f"Match Reasons: {summary['match_reasons']}",
font=ctk.CTkFont(size=12)
)
info_label.pack(pady=10)
# Action buttons frame
self.action_frame = ctk.CTkFrame(self.display_frame)
self.action_frame.pack(fill="x", padx=5, pady=5)
# Selection info
self.selection_label = ctk.CTkLabel(
self.action_frame,
text="No images selected"
)
self.selection_label.pack(side="left", padx=5)
# Action buttons
self.delete_btn = ctk.CTkButton(
self.action_frame,
text="Delete Selected (D)",
command=self.delete_selected_images,
state="disabled"
)
self.delete_btn.pack(side="right", padx=5)
self.move_btn = ctk.CTkButton(
self.action_frame,
text="Move Selected (M)",
command=self.move_selected_images,
state="disabled"
)
self.move_btn.pack(side="right", padx=5)
# Scrollable frame for images
self.image_scroll_frame = ctk.CTkScrollableFrame(self.display_frame)
self.image_scroll_frame.pack(fill="both", expand=True, padx=5, pady=5)
# Display images
self.display_group_images(group_id)
def display_group_images(self, group_id: str):
"""Display all images for the selected group."""
group_data = self.data_manager.get_group(group_id)
if group_data is None:
return
# Clear previous widgets
self.image_widgets.clear()
for widget in self.image_scroll_frame.winfo_children():
widget.destroy()
# Calculate optimal grid layout based on available space
self.root.update_idletasks() # Ensure geometry is calculated
available_width = self.image_scroll_frame.winfo_width()
if available_width <= 1: # Not yet rendered
available_width = 800 # Default fallback
# Calculate dynamic thumbnail size and columns
min_thumb_size = 250
max_thumb_size = 800 # Increased from 400 to better use screen space
min_columns = 2
max_columns = 8 # Increased from 6 to allow more flexible layouts
# Try different column counts to find optimal size
best_columns = min_columns
best_thumb_size = min_thumb_size
for cols in range(min_columns, max_columns + 1):
padding = 10 * (cols + 1) # Account for padding
available_per_image = (available_width - padding) / cols
if available_per_image >= min_thumb_size:
thumb_size = min(available_per_image, max_thumb_size)
if thumb_size > best_thumb_size:
best_columns = cols
best_thumb_size = thumb_size
# If we have a very wide screen, prefer larger thumbnails over more columns
if available_width > 1600 and best_thumb_size < max_thumb_size:
# Recalculate with preference for larger thumbnails
for cols in range(min_columns, best_columns + 1):
padding = 10 * (cols + 1)
available_per_image = (available_width - padding) / cols
thumb_size = min(available_per_image, max_thumb_size)
if thumb_size >= best_thumb_size * 1.2: # At least 20% larger
best_columns = cols
best_thumb_size = thumb_size
break
# Update image manager thumbnail size
self.image_manager.thumbnail_size = (int(best_thumb_size), int(best_thumb_size))
# Create grid layout for images
columns = best_columns
row = 0
col = 0
for idx, (_, image_data) in enumerate(group_data.iterrows()):
# Create image widget with dynamic size
image_widget = ImageWidget(
self.image_scroll_frame,
image_data,
self.image_manager,
thumbnail_size=int(best_thumb_size),
main_app=self
)
image_widget.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
self.image_widgets.append(image_widget)
# Bind double-click for full-size viewer
image_widget.bind("<Double-Button-1>", lambda e, idx=idx: self.open_image_viewer(idx))
image_widget.image_label.bind("<Double-Button-1>", lambda e, idx=idx: self.open_image_viewer(idx))
# Update grid position
col += 1
if col >= columns:
col = 0
row += 1
# Configure grid weights for responsive layout
for i in range(columns):
self.image_scroll_frame.grid_columnconfigure(i, weight=1)
# Auto-select non-master images for easy processing (if enabled)
if self.auto_select_enabled:
self.auto_select_non_masters()
else:
self.selected_images.clear()
# Update selection UI
self.update_selection_ui()
# Start aggressive pre-loading for current group images
self.start_current_group_preloading()
# Also pre-load adjacent groups for faster navigation
self.preload_adjacent_groups()
def auto_select_non_masters(self):
"""Automatically select non-master images for easy processing."""
logger.debug(f"Auto-selecting non-master images in group {self.current_group}")
self.selected_images.clear()
selected_count = 0
for image_widget in self.image_widgets:
if not image_widget.is_master and image_widget.file_exists:
image_widget.set_selected(True)
self.selected_images.add(image_widget)
selected_count += 1
if selected_count > 0:
logger.info(f"Auto-selected {selected_count} non-master images in group {self.current_group}")
self.show_operation_status(f"Auto-selected {selected_count} non-master image(s)", "blue")
# Check if auto-selection selected all images except master (warning condition)
total_existing = sum(1 for w in self.image_widgets if w.file_exists)
if selected_count == total_existing - 1 and total_existing > 1:
logger.warning(f"Auto-selected all non-master images in group {self.current_group} - only master will remain")
self.show_operation_status("⚠️ Auto-selected all duplicates - only master will remain", "orange")
else:
logger.debug(f"No non-master images to auto-select in group {self.current_group}")
# Update button states after auto-selection
self.update_selection_ui()
def start_current_group_preloading(self):
"""Start aggressive pre-loading for current group images."""