-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui_components.py
More file actions
2157 lines (1877 loc) · 75.7 KB
/
Copy pathgui_components.py
File metadata and controls
2157 lines (1877 loc) · 75.7 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
"""
Reusable GUI components for the dithering application.
Separated from main app for better maintainability.
"""
import os
import json
import colorsys
import ctypes
import threading
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog, colorchooser
import customtkinter as ctk
from PIL import Image, ImageTk
import numpy as np
from typing import List, Tuple, Optional, Callable
__all__ = [
'ZoomableImage',
'PixelizationEditorCanvas',
'PalettePreview',
'ProgressDialog',
'ColorPickerGrid',
'StatusBar',
'ImageComparisonView',
'HSVColorPickerDialog',
'CustomPaletteCreator',
'PaletteImagePreviewDialog',
'DitherSettingsDialog',
'PixelizationEditorDialog',
]
class ZoomableImage(tk.Canvas):
"""
A custom widget that supports zooming & panning for a displayed PIL image.
"""
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.master = master
self.original_image = None
self.displayed_image = None
self.image_id = None
self.zoom_factor = 1.0
self.offset_x = 0
self.offset_y = 0
self.pan_start_x = 0
self.pan_start_y = 0
self._auto_fit_on_resize = True
self.bind("<ButtonPress-1>", self.start_pan)
self.bind("<B1-Motion>", self.pan)
self.bind("<MouseWheel>", self.zoom)
# For Linux
self.bind("<Button-4>", self.zoom)
self.bind("<Button-5>", self.zoom)
self.bind("<Configure>", self.on_resize)
def set_image(self, image: Image.Image, update: bool = True):
"""
Set the image to display.
Args:
image: PIL Image to display
update: If True, immediately update the view. Set to False if you'll call fit_to_window() right after.
"""
self.original_image = image
self.zoom_factor = 1.0
self.offset_x = 0
self.offset_y = 0
self._auto_fit_on_resize = True
if update:
self.update_view()
def fit_to_window(self):
if not self.original_image:
return
self.update_idletasks()
cw = self.winfo_width()
ch = self.winfo_height()
iw, ih = self.original_image.size
if iw == 0 or ih == 0:
return
wr = cw / iw
hr = ch / ih
self.zoom_factor = min(wr, hr)
self.offset_x = 0
self.offset_y = 0
self._auto_fit_on_resize = True
self.update_view()
# Transparency checkerboard, in screen pixels so squares stay a constant
# size however far the user zooms in.
_CHECKER_SQUARE = 8
_CHECKER_LIGHT = (99, 99, 99)
_CHECKER_DARK = (72, 72, 72)
@classmethod
def _make_checkerboard(cls, w: int, h: int) -> Image.Image:
"""Build a w x h checkerboard by tiling a 2x2-square patch."""
s = cls._CHECKER_SQUARE
tile = np.empty((2 * s, 2 * s, 3), dtype=np.uint8)
tile[:s, :s] = cls._CHECKER_LIGHT
tile[s:, s:] = cls._CHECKER_LIGHT
tile[:s, s:] = cls._CHECKER_DARK
tile[s:, :s] = cls._CHECKER_DARK
reps = ((h + 2 * s - 1) // (2 * s), (w + 2 * s - 1) // (2 * s), 1)
return Image.fromarray(np.tile(tile, reps)[:h, :w], 'RGB')
@classmethod
def _composite_for_display(cls, image: Image.Image) -> Image.Image:
"""
Flatten a transparent image onto a checkerboard for display.
Without this, transparent regions take the canvas background and read
as black content rather than as empty space.
"""
if image.mode not in ('RGBA', 'LA', 'PA', 'P'):
return image
rgba = image.convert('RGBA')
if rgba.getchannel('A').getextrema()[0] == 255:
return image # nothing actually transparent
backdrop = cls._make_checkerboard(rgba.width, rgba.height).convert('RGBA')
return Image.alpha_composite(backdrop, rgba).convert('RGB')
def update_view(self):
if not self.original_image:
return
nw = int(self.original_image.width * self.zoom_factor)
nh = int(self.original_image.height * self.zoom_factor)
if nw <= 0 or nh <= 0:
return
resized = self.original_image.resize((nw, nh), Image.Resampling.NEAREST)
resized = self._composite_for_display(resized)
self.displayed_image = ImageTk.PhotoImage(resized)
cw = self.winfo_width()
ch = self.winfo_height()
x = (cw - nw)//2 + self.offset_x
y = (ch - nh)//2 + self.offset_y
self.delete("all")
self.image_id = self.create_image(x, y, anchor='nw', image=self.displayed_image)
def start_pan(self, event):
self.pan_start_x = event.x - self.offset_x
self.pan_start_y = event.y - self.offset_y
self._auto_fit_on_resize = False
def pan(self, event):
self.offset_x = event.x - self.pan_start_x
self.offset_y = event.y - self.pan_start_y
self._auto_fit_on_resize = False
self.update_view()
def zoom(self, event):
if not self.original_image:
return
fine = False
if hasattr(event, "state"):
fine = bool(event.state & 0x0001) # Shift key
step = 0.98 if fine else 0.9
grow = 1.02 if fine else 1.1
# Zoom out on negative delta or Button-5
if event.num == 5 or (hasattr(event, 'delta') and event.delta < 0):
self.zoom_factor *= step
else:
self.zoom_factor *= grow
self.zoom_factor = max(0.01, min(30.0, self.zoom_factor))
self._auto_fit_on_resize = False
self.update_view()
def on_resize(self, event):
if self._auto_fit_on_resize:
self.fit_to_window()
else:
self.update_view()
class PixelizationEditorCanvas(ZoomableImage):
"""
Canvas with grid overlay and pixel-editing tools.
"""
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.source_image = None
self.grid_w = 1
self.grid_h = 1
self.show_grid = True
self.mode = "preview" # "preview" or "edit"
self.tool = "brush" # "brush", "magic", "picker"
self.tool_size = 1
self.magic_threshold = 5
self.draw_color = (0, 0, 0)
self.highlight_cell = None
self.pixel_colors = []
self.history = []
self.redo = []
self._drawing_active = False
self._drawing_occurred = False
self._last_draw_cell = None
self.on_color_pick = None
self.preview_grid_scale = 1.0
self.alt_zoom_active = False
self.preview_grid_offset_x = 0.0
self.preview_grid_offset_y = 0.0
self._last_pan_event = None
self.bind("<ButtonPress-1>", self._on_left_down)
self.bind("<B1-Motion>", self._on_left_drag)
self.bind("<ButtonRelease-1>", self._on_left_up)
self.bind("<ButtonPress-3>", self._on_right_down)
self.bind("<B3-Motion>", self._on_right_drag)
self.bind("<ButtonRelease-3>", self._on_right_up)
self.bind("<Motion>", self._on_motion)
def set_mode(self, mode: str):
self.mode = mode
self.highlight_cell = None
self.update_view()
def set_source_image(self, image: Image.Image):
self.source_image = image
def set_grid(self, grid_w: int, grid_h: int):
self.grid_w = max(1, int(grid_w))
self.grid_h = max(1, int(grid_h))
self.preview_grid_scale = 1.0
self.preview_grid_offset_x = 0.0
self.preview_grid_offset_y = 0.0
if self.mode == "edit":
self._ensure_pixel_data()
self.update_view()
def set_tool(self, tool: str):
self.tool = tool
def set_tool_size(self, size: int):
self.tool_size = max(1, int(size))
self.update_view()
def set_draw_color(self, color: Tuple[int, int, int]):
self.draw_color = color
def set_magic_threshold(self, value: int):
self.magic_threshold = max(0, int(value))
def set_show_grid(self, show: bool):
self.show_grid = bool(show)
self.update_view()
def set_pixel_data(self, pixel_colors: List[List[Optional[Tuple[int, int, int]]]]):
self.pixel_colors = pixel_colors
self._reset_history()
self._update_image_from_pixels(preserve_view=False)
def get_pixel_data(self) -> List[List[Optional[Tuple[int, int, int]]]]:
return self.pixel_colors
def undo(self):
if len(self.history) <= 1:
return
state = self.history.pop()
self.redo.append(state)
self.pixel_colors = self._deep_copy_pixels(self.history[-1])
self._update_image_from_pixels(preserve_view=True)
def redo_action(self):
if not self.redo:
return
state = self.redo.pop()
self.history.append(self._deep_copy_pixels(state))
self.pixel_colors = self._deep_copy_pixels(state)
self._update_image_from_pixels(preserve_view=True)
def update_view(self):
super().update_view()
self._draw_overlays()
def _get_image_draw_rect(self) -> Optional[Tuple[int, int, int, int]]:
if not self.original_image:
return None
nw = int(self.original_image.width * self.zoom_factor)
nh = int(self.original_image.height * self.zoom_factor)
if nw <= 0 or nh <= 0:
return None
cw = self.winfo_width()
ch = self.winfo_height()
x = (cw - nw) // 2 + self.offset_x
y = (ch - nh) // 2 + self.offset_y
return x, y, nw, nh
def _get_image_transform(self) -> Optional[Tuple[int, int, float]]:
rect = self._get_image_draw_rect()
if not rect:
return None
x, y, _, _ = rect
return x, y, self.zoom_factor
def _get_preview_grid_rect(self) -> Optional[Tuple[float, float, float, float, float]]:
cw = self.winfo_width()
ch = self.winfo_height()
if cw <= 1 or ch <= 1:
return None
base_cell = min(cw / self.grid_w, ch / self.grid_h)
cell = base_cell * self.preview_grid_scale
if cell <= 0:
return None
gw = self.grid_w * cell
gh = self.grid_h * cell
x0 = (cw - gw) / 2 + self.preview_grid_offset_x
y0 = (ch - gh) / 2 + self.preview_grid_offset_y
return x0, y0, gw, gh, cell
def fit_image_to_grid(self):
if not self.original_image:
return
self.preview_grid_scale = 1.0
self.preview_grid_offset_x = 0.0
self.preview_grid_offset_y = 0.0
self._auto_fit_on_resize = True
grid_rect = self._get_preview_grid_rect()
if not grid_rect:
return
x0, y0, gw, gh, _ = grid_rect
iw, ih = self.original_image.size
if iw == 0 or ih == 0:
return
self.zoom_factor = min(gw / iw, gh / ih)
nw = iw * self.zoom_factor
nh = ih * self.zoom_factor
cw = self.winfo_width()
ch = self.winfo_height()
target_x = x0 + (gw - nw) / 2
target_y = y0 + (gh - nh) / 2
self.offset_x = target_x - (cw - nw) / 2
self.offset_y = target_y - (ch - nh) / 2
self.update_view()
@staticmethod
def _shift_down(event) -> bool:
if hasattr(event, "state"):
return bool(event.state & 0x0001)
return False
def start_pan(self, event):
self._last_pan_event = (event.x, event.y)
super().start_pan(event)
def pan(self, event):
if self.mode == "preview" and self._shift_down(event):
if self._last_pan_event:
dx = event.x - self._last_pan_event[0]
dy = event.y - self._last_pan_event[1]
self.preview_grid_offset_x += dx
self.preview_grid_offset_y += dy
self._last_pan_event = (event.x, event.y)
super().pan(event)
def on_resize(self, event):
if self._auto_fit_on_resize:
if self.mode == "preview":
self.fit_image_to_grid()
else:
self.fit_to_window()
else:
self.update_view()
def zoom(self, event):
if not self.original_image:
return
fine = False
if hasattr(event, "state"):
fine = bool(event.state & 0x0001) # Shift key
step = 0.98 if fine else 0.9
grow = 1.02 if fine else 1.1
if event.num == 5 or (hasattr(event, 'delta') and event.delta < 0):
factor = step
else:
factor = grow
self.zoom_factor *= factor
self.zoom_factor = max(0.01, min(30.0, self.zoom_factor))
if self.alt_zoom_active and self.mode == "preview":
self.preview_grid_scale *= factor
self.preview_grid_scale = max(0.1, min(10.0, self.preview_grid_scale))
self._auto_fit_on_resize = False
self.update_view()
def _draw_overlays(self):
self.delete("grid")
self.delete("highlight")
if self.grid_w <= 0 or self.grid_h <= 0:
return
if self.mode == "preview":
self._draw_preview_grid()
else:
self._draw_edit_grid()
self._draw_highlight()
def _draw_preview_grid(self):
if not self.show_grid:
return
grid_rect = self._get_preview_grid_rect()
if not grid_rect:
return
x0, y0, nw, nh, cell_w = grid_rect
cell_h = cell_w
if min(cell_w, cell_h) < 3:
return
for i in range(1, self.grid_w):
x = x0 + i * cell_w
self.create_line(x, y0, x, y0 + nh, fill="#ffffff", width=1, tags="grid", stipple="gray50")
for j in range(1, self.grid_h):
y = y0 + j * cell_h
self.create_line(x0, y, x0 + nw, y, fill="#ffffff", width=1, tags="grid", stipple="gray50")
def _draw_edit_grid(self):
if not self.show_grid:
return
rect = self._get_image_draw_rect()
if not rect:
return
x0, y0, _, _ = rect
if self.zoom_factor < 3:
return
for i in range(1, self.grid_w):
x = x0 + i * self.zoom_factor
self.create_line(x, y0, x, y0 + self.grid_h * self.zoom_factor,
fill="#ffffff", width=1, tags="grid", stipple="gray50")
for j in range(1, self.grid_h):
y = y0 + j * self.zoom_factor
self.create_line(x0, y, x0 + self.grid_w * self.zoom_factor, y,
fill="#ffffff", width=1, tags="grid", stipple="gray50")
def _draw_highlight(self):
if self.highlight_cell is None:
return
rect = self._get_image_draw_rect()
if not rect:
return
if self.tool == "picker":
return
x0, y0, _, _ = rect
i, j = self.highlight_cell
size = self.tool_size
x = x0 + i * self.zoom_factor
y = y0 + j * self.zoom_factor
w = size * self.zoom_factor
h = size * self.zoom_factor
self.create_rectangle(x, y, x + w, y + h, outline="#ff3333",
width=2, tags="highlight")
def _ensure_pixel_data(self):
if self.pixel_colors:
return
self.pixel_colors = [
[None for _ in range(self.grid_w)]
for _ in range(self.grid_h)
]
self._reset_history()
def _reset_history(self):
if not self.pixel_colors:
return
self.history = [self._deep_copy_pixels(self.pixel_colors)]
self.redo = []
def _push_history(self):
self.history.append(self._deep_copy_pixels(self.pixel_colors))
self.redo = []
@staticmethod
def _deep_copy_pixels(pixels):
return [row[:] for row in pixels]
def _update_image_from_pixels(self, preserve_view: bool):
if not self.pixel_colors:
return
img = Image.new("RGBA", (self.grid_w, self.grid_h), (0, 0, 0, 0))
px = img.load()
for j in range(self.grid_h):
for i in range(self.grid_w):
color = self.pixel_colors[j][i]
if color is None:
continue
px[i, j] = (*color, 255)
if preserve_view:
self._set_image_preserve_view(img)
else:
self.set_image(img, update=True)
def _set_image_preserve_view(self, image: Image.Image):
zoom = self.zoom_factor
ox = self.offset_x
oy = self.offset_y
auto_fit = self._auto_fit_on_resize
self.set_image(image, update=False)
self.zoom_factor = zoom
self.offset_x = ox
self.offset_y = oy
self._auto_fit_on_resize = auto_fit
self.update_view()
def _canvas_to_cell(self, x: float, y: float) -> Optional[Tuple[int, int]]:
rect = self._get_image_draw_rect()
if not rect:
return None
x0, y0, _, _ = rect
img_x = (x - x0) / self.zoom_factor
img_y = (y - y0) / self.zoom_factor
i = int(img_x)
j = int(img_y)
if i < 0 or j < 0 or i >= self.grid_w or j >= self.grid_h:
return None
return i, j
def _on_left_down(self, event):
if self.mode == "preview":
if self.tool == "picker":
self._pick_color_at_canvas(event.x, event.y)
self.update_view()
return
self.start_pan(event)
return
self._ensure_pixel_data()
cell = self._canvas_to_cell(event.x, event.y)
if not cell:
return
if self.tool == "picker":
self._pick_color_at_canvas(event.x, event.y)
self.update_view()
return
if self.tool == "magic":
self._apply_magic_wand(cell)
self._push_history()
self.update_view()
else:
self._drawing_active = True
self._last_draw_cell = cell
self._apply_brush(cell)
self._drawing_occurred = True
self.update_view()
def _on_left_drag(self, event):
if self.mode == "preview":
self.pan(event)
return
if not self._drawing_active:
return
cell = self._canvas_to_cell(event.x, event.y)
if cell:
if self._last_draw_cell is None:
self._last_draw_cell = cell
self._apply_brush_line(self._last_draw_cell, cell)
self._last_draw_cell = cell
self._drawing_occurred = True
self.update_view()
def _on_left_up(self, _event):
if self.mode == "preview":
self._last_pan_event = None
return
if self._drawing_active:
self._drawing_active = False
self._last_draw_cell = None
if self._drawing_occurred:
self._push_history()
self._drawing_occurred = False
def _on_right_down(self, event):
self.start_pan(event)
def _on_right_drag(self, event):
self.pan(event)
def _on_right_up(self, _event):
self._last_pan_event = None
return
def _on_motion(self, event):
if self.mode != "edit":
return
cell = self._canvas_to_cell(event.x, event.y)
if cell != self.highlight_cell:
self.highlight_cell = cell
self.update_view()
def _apply_brush(self, cell: Tuple[int, int]):
i0, j0 = cell
if self.tool == "brush":
color = self.draw_color
else:
return
size = self.tool_size
for dj in range(size):
for di in range(size):
i = min(self.grid_w - 1, i0 + di)
j = min(self.grid_h - 1, j0 + dj)
self.pixel_colors[j][i] = color
self._update_image_from_pixels(preserve_view=True)
def _apply_brush_line(self, start: Tuple[int, int], end: Tuple[int, int]):
x0, y0 = start
x1, y1 = end
dx = abs(x1 - x0)
dy = abs(y1 - y0)
sx = 1 if x0 < x1 else -1
sy = 1 if y0 < y1 else -1
err = dx - dy
while True:
self._apply_brush((x0, y0))
if x0 == x1 and y0 == y1:
break
e2 = err * 2
if e2 > -dy:
err -= dy
x0 += sx
if e2 < dx:
err += dx
y0 += sy
def _apply_magic_wand(self, cell: Tuple[int, int]):
i0, j0 = cell
size = max(1, int(self.tool_size))
start_i = min(self.grid_w - 1, i0)
start_j = min(self.grid_h - 1, j0)
end_i = min(self.grid_w - 1, i0 + size - 1)
end_j = min(self.grid_h - 1, j0 + size - 1)
targets = []
for j in range(start_j, end_j + 1):
for i in range(start_i, end_i + 1):
color = self.pixel_colors[j][i]
if color is None:
continue
if color not in targets:
targets.append(color)
replacement = self.draw_color
for target in targets:
if self._color_distance(target, replacement) == 0:
continue
start_cell = self._find_cell_with_color(start_i, start_j, end_i, end_j, target)
if start_cell:
self._flood_fill_from(start_cell, target, replacement)
self._update_image_from_pixels(preserve_view=True)
def _find_cell_with_color(self, start_i, start_j, end_i, end_j, target):
for j in range(start_j, end_j + 1):
for i in range(start_i, end_i + 1):
color = self.pixel_colors[j][i]
if color is not None and color == target:
return (i, j)
return None
def _flood_fill_from(self, cell: Tuple[int, int], target: Tuple[int, int, int], replacement: Tuple[int, int, int]):
i, j = cell
threshold = self.magic_threshold
stack = [(i, j)]
visited = set()
while stack:
ci, cj = stack.pop()
if (ci, cj) in visited:
continue
visited.add((ci, cj))
if ci < 0 or cj < 0 or ci >= self.grid_w or cj >= self.grid_h:
continue
color = self.pixel_colors[cj][ci]
if color is None:
continue
if self._color_distance(color, target) > threshold:
continue
self.pixel_colors[cj][ci] = replacement
stack.extend([
(ci - 1, cj), (ci + 1, cj),
(ci, cj - 1), (ci, cj + 1)
])
def _pick_color_at_canvas(self, x: float, y: float):
color = None
if self.mode == "edit" and self.pixel_colors:
cell = self._canvas_to_cell(x, y)
if cell:
i, j = cell
color = self.pixel_colors[j][i]
if color is None and self.source_image is not None:
transform = self._get_image_transform()
if transform:
origin_x, origin_y, scale = transform
ox = int((x - origin_x) / scale)
oy = int((y - origin_y) / scale)
ox = max(0, min(self.source_image.width - 1, ox))
oy = max(0, min(self.source_image.height - 1, oy))
color = self.source_image.getpixel((ox, oy))[:3]
if color is None:
return
self.draw_color = color
if self.on_color_pick:
self.on_color_pick(color)
@staticmethod
def _color_distance(c1: Tuple[int, int, int], c2: Tuple[int, int, int]) -> float:
dr = c1[0] - c2[0]
dg = c1[1] - c2[1]
db = c1[2] - c2[2]
return (dr * dr + dg * dg + db * db) ** 0.5
class PalettePreview(ctk.CTkFrame):
"""
Shows a small horizontal bar for each color in the palette.
"""
def __init__(self, master, palette, width=200, height=30, **kwargs):
super().__init__(master, width=width, height=height, **kwargs)
self.palette = palette
self.canvas = tk.Canvas(self, width=width, height=height, highlightthickness=0)
self.canvas.pack(fill="both", expand=True)
self.after(100, self.draw_palette)
self.bind("<Configure>", lambda ev: self.after(100, self.draw_palette))
def draw_palette(self):
self.canvas.delete("all")
self.canvas.update_idletasks()
w = self.canvas.winfo_width()
h = self.canvas.winfo_height()
n = len(self.palette)
if n == 0:
return
seg_w = w / n
for i, color in enumerate(self.palette):
x1 = i*seg_w
x2 = (i+1)*seg_w
hx = f'#{color[0]:02x}{color[1]:02x}{color[2]:02x}'
self.canvas.create_rectangle(x1, 0, x2, h, fill=hx, outline='')
class ProgressDialog(ctk.CTkToplevel):
"""
Modal dialog showing progress bar and status message.
"""
def __init__(self, parent, title="Processing"):
super().__init__(parent)
self.title(title)
self.geometry("500x150")
self.resizable(False, False)
self.grab_set()
# Center on parent
self.update_idletasks()
x = parent.winfo_x() + (parent.winfo_width() // 2) - (500 // 2)
y = parent.winfo_y() + (parent.winfo_height() // 2) - (150 // 2)
self.geometry(f"+{x}+{y}")
# Status label
self.status_label = ctk.CTkLabel(
self,
text="Initializing...",
font=("Arial", 14)
)
self.status_label.pack(pady=(20, 10))
# Progress bar
self.progress_bar = ctk.CTkProgressBar(self, width=400)
self.progress_bar.pack(pady=10)
self.progress_bar.set(0)
# Percentage label
self.percent_label = ctk.CTkLabel(
self,
text="0%",
font=("Arial", 12)
)
self.percent_label.pack(pady=5)
# Cancel button
self.cancelled = False
self.cancel_button = ctk.CTkButton(
self,
text="Cancel",
command=self.cancel,
width=100
)
self.cancel_button.pack(pady=10)
self.protocol("WM_DELETE_WINDOW", self.cancel)
def update_progress(self, fraction: float, message: str = ""):
"""Update progress bar and status message."""
self.progress_bar.set(fraction)
self.percent_label.configure(text=f"{int(fraction * 100)}%")
if message:
self.status_label.configure(text=message)
self.update()
def cancel(self):
"""Mark as cancelled and close."""
self.cancelled = True
self.destroy()
def is_cancelled(self) -> bool:
"""Check if user cancelled the operation."""
return self.cancelled
class ColorPickerGrid(ctk.CTkFrame):
"""
Grid of color swatches that can be clicked to edit.
"""
def __init__(self, master, colors: List[Tuple[int, int, int]],
on_color_change: Callable[[int, Tuple[int, int, int]], None],
**kwargs):
super().__init__(master, **kwargs)
self.colors = colors
self.on_color_change = on_color_change
self.color_buttons = []
self.build_grid()
def build_grid(self):
"""Build the grid of color swatches."""
cols = min(8, len(self.colors))
rows = (len(self.colors) + cols - 1) // cols
for i, color in enumerate(self.colors):
row = i // cols
col = i % cols
hex_color = f'#{color[0]:02x}{color[1]:02x}{color[2]:02x}'
btn = tk.Button(
self,
bg=hex_color,
width=4,
height=2,
relief="raised",
bd=2,
command=lambda idx=i, c=color: self.edit_color(idx, c)
)
btn.grid(row=row, column=col, padx=2, pady=2)
self.color_buttons.append(btn)
def edit_color(self, index: int, current_color: Tuple[int, int, int]):
"""Open color picker to edit a color."""
from tkinter import colorchooser
hex_color = f'#{current_color[0]:02x}{current_color[1]:02x}{current_color[2]:02x}'
result = colorchooser.askcolor(
color=hex_color,
title=f"Edit Color {index + 1}",
parent=self
)
if result and result[0]:
# result[0] is RGB tuple as floats
new_color = tuple(int(c) for c in result[0])
self.colors[index] = new_color
# Update button color
hex_new = f'#{new_color[0]:02x}{new_color[1]:02x}{new_color[2]:02x}'
self.color_buttons[index].configure(bg=hex_new)
# Notify callback
self.on_color_change(index, new_color)
def get_colors(self) -> List[Tuple[int, int, int]]:
"""Get current color list."""
return self.colors
class StatusBar(ctk.CTkFrame):
"""
Status bar to show information at the bottom of the window.
Supports animated spinners for processing states.
"""
def __init__(self, master, spinner_name: str = "dots", **kwargs):
super().__init__(master, height=30, **kwargs)
self.label = ctk.CTkLabel(
self,
text="Ready",
anchor="w"
)
self.label.pack(side="left", padx=10, fill="x", expand=True)
# Spinner state
self.spinner_active = False
self.spinner_frames = []
self.spinner_interval = 80
self.spinner_index = 0
self.spinner_message = ""
self.spinner_after_id = None
# Load spinner configuration
self._load_spinner(spinner_name)
def _load_spinner(self, spinner_name: str):
"""Load spinner configuration from spinners.json."""
try:
import json
from pathlib import Path
# Look for spinners.json in the same directory as this file
spinner_file = Path(__file__).parent / "spinners.json"
if spinner_file.exists():
with open(spinner_file, 'r', encoding='utf-8') as f:
spinners = json.load(f)
if spinner_name in spinners:
spinner_config = spinners[spinner_name]
self.spinner_frames = spinner_config.get('frames', ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'])
self.spinner_interval = spinner_config.get('interval', 80)
else:
# Default fallback
self.spinner_frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
self.spinner_interval = 80
else:
# Default fallback if file not found
self.spinner_frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
self.spinner_interval = 80
except Exception as e:
print(f"Error loading spinner: {e}")
# Simple fallback
self.spinner_frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
self.spinner_interval = 80
def set_status(self, message: str, spinning: bool = False):
"""
Update status message.
Args:
message: The status message to display
spinning: If True, starts animated spinner. If False, stops any active spinner.
"""
if spinning:
self.start_spinner(message)
else:
self.stop_spinner()
self.label.configure(text=message)
self.update()
def start_spinner(self, message: str):
"""Start the animated spinner with the given message."""
self.spinner_message = message
self.spinner_active = True
self.spinner_index = 0
self._animate_spinner()
def stop_spinner(self):
"""Stop the animated spinner."""
self.spinner_active = False
if self.spinner_after_id is not None:
self.after_cancel(self.spinner_after_id)
self.spinner_after_id = None
def _animate_spinner(self):
"""Internal method to animate the spinner."""
if not self.spinner_active:
return
frame = self.spinner_frames[self.spinner_index]
self.label.configure(text=f"{frame} {self.spinner_message}")
self.update()
self.spinner_index = (self.spinner_index + 1) % len(self.spinner_frames)
self.spinner_after_id = self.after(self.spinner_interval, self._animate_spinner)
class ImageComparisonView(ctk.CTkFrame):
"""
Side-by-side comparison of two images with synchronized zooming.
"""
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(1, weight=1)
self.grid_rowconfigure(0, weight=0)
self.grid_rowconfigure(1, weight=1)
# Labels
self.left_label = ctk.CTkLabel(self, text="Original")
self.left_label.grid(row=0, column=0, pady=5)
self.right_label = ctk.CTkLabel(self, text="Processed")
self.right_label.grid(row=0, column=1, pady=5)
# Image viewers
self.left_viewer = ZoomableImage(self, bg="gray20", highlightthickness=0)
self.left_viewer.grid(row=1, column=0, sticky="nsew", padx=(0, 5))
self.right_viewer = ZoomableImage(self, bg="gray20", highlightthickness=0)
self.right_viewer.grid(row=1, column=1, sticky="nsew", padx=(5, 0))
def set_images(self, left_image: Image.Image, right_image: Image.Image):
"""Set the images to display."""
self.left_viewer.set_image(left_image)
self.right_viewer.set_image(right_image)
# -------------------- HSV Color Picker Dialog --------------------