-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_manager.py
More file actions
1158 lines (948 loc) · 44.6 KB
/
Copy pathimage_manager.py
File metadata and controls
1158 lines (948 loc) · 44.6 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
from PIL import Image, ImageTk
import customtkinter as ctk
from pathlib import Path
import logging
# Register HEIF/HEIC support
try:
from pillow_heif import register_heif_opener
register_heif_opener()
logging.info("HEIF/HEIC support enabled via pillow-heif")
except ImportError:
logging.warning("pillow-heif not available - HEIF/HEIC files will not be supported")
from typing import Dict, Optional, Tuple
import threading
import json
from hashlib import md5
# Get logger for this module
logger = logging.getLogger('lineup.image_manager')
class ImageManager:
"""Handles image loading, thumbnail generation, and caching."""
def __init__(self, cache_dir: str = ".image_cache"):
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(exist_ok=True)
# In-memory cache for loaded images
self.image_cache: Dict[str, ImageTk.PhotoImage] = {}
self.thumbnail_cache: Dict[str, ImageTk.PhotoImage] = {}
# Cache metadata
self.cache_metadata_file = self.cache_dir / "cache_metadata.json"
self.cache_metadata = self._load_cache_metadata()
# Thumbnail settings
self.thumbnail_size = (150, 150)
self.preview_size = (400, 400)
# Pre-loading state
self.preload_threads = {} # Track active preload threads
self.max_cache_size = 50 # Limit memory usage
logger.info(f"ImageManager initialized with cache dir: {self.cache_dir}")
logger.debug(f"Thumbnail size: {self.thumbnail_size}, Preview size: {self.preview_size}")
def _load_cache_metadata(self) -> Dict:
"""Load cache metadata from disk."""
if self.cache_metadata_file.exists():
try:
with open(self.cache_metadata_file, 'r') as f:
return json.load(f)
except Exception as e:
logging.warning(f"Could not load cache metadata: {e}")
return {}
def _save_cache_metadata(self):
"""Save cache metadata to disk."""
try:
with open(self.cache_metadata_file, 'w') as f:
json.dump(self.cache_metadata, f)
except Exception as e:
logging.warning(f"Could not save cache metadata: {e}")
def _get_cache_key(self, file_path: str, size: Tuple[int, int]) -> str:
"""Generate cache key for a file and size."""
content = f"{file_path}_{size[0]}x{size[1]}"
return md5(content.encode()).hexdigest()
def _get_cached_thumbnail_path(self, cache_key: str) -> Path:
"""Get the path for a cached thumbnail."""
return self.cache_dir / f"{cache_key}.png"
def load_thumbnail(self, file_path: str, callback=None, quick_load=False) -> Optional[ImageTk.PhotoImage]:
"""Load or generate thumbnail for an image.
Args:
file_path: Path to the image file
callback: Optional callback function for async loading
quick_load: If True, return a quick low-quality preview first
"""
if not Path(file_path).exists():
return None
cache_key = self._get_cache_key(file_path, self.thumbnail_size)
# Check in-memory cache first
if cache_key in self.thumbnail_cache:
if callback:
callback(self.thumbnail_cache[cache_key])
return self.thumbnail_cache[cache_key]
# Check disk cache
cached_path = self._get_cached_thumbnail_path(cache_key)
file_stat = Path(file_path).stat()
if (cached_path.exists() and
cache_key in self.cache_metadata and
self.cache_metadata[cache_key].get('mtime') == file_stat.st_mtime):
try:
# Load from disk cache
image = Image.open(cached_path)
photo_image = ImageTk.PhotoImage(image)
self.thumbnail_cache[cache_key] = photo_image
if callback:
callback(photo_image)
return photo_image
except Exception as e:
logging.warning(f"Could not load cached thumbnail for {file_path}: {e}")
# Quick load mode: provide immediate low-quality preview
if quick_load and callback:
self._load_quick_thumbnail_async(file_path, cache_key, callback)
return None
# Generate new thumbnail
if callback:
# Generate asynchronously
thread = threading.Thread(
target=self._generate_thumbnail_async,
args=(file_path, cache_key, callback)
)
thread.daemon = True
thread.start()
return None
else:
# Generate synchronously
return self._generate_thumbnail(file_path, cache_key)
def _generate_thumbnail(self, file_path: str, cache_key: str) -> Optional[ImageTk.PhotoImage]:
"""Generate thumbnail synchronously."""
try:
with Image.open(file_path) as image:
# Convert to RGB if necessary
if image.mode in ('RGBA', 'LA', 'P'):
image = image.convert('RGB')
# Generate thumbnail
image.thumbnail(self.thumbnail_size, Image.Resampling.LANCZOS)
# Save to disk cache
cached_path = self._get_cached_thumbnail_path(cache_key)
image.save(cached_path, 'PNG')
# Update metadata
file_stat = Path(file_path).stat()
self.cache_metadata[cache_key] = {
'file_path': file_path,
'mtime': file_stat.st_mtime,
'size': self.thumbnail_size
}
self._save_cache_metadata()
# Create PhotoImage
photo_image = ImageTk.PhotoImage(image)
self.thumbnail_cache[cache_key] = photo_image
return photo_image
except Exception as e:
logging.error(f"Could not generate thumbnail for {file_path}: {e}")
return None
def _load_quick_thumbnail_async(self, file_path: str, cache_key: str, callback):
"""Load a quick, low-quality thumbnail first, then a high-quality one."""
def quick_load_worker():
try:
# First pass: Quick, low-quality thumbnail
with Image.open(file_path) as image:
if image.mode in ('RGBA', 'LA', 'P'):
image = image.convert('RGB')
# Create a very quick, low-quality preview (1/4 size, then scaled up)
quick_size = (self.thumbnail_size[0] // 2, self.thumbnail_size[1] // 2)
quick_image = image.copy()
quick_image.thumbnail(quick_size, Image.Resampling.NEAREST) # Fastest resampling
# Scale back up for display
quick_image = quick_image.resize(self.thumbnail_size, Image.Resampling.NEAREST)
quick_photo = ImageTk.PhotoImage(quick_image)
# Provide quick preview immediately
callback(quick_photo)
# Now generate high-quality thumbnail in background
high_quality_photo = self._generate_thumbnail(file_path, cache_key)
if high_quality_photo:
# Replace with high-quality version
callback(high_quality_photo)
except Exception as e:
logger.warning(f"Failed to load quick thumbnail for {file_path}: {e}")
# Fallback to normal thumbnail generation
photo_image = self._generate_thumbnail(file_path, cache_key)
if photo_image:
callback(photo_image)
thread = threading.Thread(target=quick_load_worker, daemon=True)
thread.start()
def _generate_thumbnail_async(self, file_path: str, cache_key: str, callback):
"""Generate thumbnail asynchronously and call callback."""
photo_image = self._generate_thumbnail(file_path, cache_key)
if photo_image and callback:
# Schedule callback on main thread
callback(photo_image)
def load_preview_image(self, file_path: str, callback=None, target_size=None) -> Optional[ImageTk.PhotoImage]:
"""Load a larger preview image.
Args:
file_path: Path to the image file
callback: Optional callback for async loading
target_size: Optional target size (width, height), defaults to preview_size
"""
if not Path(file_path).exists():
return None
size = target_size or self.preview_size
cache_key = self._get_cache_key(file_path, size)
# Check in-memory cache
if cache_key in self.image_cache:
if callback:
callback(self.image_cache[cache_key])
return self.image_cache[cache_key]
if callback:
# Load asynchronously
thread = threading.Thread(
target=self._load_preview_async,
args=(file_path, cache_key, size, callback)
)
thread.daemon = True
thread.start()
return None
# Load synchronously
return self._load_preview_sync(file_path, cache_key, size)
def _load_preview_sync(self, file_path: str, cache_key: str, size: Tuple[int, int]) -> Optional[ImageTk.PhotoImage]:
"""Load preview image synchronously."""
try:
with Image.open(file_path) as image:
# Convert to RGB if necessary
if image.mode in ('RGBA', 'LA', 'P'):
image = image.convert('RGB')
# Resize for preview
image.thumbnail(size, Image.Resampling.LANCZOS)
# Create PhotoImage
photo_image = ImageTk.PhotoImage(image)
self.image_cache[cache_key] = photo_image
return photo_image
except Exception as e:
logging.error(f"Could not load preview image for {file_path}: {e}")
return None
def _load_preview_async(self, file_path: str, cache_key: str, size: Tuple[int, int], callback):
"""Load preview image asynchronously."""
photo_image = self._load_preview_sync(file_path, cache_key, size)
if photo_image and callback:
callback(photo_image)
def get_image_info(self, file_path: str) -> Dict:
"""Get basic information about an image file."""
if not Path(file_path).exists():
return {'error': 'File not found'}
try:
with Image.open(file_path) as image:
file_stat = Path(file_path).stat()
return {
'width': image.width,
'height': image.height,
'mode': image.mode,
'format': image.format,
'file_size': file_stat.st_size,
'file_size_mb': round(file_stat.st_size / 1024 / 1024, 2)
}
except Exception as e:
return {'error': str(e)}
def preload_group_images(self, file_paths: list, group_id: str = None, priority: bool = False):
"""Pre-load images for a group in background thread.
Args:
file_paths: List of image file paths to preload
group_id: Group identifier for tracking
priority: If True, load with higher priority and larger cache allocation
"""
if not file_paths:
return
# Cancel existing preload for this group if any
if group_id and group_id in self.preload_threads:
# Don't interrupt if already running
if self.preload_threads[group_id].is_alive():
logger.debug(f"Preload already running for group {group_id}")
return
def preload_worker():
logger.debug(f"Starting {'priority' if priority else 'background'} preload for group {group_id} with {len(file_paths)} images")
loaded_count = 0
# Adjust cache size for priority loading
original_max_cache = self.max_cache_size
if priority:
self.max_cache_size = min(100, original_max_cache * 2) # Double cache size for priority loading
for file_path in file_paths:
if not Path(file_path).exists():
continue
# Check if already cached
cache_key = self._get_cache_key(file_path, self.preview_size)
if cache_key in self.image_cache:
continue
# For priority loading, be more aggressive with cache management
cache_threshold = self.max_cache_size if priority else self.max_cache_size * 0.8
if len(self.image_cache) >= cache_threshold:
self._evict_oldest_cache_entries()
try:
# Load preview image synchronously for better control
self._load_preview_sync(file_path, cache_key, self.preview_size)
loaded_count += 1
logger.debug(f"Pre-loaded image {loaded_count}/{len(file_paths)}: {Path(file_path).name}")
# For priority loading, also pre-load thumbnails
if priority:
thumb_cache_key = self._get_cache_key(file_path, self.thumbnail_size)
if thumb_cache_key not in self.thumbnail_cache:
self._generate_thumbnail(file_path, thumb_cache_key)
except Exception as e:
logger.warning(f"Failed to preload {file_path}: {e}")
# Restore original cache size
if priority:
self.max_cache_size = original_max_cache
logger.info(f"{'Priority' if priority else 'Background'} preload complete for group {group_id}: {loaded_count} images loaded")
thread = threading.Thread(target=preload_worker, daemon=True)
thread.start()
if group_id:
self.preload_threads[group_id] = thread
def _evict_oldest_cache_entries(self):
"""Remove oldest cache entries to manage memory usage."""
if len(self.image_cache) <= self.max_cache_size * 0.8:
return
# Remove 20% of cache entries (simple FIFO for now)
entries_to_remove = max(1, len(self.image_cache) // 5)
keys_to_remove = list(self.image_cache.keys())[:entries_to_remove]
for key in keys_to_remove:
del self.image_cache[key]
logger.debug(f"Evicted {len(keys_to_remove)} cache entries for memory management")
def clear_cache(self):
"""Clear all caches."""
self.image_cache.clear()
self.thumbnail_cache.clear()
self.preload_threads.clear()
# Clear disk cache
try:
for cache_file in self.cache_dir.glob("*.png"):
cache_file.unlink()
self.cache_metadata.clear()
self._save_cache_metadata()
logging.info("Image cache cleared")
except Exception as e:
logging.error(f"Could not clear cache: {e}")
class ImageWidget(ctk.CTkFrame):
"""Custom widget for displaying an image with selection and master highlighting."""
def __init__(self, parent, image_data, image_manager, thumbnail_size=150, main_app=None, **kwargs):
super().__init__(parent, **kwargs)
self.image_data = image_data # Row from DataFrame
self.image_manager = image_manager
self.is_selected = False
self.is_master = image_data.get('IsMaster', False)
self.file_exists = image_data.get('FileExists', False)
self.thumbnail_size = thumbnail_size
self.main_app = main_app
self.setup_ui()
self.load_thumbnail()
def setup_ui(self):
"""Setup the image widget UI."""
# Configure grid
self.grid_columnconfigure(0, weight=1)
# Image label
self.image_label = ctk.CTkLabel(
self,
text="Loading...",
width=self.thumbnail_size,
height=self.thumbnail_size
)
self.image_label.grid(row=0, column=0, padx=5, pady=5)
# File name label
file_name = Path(self.image_data['File']).name
self.name_label = ctk.CTkLabel(
self,
text=file_name,
width=self.thumbnail_size,
font=ctk.CTkFont(size=max(8, min(12, self.thumbnail_size // 15))),
wraplength=self.thumbnail_size - 10 # Enable text wrapping
)
self.name_label.grid(row=1, column=0, padx=5, pady=(0, 5))
# File path label
file_path = self.image_data['Path']
self.path_label = ctk.CTkLabel(
self,
text=file_path,
width=self.thumbnail_size,
font=ctk.CTkFont(size=max(7, min(10, self.thumbnail_size // 20))),
wraplength=self.thumbnail_size - 10, # Enable text wrapping
text_color="gray"
)
self.path_label.grid(row=2, column=0, padx=5, pady=(0, 5))
# Master indicator
if self.is_master:
self.master_label = ctk.CTkLabel(
self,
text="★ MASTER",
text_color="gold",
font=ctk.CTkFont(size=10, weight="bold")
)
self.master_label.grid(row=3, column=0, padx=5, pady=(0, 5))
# File status
if not self.file_exists:
self.status_label = ctk.CTkLabel(
self,
text="❌ Missing",
text_color="red",
font=ctk.CTkFont(size=10)
)
self.status_label.grid(row=4, column=0, padx=5, pady=(0, 5))
# Bind click events
self.bind("<Button-1>", self.on_click)
self.image_label.bind("<Button-1>", self.on_click)
self.name_label.bind("<Button-1>", self.on_click)
self.path_label.bind("<Button-1>", self.on_click)
# Update border for master status
self.update_appearance()
def load_thumbnail(self):
"""Load thumbnail image with quick preview first."""
if not self.file_exists:
self.image_label.configure(text="❌\nMissing\nFile")
return
def thumbnail_callback(photo_image):
if photo_image:
self.image_label.configure(image=photo_image, text="")
# Keep reference to prevent garbage collection
self.image_label.image = photo_image
# Try to load from cache first (immediate)
thumbnail = self.image_manager.load_thumbnail(
self.image_data['Path'],
callback=None # No callback, just check cache
)
if thumbnail:
# Got it from cache, display immediately
self.image_label.configure(image=thumbnail, text="")
self.image_label.image = thumbnail
else:
# Not in cache, use quick loading with callback
self.image_label.configure(text="Loading...")
self.image_manager.load_thumbnail(
self.image_data['Path'],
callback=thumbnail_callback,
quick_load=True # Use the new quick loading feature
)
def on_click(self, event):
"""Handle click events."""
self.toggle_selection()
def toggle_selection(self):
"""Toggle selection state."""
self.is_selected = not self.is_selected
self.update_appearance()
# Notify main app of selection change
if self.main_app and hasattr(self.main_app, 'on_image_selection_changed'):
self.main_app.on_image_selection_changed(self)
def set_selected(self, selected: bool):
"""Set selection state."""
self.is_selected = selected
self.update_appearance()
def update_appearance(self):
"""Update widget appearance based on state."""
if self.is_selected:
# Selected images are always red
border_color = "red"
border_width = 3
else:
# Non-selected images are always green (no special master styling)
border_color = "green"
border_width = 1
self.configure(border_width=border_width, border_color=border_color)
class ImageViewerWindow:
"""Full-size image viewer window with navigation."""
def __init__(self, parent, image_widgets, current_index, image_manager, data_manager=None, current_group=None, main_app=None):
self.parent = parent
self.image_widgets = image_widgets
self.current_index = current_index
self.image_manager = image_manager
self.data_manager = data_manager
self.current_group = current_group
self.main_app = main_app
# Create window
self.window = ctk.CTkToplevel(parent)
self.window.title("Image Viewer")
self.window.geometry("1000x750") # Sized to fit 1920x1080 screens comfortably
self.window.minsize(600, 450)
# Make window modal
self.window.transient(parent)
self.window.grab_set()
# Center window on parent
self.center_window()
self.setup_ui()
self.bind_keys()
self.load_current_image()
def center_window(self):
"""Center the window on the parent and ensure it fits on screen."""
self.window.update_idletasks()
# Get screen dimensions
screen_width = self.window.winfo_screenwidth()
screen_height = self.window.winfo_screenheight()
# Get parent window position and size
parent_x = self.parent.winfo_x()
parent_y = self.parent.winfo_y()
parent_width = self.parent.winfo_width()
parent_height = self.parent.winfo_height()
# Get this window size
window_width = self.window.winfo_width()
window_height = self.window.winfo_height()
# Adjust window size if it's too large for the screen
max_width = int(screen_width * 0.9) # Use 90% of screen width
max_height = int(screen_height * 0.85) # Use 85% of screen height (leave room for taskbar)
if window_width > max_width or window_height > max_height:
window_width = min(window_width, max_width)
window_height = min(window_height, max_height)
self.window.geometry(f"{window_width}x{window_height}")
self.window.update_idletasks()
# Calculate center position
x = parent_x + (parent_width - window_width) // 2
y = parent_y + (parent_height - window_height) // 2
# Ensure window doesn't go off screen
x = max(0, min(x, screen_width - window_width))
y = max(0, min(y, screen_height - window_height))
self.window.geometry(f"{window_width}x{window_height}+{x}+{y}")
def setup_ui(self):
"""Setup the viewer UI."""
# Main frame
self.main_frame = ctk.CTkFrame(self.window)
self.main_frame.pack(fill="both", expand=True, padx=10, pady=10)
# Group info bar (top)
if self.data_manager and self.current_group:
self.group_info_frame = ctk.CTkFrame(self.main_frame)
self.group_info_frame.pack(fill="x", padx=5, pady=5)
# Group navigation
self.prev_group_btn = ctk.CTkButton(
self.group_info_frame,
text="◀ Prev Group (P)",
command=self.previous_group,
width=100
)
self.prev_group_btn.pack(side="left", padx=5)
# Group info display
self.group_info_label = ctk.CTkLabel(
self.group_info_frame,
text="",
font=ctk.CTkFont(size=14, weight="bold")
)
self.group_info_label.pack(side="left", expand=True, padx=20)
# Next group button
self.next_group_btn = ctk.CTkButton(
self.group_info_frame,
text="Next Group ▶ (N)",
command=self.next_group,
width=100
)
self.next_group_btn.pack(side="right", padx=5)
# Image info bar
self.info_frame = ctk.CTkFrame(self.main_frame)
self.info_frame.pack(fill="x", padx=5, pady=5)
# Image counter
self.counter_label = ctk.CTkLabel(
self.info_frame,
text="",
font=ctk.CTkFont(size=12)
)
self.counter_label.pack(side="left", padx=10)
# File name
self.filename_label = ctk.CTkLabel(
self.info_frame,
text="",
font=ctk.CTkFont(size=12, weight="bold")
)
self.filename_label.pack(side="left", padx=10)
# File path
self.filepath_label = ctk.CTkLabel(
self.info_frame,
text="",
font=ctk.CTkFont(size=10),
text_color="gray"
)
self.filepath_label.pack(side="left", padx=10)
# Master indicator
self.master_indicator = ctk.CTkLabel(
self.info_frame,
text="",
text_color="gold",
font=ctk.CTkFont(size=12, weight="bold")
)
self.master_indicator.pack(side="right", padx=10)
# Navigation buttons frame
self.nav_frame = ctk.CTkFrame(self.main_frame)
self.nav_frame.pack(fill="x", padx=5, pady=5)
# Previous button
self.prev_btn = ctk.CTkButton(
self.nav_frame,
text="◀ Previous (←)",
command=self.previous_image,
width=120
)
self.prev_btn.pack(side="left", padx=5)
# Next button
self.next_btn = ctk.CTkButton(
self.nav_frame,
text="Next (→) ▶",
command=self.next_image,
width=120
)
self.next_btn.pack(side="right", padx=5)
# Action buttons frame
self.action_frame = ctk.CTkFrame(self.nav_frame)
self.action_frame.pack(side="bottom", fill="x", pady=5)
# Delete button
self.delete_btn = ctk.CTkButton(
self.action_frame,
text="Delete Image (D)",
command=self.delete_current_image,
width=100,
fg_color="red",
hover_color="darkred"
)
self.delete_btn.pack(side="left", padx=5)
# Move button
self.move_btn = ctk.CTkButton(
self.action_frame,
text="Move Image (M)",
command=self.move_current_image,
width=100
)
self.move_btn.pack(side="left", padx=5)
# Close button
self.close_btn = ctk.CTkButton(
self.action_frame,
text="Close (Esc)",
command=self.close,
width=100
)
self.close_btn.pack(side="right", padx=5)
# Image display frame
self.image_frame = ctk.CTkFrame(self.main_frame)
self.image_frame.pack(fill="both", expand=True, padx=5, pady=5)
# Image label (scrollable)
self.image_scroll = ctk.CTkScrollableFrame(self.image_frame)
self.image_scroll.pack(fill="both", expand=True)
self.image_label = ctk.CTkLabel(
self.image_scroll,
text="Loading...",
font=ctk.CTkFont(size=16)
)
self.image_label.pack(expand=True, fill="both")
def bind_keys(self):
"""Bind keyboard shortcuts."""
# Navigation shortcuts
self.window.bind("<Left>", lambda e: self.previous_image())
self.window.bind("<Right>", lambda e: self.next_image())
self.window.bind("<Escape>", lambda e: self.close())
self.window.bind("<Return>", lambda e: self.close())
# Action shortcuts
self.window.bind("<KeyPress-d>", lambda e: self.keyboard_delete_image())
self.window.bind("<KeyPress-D>", lambda e: self.keyboard_delete_image())
self.window.bind("<KeyPress-m>", lambda e: self.keyboard_move_image())
self.window.bind("<KeyPress-M>", lambda e: self.keyboard_move_image())
self.window.bind("<KeyPress-n>", lambda e: self.keyboard_next_group())
self.window.bind("<KeyPress-N>", lambda e: self.keyboard_next_group())
self.window.bind("<KeyPress-p>", lambda e: self.keyboard_previous_group())
self.window.bind("<KeyPress-P>", lambda e: self.keyboard_previous_group())
# Make sure window has focus for key events
self.window.focus_set()
logging.debug("Image viewer keyboard shortcuts: ←/→=Nav, D=Delete, M=Move, N/P=Groups, Esc=Close")
def keyboard_delete_image(self):
"""Handle keyboard shortcut for deleting current image."""
if hasattr(self, 'delete_btn') and self.delete_btn.cget('state') == 'normal':
logging.info("Image viewer keyboard shortcut: Delete (D) pressed")
self.delete_current_image()
def keyboard_move_image(self):
"""Handle keyboard shortcut for moving current image."""
if hasattr(self, 'move_btn') and self.move_btn.cget('state') == 'normal':
logging.info("Image viewer keyboard shortcut: Move (M) pressed")
self.move_current_image()
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':
logging.info("Image viewer keyboard shortcut: Next Group (N) pressed")
self.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':
logging.info("Image viewer keyboard shortcut: Previous Group (P) pressed")
self.previous_group()
def load_current_image(self):
"""Load and display the current image."""
if not self.image_widgets or self.current_index >= len(self.image_widgets):
return
current_widget = self.image_widgets[self.current_index]
image_data = current_widget.image_data
# Update group info if available
if self.data_manager and self.current_group:
group_summary = self.data_manager.get_group_summary(self.current_group)
group_list = self.data_manager.get_group_list()
current_group_index = group_list.index(self.current_group) + 1 if self.current_group in group_list else 0
group_info_text = f"Group {self.current_group} ({current_group_index}/{len(group_list)}) - {group_summary.get('existing_images', 0)} images"
if group_summary.get('match_reasons'):
group_info_text += f" - {group_summary['match_reasons']}"
self.group_info_label.configure(text=group_info_text)
# Update group navigation buttons
self.prev_group_btn.configure(state="normal" if current_group_index > 1 else "disabled")
self.next_group_btn.configure(state="normal" if current_group_index < len(group_list) else "disabled")
# Update info labels
self.counter_label.configure(
text=f"Image {self.current_index + 1} of {len(self.image_widgets)}"
)
file_path = Path(image_data['File'])
self.filename_label.configure(text=file_path.name)
self.filepath_label.configure(text=image_data['Path'])
# Show master indicator
if current_widget.is_master:
self.master_indicator.configure(text="★ MASTER")
else:
self.master_indicator.configure(text="")
# Update navigation buttons
self.prev_btn.configure(state="normal" if self.current_index > 0 else "disabled")
self.next_btn.configure(state="normal" if self.current_index < len(self.image_widgets) - 1 else "disabled")
# Update move button text based on pre-selected directory
self.update_move_button_text()
# Load full-size image
if current_widget.file_exists:
self.load_full_image(image_data['Path'])
else:
self.image_label.configure(
image=None,
text="❌ File Not Found\n\n" + str(file_path)
)
def load_full_image(self, file_path: str):
"""Load and display full-size image with progressive loading."""
try:
# Get window size for optimal display
self.window.update_idletasks()
max_width = self.image_frame.winfo_width() - 20
max_height = self.image_frame.winfo_height() - 20
if max_width <= 1 or max_height <= 1:
max_width = 800
max_height = 600
target_size = (max_width, max_height)
# Check if we have a cached preview image first
cache_key = self.image_manager._get_cache_key(file_path, self.image_manager.preview_size)
cached_image = self.image_manager.image_cache.get(cache_key)
if cached_image:
# Use cached image immediately - much faster
self.image_label.configure(image=cached_image, text="")
self.image_label.image = cached_image
logger.debug(f"Used cached image for {Path(file_path).name}")
# Get original dimensions for title
try:
with Image.open(file_path) as img:
img_width, img_height = img.size
self.window.title(f"Image Viewer - {Path(file_path).name} ({img_width}×{img_height})")
except:
self.window.title(f"Image Viewer - {Path(file_path).name}")
# If the cached image is smaller than our target, load a better quality version in background
if (cached_image.width() < max_width * 0.8 or
cached_image.height() < max_height * 0.8):
self._load_high_quality_async(file_path, target_size)
return
# No cached image available, show loading message and load asynchronously
self.image_label.configure(image=None, text="Loading full image...")
self._load_high_quality_async(file_path, target_size)
except Exception as e:
logging.error(f"Could not load image {file_path}: {e}")
self.image_label.configure(
image=None,
text=f"❌ Error Loading Image\n\n{str(e)}"
)
def _load_high_quality_async(self, file_path: str, target_size: Tuple[int, int]):
"""Load high-quality image asynchronously."""
def load_callback(photo_image):
if photo_image:
self.image_label.configure(image=photo_image, text="")
self.image_label.image = photo_image
# Update window title with image info
try:
with Image.open(file_path) as img:
img_width, img_height = img.size
self.window.title(f"Image Viewer - {Path(file_path).name} ({img_width}×{img_height})")
except:
self.window.title(f"Image Viewer - {Path(file_path).name}")
# Use the async preview loading
self.image_manager.load_preview_image(
file_path,
callback=load_callback,
target_size=target_size
)
def previous_image(self):
"""Navigate to previous image."""
if self.current_index > 0:
self.current_index -= 1
self.load_current_image()
def next_image(self):
"""Navigate to next image."""
if self.current_index < len(self.image_widgets) - 1:
self.current_index += 1
self.load_current_image()
def update_move_button_text(self):
"""Update move button text based on pre-selected directory."""
if hasattr(self, 'move_btn') and self.main_app:
if self.main_app.move_to_directory and self.main_app.move_to_directory.exists():
self.move_btn.configure(text="Move to Pre-selected (M)")
else:
self.move_btn.configure(text="Move Image (M)")
def previous_group(self):
"""Navigate to previous group."""
if not (self.data_manager and self.current_group and self.main_app):
return
group_list = self.data_manager.get_group_list()
if self.current_group not in group_list:
return
current_index = group_list.index(self.current_group)
if current_index > 0:
new_group = group_list[current_index - 1]
self.switch_to_group(new_group)
def next_group(self):
"""Navigate to next group."""
if not (self.data_manager and self.current_group and self.main_app):
return
group_list = self.data_manager.get_group_list()
if self.current_group not in group_list:
return
current_index = group_list.index(self.current_group)
if current_index < len(group_list) - 1:
new_group = group_list[current_index + 1]
self.switch_to_group(new_group)
def switch_to_group(self, new_group: str):
"""Switch to a different group and update the viewer."""
# Update main app to display new group
self.main_app.select_group(new_group)
# Update this viewer with new group data
self.current_group = new_group
self.image_widgets = self.main_app.image_widgets
self.current_index = 0 # Start with first image in new group
# Reload the display
self.load_current_image()
def delete_current_image(self):
"""Delete the currently displayed image."""
if not self.image_widgets or self.current_index >= len(self.image_widgets):
return
from tkinter import messagebox
import logging
current_widget = self.image_widgets[self.current_index]
file_path = current_widget.image_data['Path']