-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimg-txt_viewer.py
3041 lines (2608 loc) · 149 KB
/
img-txt_viewer.py
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
"""
########################################
# IMG-TXT VIEWER #
# Version : v1.96 #
# Author : github.com/Nenotriple #
########################################
Description:
-------------
Display an image and text file side-by-side for easy manual caption editing.
More info here: https://github.com/Nenotriple/img-txt_viewer
"""
################################################################################################################################################
#region - Imports
# Standard Library
import os
import re
import csv
import sys
import glob
import time
import shutil
import ctypes
import zipfile
import subprocess
# Standard Library - GUI
from tkinter import (
ttk, Tk, messagebox, filedialog, simpledialog,
StringVar, BooleanVar, IntVar,
Frame, PanedWindow, Menu, scrolledtext,
Label, Text,
Event, TclError
)
# Third-Party Libraries
import numpy
from TkToolTip.TkToolTip import TkToolTip as ToolTip
from PIL import Image, ImageTk, ImageSequence, ImageOps, UnidentifiedImageError
# Custom Libraries
from main.scripts import (
about_img_txt_viewer,
calculate_file_stats,
batch_resize_images,
batch_crop_images,
settings_manager,
batch_tag_edit,
find_dupe_file,
text_controller,
upscale_image,
resize_image,
image_grid,
edit_panel,
CropUI,
)
from main.scripts.Autocomplete import SuggestionHandler
from main.scripts.PopUpZoom import PopUpZoom as PopUpZoom
from main.scripts.OnnxTagger import OnnxTagger as OnnxTagger
#endregion
################################################################################################################################################
#region CLS: ImgTxtViewer
class ImgTxtViewer:
def __init__(self, root):
self.app_version = "v1.96"
self.root = root
self.application_path = self.get_app_path()
self.set_appid()
self.setup_window()
self.set_icon()
self.initial_class_setup()
self.define_app_settings()
self.setup_general_binds()
self.create_menu_bar()
self.create_primary_ui()
self.settings_manager.read_settings()
#endregion
################################################################################################################################################
#region - Setup
def initial_class_setup(self):
# Setup tools
self.about_window = about_img_txt_viewer.AboutWindow(self, self.root, self.blank_image)
self.settings_manager = settings_manager.SettingsManager(self, self.root)
self.stat_calculator = calculate_file_stats.CalculateFileStats(self, self.root)
self.batch_resize_images = batch_resize_images.BatchResizeImages()
self.edit_panel = edit_panel.EditPanel(self, self.root)
self.batch_tag_edit = batch_tag_edit.BatchTagEdit()
self.find_dupe_file = find_dupe_file.FindDupeFile()
self.crop_ui = CropUI.CropInterface()
self.onnx_tagger = OnnxTagger(self)
self.autocomplete = SuggestionHandler(self)
self.text_controller = text_controller.TextController(self, self.root)
# Setup UI state
self.ui_state = "ImgTxtViewer"
# Window drag variables
self.drag_x = None
self.drag_y = None
# Navigation variables
self.last_scroll_time = 0
self.prev_num_files = 0
self.current_index = 0
# Text tools
self.search_string_var = StringVar()
self.replace_string_var = StringVar()
self.prefix_string_var = StringVar()
self.append_string_var = StringVar()
self.custom_highlight_string_var = StringVar()
# Filter variables
self.original_image_files = []
self.original_text_files = []
self.filter_string_var = StringVar()
# File lists
self.text_files = []
self.image_files = []
self.deleted_pairs = []
self.new_text_files = []
self.thumbnail_cache = {}
self.image_info_cache = {}
# Misc variables
self.about_window_open = False
self.panes_swap_ew_var = BooleanVar(value=False)
self.panes_swap_ns_var = BooleanVar(value=False)
self.text_modified_var = False
self.is_alt_arrow_pressed = False
self.filepath_contains_images_var = False
self.toggle_zoom_var = None
self.undo_state = StringVar(value="disabled")
self.previous_window_size = (self.root.winfo_width(), self.root.winfo_height())
self.initialize_text_pane = True
# 'after()' Job IDs
self.is_resizing_job_id = None
self.delete_tag_job_id = None
self.animation_job_id = None
self.update_thumbnail_job_id = None
# Image Resize Variables
self.current_image = None # ImageTk.PhotoImage object
self.original_image = None # ImageTk.PhotoImage object
self.current_max_img_height = None
self.current_max_img_width = None
# GIF animation variables
self.gif_frames = []
self.gif_frame_cache = {}
self.frame_durations = []
self.current_frame = 0
self.current_gif_frame_image = None
# Color Palette
self.pastel_colors = [
"#a2d2ff", "#ffafcf", "#aec3ae", "#ebe3d5", "#beadfa",
"#cdf5fd", "#fdcedf", "#c3edc0", "#d6c7ae", "#dfccfb",
"#c0dbea", "#f2d8d8", "#cbffa9", "#f9f3cc", "#acb1d6",
"#a1ccd1", "#dba39a", "#c4d7b2", "#ffd9b7", "#d9acf5",
"#7895b2", "#ff8787", "#90a17d", "#f8c4b4", "#af7ab3"
] # Blue Pink Green Brown Purple
# --------------------------------------
# Settings
# --------------------------------------
def define_app_settings(self):
# Misc Settings
self.app_settings_cfg = 'settings.cfg'
self.my_tags_csv = 'my_tags.csv'
self.onnx_models_dir = "onnx_models"
self.image_dir = StringVar(value="Choose Directory...")
self.text_dir = ""
self.external_image_editor_path = "mspaint"
self.always_on_top_var = BooleanVar(value=False)
self.big_save_button_var = BooleanVar(value=True)
# Font Settings
self.font_var = StringVar(value="Courier New")
self.font_size_var = IntVar(value=10)
# List Mode Settings
self.list_mode_var = BooleanVar(value=False)
self.cleaning_text_var = BooleanVar(value=True)
# Auto Save Settings
self.auto_save_var = BooleanVar(value=False)
self.auto_delete_blank_files_var = BooleanVar(value=False)
# Highlight Settings
self.highlight_selection_var = BooleanVar(value=True)
self.highlight_use_regex_var = BooleanVar(value=False)
self.highlight_all_duplicates_var = BooleanVar(value=False)
self.truncate_stat_captions_var = BooleanVar(value=True)
self.search_and_replace_regex_var = BooleanVar(value=False)
# Image Stats Settings
self.process_image_stats_var = BooleanVar(value=False)
self.use_mytags_var = BooleanVar(value=True)
# Filter Settings
self.filter_empty_files_var = BooleanVar(value=False)
self.filter_use_regex_var = BooleanVar(value=False)
# Load Order Settings
self.load_order_var = StringVar(value="Name (default)")
self.reverse_load_order_var = BooleanVar(value=False)
# Thumbnail Panel
self.thumbnails_visible = BooleanVar(value=True)
self.thumbnail_width = IntVar(value=50)
# Edit Panel
self.edit_panel_visible_var = BooleanVar(value=False)
# Image Quality
self.image_quality_var = StringVar(value="Normal")
self.quality_max_size = 1280
self.quality_filter = Image.BILINEAR
Image.MAX_IMAGE_PIXELS = 300000000 # ~(17320x17320)px
# Autocomplete
self.csv_danbooru = BooleanVar(value=False)
self.csv_danbooru_safe = BooleanVar(value=False)
self.csv_derpibooru = BooleanVar(value=False)
self.csv_e621 = BooleanVar(value=False)
self.csv_english_dictionary = BooleanVar(value=False)
self.colored_suggestion_var = BooleanVar(value=True)
self.suggestion_quantity_var = IntVar(value=4)
self.suggestion_threshold_var = StringVar(value="Normal")
self.last_word_match_var = BooleanVar(value=False)
# --------------------------------------
# Bindings
# --------------------------------------
def setup_general_binds(self):
self.root.bind("<Control-f>", lambda event: self.toggle_highlight_all_duplicates())
self.root.bind("<Control-s>", lambda event: self.save_text_file(highlight=True))
self.root.bind("<Alt-Right>", lambda event: self.next_pair(event))
self.root.bind("<Alt-Left>", lambda event: self.prev_pair(event))
self.root.bind('<Shift-Delete>', lambda event: self.delete_pair())
self.root.bind('<Configure>', self.handle_window_configure)
self.root.bind('<F1>', lambda event: self.toggle_zoom_popup(event))
self.root.bind('<F2>', lambda event: self.open_image_grid(event))
self.root.bind('<F4>', lambda event: self.open_image_in_editor(event))
self.root.bind('<F5>', lambda event: self.show_batch_tag_edit(event))
self.root.bind('<Control-w>', lambda event: self.on_closing(event))
# Display window size on resize:
#self.root.bind("<Configure>", lambda event: print(f"\rWindow size (W,H): {event.width},{event.height} ", end='') if event.widget == self.root else None, add="+")
#endregion
################################################################################################################################################
#region - Menubar
def create_menu_bar(self):
self.initialize_menu()
self.create_options_menu()
self.create_tools_menu()
# --------------------------------------
# Initialize Menu Bar
# --------------------------------------
def initialize_menu(self):
# Main
menubar = Menu(self.root)
self.root.config(menu=menubar)
# Options
self.optionsMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Options", underline=0, menu=self.optionsMenu)
# Tools
self.toolsMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Tools", underline=0, menu=self.toolsMenu)
# About
menubar.add_command(label="About", underline=0, command=self.toggle_about_window)
# --------------------------------------
# Options
# --------------------------------------
def create_options_menu(self):
# Options
self.options_subMenu = Menu(self.optionsMenu, tearoff=0)
self.optionsMenu.add_cascade(label="Options", underline=0, state="disable", menu=self.options_subMenu)
self.options_subMenu.add_checkbutton(label="Clean-Text", underline=0, variable=self.cleaning_text_var, command=self.toggle_list_menu)
self.options_subMenu.add_checkbutton(label="Auto-Delete Blank Files", underline=0, variable=self.auto_delete_blank_files_var)
self.options_subMenu.add_checkbutton(label="Colored Suggestions", underline=1, variable=self.colored_suggestion_var, command=self.autocomplete.update_autocomplete_dictionary)
self.options_subMenu.add_checkbutton(label="Highlight Selection", underline=0, variable=self.highlight_selection_var)
self.options_subMenu.add_checkbutton(label="Big Save Button", underline=0, variable=self.big_save_button_var, command=self.toggle_save_button_height)
self.options_subMenu.add_checkbutton(label="List View", underline=0, variable=self.list_mode_var, command=self.toggle_list_mode)
self.options_subMenu.add_separator()
self.options_subMenu.add_checkbutton(label="Always On Top", underline=0, variable=self.always_on_top_var, command=self.set_always_on_top)
self.options_subMenu.add_checkbutton(label="Toggle Zoom", accelerator="F1", variable=self.toggle_zoom_var, command=self.toggle_zoom_popup)
self.options_subMenu.add_checkbutton(label="Toggle Thumbnail Panel", variable=self.thumbnails_visible, command=self.update_thumbnail_panel)
self.options_subMenu.add_checkbutton(label="Toggle Edit Panel", variable=self.edit_panel_visible_var, command=self.edit_panel.toggle_edit_panel)
self.options_subMenu.add_checkbutton(label="Vertical View", underline=0, variable=self.panes_swap_ns_var, command=self.swap_pane_orientation)
self.options_subMenu.add_checkbutton(label="Swap img-txt Sides", underline=0, variable=self.panes_swap_ew_var, command=self.swap_pane_sides)
self.options_subMenu.add_command(label="Set Default Image Editor", underline=0, command=self.set_external_image_editor_path)
# Image Display Quality Menu
image_quality_menu = Menu(self.options_subMenu, tearoff=0)
self.options_subMenu.add_cascade(label="Image Display Quality", underline=1, menu=image_quality_menu)
for value in ["High", "Normal", "Low"]:
image_quality_menu.add_radiobutton(label=value, variable=self.image_quality_var, value=value, command=self.set_image_quality)
# --------------------------------------
# Loading Order
# --------------------------------------
# Loading Order Menu
load_order_menu = Menu(self.optionsMenu, tearoff=0)
self.optionsMenu.add_cascade(label="Loading Order", underline=6, state="disable", menu=load_order_menu)
# Loading Order Options
order_options = ["Name (default)", "File size", "Date created", "Extension", "Last Access time", "Last write time"]
for option in order_options:
load_order_menu.add_radiobutton(label=option, variable=self.load_order_var, value=option, command=self.load_pairs)
# Loading Order Direction
load_order_menu.add_separator()
load_order_menu.add_radiobutton(label="Ascending", variable=self.reverse_load_order_var, value=False, command=self.load_pairs)
load_order_menu.add_radiobutton(label="Descending", variable=self.reverse_load_order_var, value=True, command=self.load_pairs)
# --------------------------------------
# Autocomplete
# --------------------------------------
# Autocomplete Settings Menu
autocompleteSettingsMenu = Menu(self.optionsMenu, tearoff=0)
self.optionsMenu.add_cascade(label="Autocomplete", underline=11, state="disable", menu=autocompleteSettingsMenu)
# Suggestion Dictionary Menu
dictionaryMenu = Menu(autocompleteSettingsMenu, tearoff=0)
autocompleteSettingsMenu.add_cascade(label="Dictionary", underline=11, menu=dictionaryMenu)
dictionaryMenu.add_checkbutton(label="English Dictionary", underline=0, variable=self.csv_english_dictionary, command=self.autocomplete.update_autocomplete_dictionary)
dictionaryMenu.add_checkbutton(label="Danbooru", underline=0, variable=self.csv_danbooru, command=self.autocomplete.update_autocomplete_dictionary)
dictionaryMenu.add_checkbutton(label="Danbooru (Safe)", underline=0, variable=self.csv_danbooru_safe, command=self.autocomplete.update_autocomplete_dictionary)
dictionaryMenu.add_checkbutton(label="Derpibooru", underline=0, variable=self.csv_derpibooru, command=self.autocomplete.update_autocomplete_dictionary)
dictionaryMenu.add_checkbutton(label="e621", underline=0, variable=self.csv_e621, command=self.autocomplete.update_autocomplete_dictionary)
dictionaryMenu.add_separator()
dictionaryMenu.add_command(label="Clear Selection", underline=0, command=self.autocomplete.clear_dictionary_csv_selection)
# Suggestion Threshold Menu
suggestion_threshold_menu = Menu(autocompleteSettingsMenu, tearoff=0)
autocompleteSettingsMenu.add_cascade(label="Threshold", underline=11, menu=suggestion_threshold_menu)
for level in ["Slow", "Normal", "Fast", "Faster"]:
suggestion_threshold_menu.add_radiobutton(label=level, variable=self.suggestion_threshold_var, value=level, command=self.autocomplete.set_suggestion_threshold)
# Suggestion Quantity Menu
suggestion_quantity_menu = Menu(autocompleteSettingsMenu, tearoff=0)
autocompleteSettingsMenu.add_cascade(label="Quantity", underline=11, menu=suggestion_quantity_menu)
for quantity in range(0, 10):
suggestion_quantity_menu.add_radiobutton(label=str(quantity), variable=self.suggestion_quantity_var, value=quantity, command=lambda suggestion_quantity=quantity: self.autocomplete.set_suggestion_quantity(suggestion_quantity))
# Match Mode Menu
match_mode_menu = Menu(autocompleteSettingsMenu, tearoff=0)
autocompleteSettingsMenu.add_cascade(label="Match Mode", menu=match_mode_menu)
match_modes = {"Match Whole String": False, "Match Last Word": True}
for mode, value in match_modes.items():
match_mode_menu.add_radiobutton(label=mode, variable=self.last_word_match_var, value=value)
# --------------------------------------
# Open/Reset Settings
# --------------------------------------
# Settings Menu
self.optionsMenu.add_separator()
self.optionsMenu.add_command(label="Reset Settings", underline=1, state="disable", command=self.settings_manager.reset_settings)
self.optionsMenu.add_command(label="Open Settings File...", underline=1, command=lambda: self.open_textfile(self.app_settings_cfg))
self.optionsMenu.add_command(label="Open MyTags File...", underline=1, command=lambda: self.open_textfile(self.my_tags_csv))
# --------------------------------------
# Batch Operations
# --------------------------------------
def create_tools_menu(self):
self.batch_operations_menu = Menu(self.toolsMenu, tearoff=0)
self.toolsMenu.add_cascade(label="Batch Operations", underline=0, state="disable", menu=self.batch_operations_menu)
self.batch_operations_menu.add_command(label="Batch Rename And/Or Convert...", underline=3, command=self.rename_and_convert_pairs)
self.batch_operations_menu.add_command(label="Batch Resize Images...", underline=10, command=self.show_batch_resize_images)
self.batch_operations_menu.add_command(label="Batch Crop Images...", underline=8, command=self.batch_crop_images)
self.batch_operations_menu.add_command(label="Batch Tag Edit...", underline=0, accelerator="F5", command=self.show_batch_tag_edit)
self.batch_operations_menu.add_command(label="Batch Upscale...", underline=0, command=lambda: self.upscale_image(batch=True))
self.batch_operations_menu.add_separator()
self.batch_operations_menu.add_command(label="Zip Dataset...", underline=0, command=self.archive_dataset)
self.batch_operations_menu.add_command(label="Find Duplicate Files...", underline=0, command=self.show_find_dupe_file)
self.batch_operations_menu.add_command(label="Cleanup All Text Files...", underline=1, command=self.cleanup_all_text_files)
self.batch_operations_menu.add_command(label="Create Blank Text Pairs...", underline=0, command=self.create_blank_text_files)
self.batch_operations_menu.add_command(label="Create Wildcard From Captions...", underline=0, command=self.collate_captions)
# --------------------------------------
# Individual Operations
# --------------------------------------
self.individual_operations_menu = Menu(self.toolsMenu, tearoff=0)
self.toolsMenu.add_cascade(label="Edit Current pair", underline=0, state="disable", menu=self.individual_operations_menu)
self.individual_operations_menu.add_command(label="Rename Pair", underline=0, command=self.manually_rename_single_pair)
self.individual_operations_menu.add_command(label="Upscale...", underline=0, command=lambda: self.upscale_image(batch=False))
self.individual_operations_menu.add_command(label="Crop...", underline=0, command=self.show_crop_ui)
self.individual_operations_menu.add_command(label="Resize...", underline=0, command=self.resize_image)
self.individual_operations_menu.add_command(label="Expand", underline=1, command=self.expand_image)
self.individual_operations_menu.add_command(label="Rotate", underline=1, command=self.rotate_current_image)
self.individual_operations_menu.add_command(label="Flip", underline=1, command=self.flip_current_image)
self.individual_operations_menu.add_separator()
self.individual_operations_menu.add_command(label="Duplicate img-txt Pair", underline=2, command=self.duplicate_pair)
self.individual_operations_menu.add_command(label="Delete img-txt Pair", accelerator="Shift+Del", command=self.delete_pair)
self.individual_operations_menu.add_command(label="Undo Delete", underline=0, state="disable", command=self.undo_delete_pair)
# --------------------------------------
# Misc
# --------------------------------------
self.toolsMenu.add_separator()
self.toolsMenu.add_command(label="Open Current Directory...", state="disable", underline=13, command=self.open_image_directory)
self.toolsMenu.add_command(label="Open Current Image...", state="disable", underline=13, command=self.open_image)
self.toolsMenu.add_command(label="Edit Image...", state="disable", underline=6, accelerator="F4", command=self.open_image_in_editor)
self.toolsMenu.add_separator()
self.toolsMenu.add_command(label="Next Empty Text File", state="disable", accelerator="Ctrl+E", command=self.index_goto_next_empty)
self.toolsMenu.add_command(label="Open Image-Grid...", state="disable", accelerator="F2", underline=11, command=self.open_image_grid)
#endregion
################################################################################################################################################
#region - Create Primary UI
def create_primary_ui(self):
self.setup_primary_frames()
self.create_primary_widgets()
def setup_primary_frames(self):
# Configure the grid weights for the master window frame
self.root.grid_rowconfigure(0, weight=1)
self.root.grid_columnconfigure(0, weight=1)
# primary_paned_window : is used to contain the ImgTxtViewer UI.
self.primary_paned_window = PanedWindow(self.root, orient="horizontal", sashwidth=6, bg="#d0d0d0", bd=0)
self.primary_paned_window.grid(row=0, column=0, sticky="nsew")
self.primary_paned_window.bind("<B1-Motion>", self.disable_button)
# master_image_frame : is exclusively used for the displayed image, thumbnails, image info.
self.master_image_frame = Frame(self.root)
self.master_image_frame.bind('<Configure>', lambda event: self.debounce_update_thumbnail_panel(event))
self.master_image_frame.grid_rowconfigure(1, weight=1)
self.master_image_frame.grid_columnconfigure(0, weight=1)
self.primary_paned_window.add(self.master_image_frame, stretch="always")
# master_control_frame : serves as a container for all primary UI frames, with the exception of the master_image_frame.
self.master_control_frame = Frame(self.root)
self.primary_paned_window.add(self.master_control_frame, stretch="always")
self.primary_paned_window.paneconfigure(self.master_control_frame, minsize=300)
self.primary_paned_window.update()
self.primary_paned_window.sash_place(0, 0, 0)
def create_primary_widgets(self):
# Image stats
self.stats_frame = Frame(self.master_image_frame)
self.stats_frame.grid(row=0, column=0, sticky="ew")
# View Menu
self.view_menubutton = ttk.Menubutton(self.stats_frame, text="View", state="disable")
self.view_menubutton.grid(row=0, column=0)
self.view_menu = Menu(self.view_menubutton, tearoff=0)
self.view_menubutton.config(menu=self.view_menu)
self.view_menu.add_checkbutton(label="Toggle Zoom", accelerator="F1", variable=self.toggle_zoom_var, command=self.toggle_zoom_popup)
self.view_menu.add_checkbutton(label="Toggle Thumbnail Panel", variable=self.thumbnails_visible, command=self.update_thumbnail_panel)
self.view_menu.add_checkbutton(label="Toggle Edit Panel", variable=self.edit_panel_visible_var, command=self.edit_panel.toggle_edit_panel)
self.view_menu.add_checkbutton(label="Vertical View", underline=0, variable=self.panes_swap_ns_var, command=self.swap_pane_orientation)
self.view_menu.add_checkbutton(label="Swap img-txt Sides", underline=0, variable=self.panes_swap_ew_var, command=self.swap_pane_sides)
image_quality_menu = Menu(self.optionsMenu, tearoff=0)
self.view_menu.add_cascade(label="Image Display Quality", menu=image_quality_menu)
for value in ["High", "Normal", "Low"]:
image_quality_menu.add_radiobutton(label=value, variable=self.image_quality_var, value=value, command=self.set_image_quality)
# Image Stats
self.label_image_stats = Label(self.stats_frame, text="...")
self.label_image_stats.grid(row=0, column=1, sticky="ew")
# Primary Image
self.primary_display_image = Label(self.master_image_frame, cursor="hand2")
self.primary_display_image.grid(row=1, column=0, sticky="nsew")
self.primary_display_image.bind("<Double-1>", lambda event: self.open_image(index=self.current_index, event=event))
self.primary_display_image.bind('<Button-2>', self.open_image_directory)
self.primary_display_image.bind("<MouseWheel>", self.mouse_scroll)
self.primary_display_image.bind("<Button-3>", self.show_image_context_menu)
self.primary_display_image.bind("<ButtonPress-1>", self.start_drag)
self.primary_display_image.bind("<ButtonRelease-1>", self.stop_drag)
self.primary_display_image.bind("<B1-Motion>", self.dragging_window)
self.popup_zoom = PopUpZoom(self.primary_display_image)
self.toggle_zoom_var = BooleanVar(value=self.popup_zoom.zoom_enabled.get())
self.image_preview_tooltip = ToolTip.create(self.primary_display_image, "Right-Click for more\nMiddle-click to open in file explorer\nDouble-Click to open in your system image viewer\nALT+Left/Right or Mouse-Wheel to move between pairs", 1000, 6, 12)
# Thumbnail Panel
self.set_custom_ttk_button_highlight_style()
self.thumbnail_panel = Frame(self.master_image_frame)
self.thumbnail_panel.grid(row=3, column=0, sticky="ew")
self.thumbnail_panel.bind("<MouseWheel>", self.mouse_scroll)
# Edit Image Panel
self.edit_image_panel = Frame(self.master_image_frame, relief="ridge", bd=1)
self.edit_image_panel.grid(row=2, column=0, sticky="ew")
self.edit_image_panel.grid_remove()
# Directory Selection
directory_frame = Frame(self.master_control_frame)
directory_frame.pack(side="top", fill="x", padx=(0,2))
self.text_path_indicator = Label(directory_frame)
self.text_path_indicator.pack(side="left", fill="y", pady=2)
self.text_path_tooltip = ToolTip.create(self.text_path_indicator, "Text Path: Same as image path", 10, 6, 12)
self.directory_entry = ttk.Entry(directory_frame, textvariable=self.image_dir)
self.directory_entry.pack(side="left", fill="both", expand=True, pady=2)
self.directory_entry.bind('<Return>', self.set_working_directory)
self.directory_entry.bind("<Double-1>", lambda event: self.text_controller.custom_select_word_for_entry(event))
self.directory_entry.bind("<Triple-1>", lambda event: self.text_controller.select_all_in_entry(event))
self.directory_entry.bind("<Button-3>", self.open_directory_context_menu)
self.directory_entry.bind("<Button-1>", self.clear_directory_entry_on_click)
self.dir_context_menu = Menu(self.directory_entry, tearoff=0)
self.dir_context_menu.add_command(label="Cut", command=self.directory_cut)
self.dir_context_menu.add_command(label="Copy", command=self.directory_copy)
self.dir_context_menu.add_command(label="Paste", command=self.directory_paste)
self.dir_context_menu.add_command(label="Delete", command=self.directory_delete)
self.dir_context_menu.add_command(label="Clear", command=self.directory_clear)
self.dir_context_menu.add_separator()
self.dir_context_menu.add_command(label="Set Text File Path...", state="disabled", command=self.set_text_file_path)
self.dir_context_menu.add_command(label="Reset Text Path To Image Path", state="disabled", command=lambda: self.set_text_file_path(self.image_dir.get()))
self.browse_button = ttk.Button(directory_frame, text="Browse...", width=8, takefocus=False, command=self.choose_working_directory)
self.browse_button.pack(side="left", pady=2)
ToolTip.create(self.browse_button, "Right click to set an alternate path for text files", 250, 6, 12)
self.browse_context_menu = Menu(self.browse_button, tearoff=0)
self.browse_context_menu.add_command(label="Set Text File Path...", state="disabled", command=self.set_text_file_path)
self.browse_context_menu.add_command(label="Reset Text Path To Image Path", state="disabled", command=lambda: self.set_text_file_path(self.image_dir.get()))
self.browse_button.bind("<Button-3>", self.open_browse_context_menu)
self.open_button = ttk.Button(directory_frame, text="Open", width=8, takefocus=False, command=lambda: self.open_directory(self.directory_entry.get()))
self.open_button.pack(side="left", pady=2)
# Image Index
self.index_frame = Frame(self.master_control_frame, relief="raised")
self.index_frame.pack(side="top", fill="x", padx=2)
self.index_pair_label = Label(self.index_frame, text="Pair", state="disabled")
self.index_pair_label.pack(side="left")
self.image_index_entry = ttk.Entry(self.index_frame, width=5, state="disabled")
self.image_index_entry.pack(side="left")
self.image_index_entry.bind("<Return>", self.jump_to_image)
self.image_index_entry.bind("<MouseWheel>", self.mouse_scroll)
self.image_index_entry.bind("<Up>", self.next_pair)
self.image_index_entry.bind("<Down>", self.prev_pair)
self.index_context_menu = Menu(self.directory_entry, tearoff=0)
self.index_context_menu.add_command(label="First", command=lambda: self.index_goto(0))
self.index_context_menu.add_command(label="Last", command=lambda: self.index_goto(len(self.image_files)))
self.index_context_menu.add_command(label="Random", accelerator="Ctrl+R", command=self.index_goto_random)
self.index_context_menu.add_command(label="Next Empty", accelerator="Ctrl+E", command=self.index_goto_next_empty)
self.total_images_label = Label(self.index_frame, text=f"of {len(self.image_files)}", state="disabled")
self.total_images_label.pack(side="left")
# Save Button
self.save_button = ttk.Button(self.index_frame, text="Save", state="disabled", style="Blue.TButton", padding=(5, 5), takefocus=False, command=self.save_text_file)
self.save_button.pack(side="left", pady=2, fill="x", expand=True)
ToolTip.create(self.save_button, "CTRL+S to save\n\nRight-Click to make the save button larger", 1000, 6, 12)
self.auto_save_checkbutton = ttk.Checkbutton(self.index_frame, width=10, text="Auto-save", state="disabled", variable=self.auto_save_var, takefocus=False, command=self.sync_title_with_content)
self.auto_save_checkbutton.pack(side="left")
ToolTip.create(self.auto_save_checkbutton, "Automatically save the current text file when:\nNavigating img-txt pairs, changing active directory, or closing the app", 1000, 6, 12)
# Navigation Buttons
nav_button_frame = Frame(self.master_control_frame)
nav_button_frame.pack(fill="x", padx=2)
self.next_button = ttk.Button(nav_button_frame, text="Next--->", width=12, state="disabled", takefocus=False, command=lambda: self.update_pair("next"))
self.prev_button = ttk.Button(nav_button_frame, text="<---Previous", width=12, state="disabled", takefocus=False, command=lambda: self.update_pair("prev"))
self.next_button.pack(side="right", fill="x", expand=True)
self.prev_button.pack(side="right", fill="x", expand=True)
ToolTip.create(self.next_button, "Hotkey: ALT+R\nHold shift to advance by 5", 1000, 6, 12)
ToolTip.create(self.prev_button, "Hotkey: ALT+L\nHold shift to advance by 5", 1000, 6, 12)
# Suggestion text
self.suggestion_frame = Frame(self.master_control_frame, bg='#f0f0f0')
self.suggestion_frame.pack(side="top", fill="x", pady=2)
# Suggestion Text
self.suggestion_textbox = Text(self.suggestion_frame, height=1, width=1, borderwidth=0, highlightthickness=0, bg='#f0f0f0', state="disabled", cursor="arrow")
self.suggestion_textbox.pack(side="left", fill="x", expand=True)
self.suggestion_textbox.bind("<Button-1>", self.disable_button)
self.suggestion_textbox.bind("<B1-Motion>", self.disable_button)
ToolTip.create(self.suggestion_textbox,
"Color Codes:\n"
"Danbooru:\n"
" - General tags: Black\n"
" - Artists: Red\n"
" - Copyright: Magenta\n"
" - Characters: Green\n"
" - Meta: Orange\n"
"e621:\n"
" - General tags: Black\n"
" - Artists: Yellow\n"
" - Copyright: Magenta\n"
" - Characters: Green\n"
" - Species: Orange\n"
" - Meta: Red\n"
" - Lore: Green\n"
"Derpibooru:\n"
" - General tags: Black\n"
" - Official Content: Yellow\n"
" - Species: Light-Orange\n"
" - Original Content: Pink\n"
" - Rating: Blue\n"
" - Body Type: Gray\n"
" - Character: Teal\n"
" - Original Content: Light-Purple\n"
" - Error: Red\n"
" - Official Content: Dark-Orange\n"
" - Original Content: Light-Pink",
1000, 6, 12, justify="left"
)
# Suggestion Options
self.suggestion_menubutton = ttk.Button(self.suggestion_frame, text="☰", takefocus=False, width=2, command=lambda: self.show_suggestion_context_menu(button=True))
self.suggestion_menubutton.pack(side="right", padx=2)
# Startup info text
self.info_text = scrolledtext.ScrolledText(self.master_control_frame)
self.info_text.pack(expand=True, fill="both")
for header, section in zip(self.about_window.info_headers, self.about_window.info_content):
self.info_text.insert("end", header + "\n", "header")
self.info_text.insert("end", section + "\n", "section")
self.info_text.tag_config("header", font=("Segoe UI", 9, "bold"))
self.info_text.tag_config("section", font=("Segoe UI", 9))
self.info_text.bind("<Button-3>", self.show_text_context_menu)
self.info_text.config(state='disabled', wrap="word")
#endregion
################################################################################################################################################
#region - Text Box setup
# --------------------------------------
# Text Pane
# --------------------------------------
def create_text_pane(self):
if not hasattr(self, 'text_pane'):
self.text_pane = PanedWindow(self.master_control_frame, orient="vertical", sashwidth=6, bg="#d0d0d0", bd=0)
self.text_pane.pack(side="bottom", fill="both", expand=1)
# --------------------------------------
# Text Box
# --------------------------------------
def create_text_box(self):
self.create_text_pane()
if not hasattr(self, 'text_frame'):
self.text_frame = Frame(self.master_control_frame)
self.text_pane.add(self.text_frame, stretch="always")
self.text_pane.paneconfigure(self.text_frame, minsize=80)
self.text_box = scrolledtext.ScrolledText(self.text_frame, wrap="word", undo=True, maxundo=200, inactiveselectbackground="#0078d7")
self.text_box.pack(side="top", expand="yes", fill="both")
self.text_box.tag_configure("highlight", background="#5da9be", foreground="white")
self.text_box.config(font=(self.font_var.get(), self.font_size_var.get()))
self.set_text_box_binds()
self.get_default_font()
self.primary_paned_window.unbind("<B1-Motion>")
self.primary_paned_window.bind('<ButtonRelease-1>', self.snap_sash_to_half)
if not hasattr(self, 'text_widget_frame'):
self.create_text_control_frame()
# --------------------------------------
# Text Widget Frame
# --------------------------------------
def create_text_control_frame(self):
self.text_widget_frame = Frame(self.master_control_frame)
self.text_pane.add(self.text_widget_frame, stretch="never")
self.text_pane.paneconfigure(self.text_widget_frame)
self.text_notebook = ttk.Notebook(self.text_widget_frame)
self.text_notebook.bind("<<NotebookTabChanged>>", self.adjust_text_pane_height)
self.tab1 = Frame(self.text_notebook)
self.tab2 = Frame(self.text_notebook)
self.tab3 = Frame(self.text_notebook)
self.tab4 = Frame(self.text_notebook)
self.tab5 = Frame(self.text_notebook)
self.tab6 = Frame(self.text_notebook)
self.tab7 = Frame(self.text_notebook)
self.tab8 = Frame(self.text_notebook)
self.tab9 = Frame(self.text_notebook)
self.text_notebook.add(self.tab1, text='S&R')
self.text_notebook.add(self.tab2, text='Prefix')
self.text_notebook.add(self.tab3, text='Append')
self.text_notebook.add(self.tab4, text='AutoTag')
self.text_notebook.add(self.tab5, text='Filter')
self.text_notebook.add(self.tab6, text='Highlight')
self.text_notebook.add(self.tab7, text='Font')
self.text_notebook.add(self.tab8, text='MyTags')
self.text_notebook.add(self.tab9, text='Stats')
self.text_notebook.pack(fill='both', expand=True)
self.text_controller.create_search_and_replace_widgets_tab1()
self.text_controller.create_prefix_text_widgets_tab2()
self.text_controller.create_append_text_widgets_tab3()
self.text_controller.create_auto_tag_widgets_tab4()
self.text_controller.create_filter_text_image_pairs_widgets_tab5()
self.text_controller.create_custom_active_highlight_widgets_tab6()
self.text_controller.create_font_widgets_tab7()
self.text_controller.create_custom_dictionary_widgets_tab8()
self.text_controller.create_stats_widgets_tab9()
#self.text_widget_frame.bind("<Configure>", lambda event: print(f"text_widget_frame height: {event.height}"))
def adjust_text_pane_height(self, event):
tab_heights = {
'S&R': 60,
'Prefix': 60,
'Append': 60,
'AutoTag': 340,
'Filter': 60,
'Highlight': 60,
'Font': 60,
'MyTags': 240,
'Stats': 240
}
selected_tab = event.widget.tab("current", "text")
tab_height = 60 if self.initialize_text_pane else tab_heights.get(selected_tab, 60)
self.initialize_text_pane = False
self.text_pane.paneconfigure(self.text_widget_frame, height=tab_height)
# --------------------------------------
# Text Box Binds
# --------------------------------------
def set_text_box_binds(self):
# Mouse binds
self.text_box.bind("<Double-1>", lambda event: self.custom_select_word_for_text(event, self.text_box))
self.text_box.bind("<Triple-1>", lambda event: self.custom_select_line_for_text(event, self.text_box))
self.text_box.bind("<Button-1>", lambda event: (self.remove_tag(), self.autocomplete.clear_suggestions()))
self.text_box.bind("<Button-2>", lambda event: (self.delete_tag_under_mouse(event), self.sync_title_with_content(event)))
self.text_box.bind("<Button-3>", lambda event: (self.show_text_context_menu(event)))
# Update the autocomplete suggestion label after every KeyRelease event.
self.text_box.bind("<KeyRelease>", lambda event: (self.autocomplete.update_suggestions(event), self.sync_title_with_content(event)))
# Insert a newline after inserting an autocomplete suggestion when list_mode is active.
self.text_box.bind('<comma>', self.autocomplete.insert_newline_listmode)
# Highlight duplicates when selecting text with keyboard or mouse.
self.text_box.bind("<Shift-Right>", lambda event: self.highlight_duplicates(event, mouse=False))
self.text_box.bind("<Shift-Left>", lambda event: self.highlight_duplicates(event, mouse=False))
self.text_box.bind("<ButtonRelease-1>", self.highlight_duplicates)
# Removes highlights when these keys are pressed.
self.text_box.bind("<Up>", lambda event: self.remove_highlight())
self.text_box.bind("<Down>", lambda event: self.remove_highlight())
self.text_box.bind("<Left>", lambda event: self.remove_highlight())
self.text_box.bind("<Right>", lambda event: self.remove_highlight())
self.text_box.bind("<BackSpace>", lambda event: (self.remove_highlight(), self.sync_title_with_content()))
# Update the title status whenever a key is pressed.
self.text_box.bind("<Key>", lambda event: self.sync_title_with_content(event))
# Disable normal button behavior
self.text_box.bind("<Tab>", self.disable_button)
self.text_box.bind("<Alt_L>", self.disable_button)
self.text_box.bind("<Alt_R>", self.disable_button)
# Show next empty text file
self.text_box.bind("<Control-e>", self.index_goto_next_empty)
# Show random img-txt pair
self.text_box.bind("<Control-r>", self.index_goto_random)
# Refresh text box
#self.text_box.bind("<F5>", lambda event: self.refresh_text_box())
# --------------------------------------
# Text Box Context Menu
# --------------------------------------
def show_text_context_menu(self, event):
if hasattr(self, 'text_box'):
self.text_box.focus_set()
widget_in_focus = root.focus_get()
text_context_menu = Menu(root, tearoff=0)
if widget_in_focus in [self.info_text, getattr(self, 'text_box', None)]:
widget_in_focus.focus_set()
if widget_in_focus == getattr(self, 'text_box', None):
select_state = "disabled"
cleaning_state = "normal" if self.cleaning_text_var.get() else "disabled"
try:
selected_text = self.text_box.get("sel.first", "sel.last")
if len(selected_text) >= 3:
select_state = "normal"
except TclError:
pass
text_context_menu.add_command(label="Cut", accelerator="Ctrl+X", command=lambda: (widget_in_focus.event_generate('<<Cut>>'), self.sync_title_with_content()))
text_context_menu.add_command(label="Copy", accelerator="Ctrl+C", command=lambda: (widget_in_focus.event_generate('<<Copy>>')))
text_context_menu.add_command(label="Paste", accelerator="Ctrl+V", command=lambda: (widget_in_focus.event_generate('<<Paste>>'), self.sync_title_with_content()))
text_context_menu.add_command(label="Delete", accelerator="Del", command=lambda: (widget_in_focus.event_generate('<<Clear>>'), self.sync_title_with_content()))
text_context_menu.add_command(label="Refresh", command=self.refresh_text_box)
text_context_menu.add_separator()
text_context_menu.add_command(label="Undo", accelerator="Ctrl+Z", command=lambda: (widget_in_focus.event_generate('<<Undo>>'), self.sync_title_with_content()))
text_context_menu.add_command(label="Redo", accelerator="Ctrl+Y", command=lambda: (widget_in_focus.event_generate('<<Redo>>'), self.sync_title_with_content()))
text_context_menu.add_separator()
text_context_menu.add_command(label="Open Text Directory...", command=self.open_text_directory)
text_context_menu.add_command(label="Open Text File...", command=self.open_textfile)
text_context_menu.add_command(label="Add Selected Text to MyTags", state=select_state, command=lambda: self.add_to_custom_dictionary(origin="text_box"))
text_context_menu.add_separator()
text_context_menu.add_command(label="Highlight all Duplicates", accelerator="Ctrl+F", command=self.highlight_all_duplicates)
text_context_menu.add_command(label="Next Empty Text File", accelerator="Ctrl+E", command=self.index_goto_next_empty)
text_context_menu.add_separator()
text_context_menu.add_checkbutton(label="Highlight Selection", variable=self.highlight_selection_var)
text_context_menu.add_checkbutton(label="Clean-Text", variable=self.cleaning_text_var, command=self.toggle_list_menu)
text_context_menu.add_checkbutton(label="List View", variable=self.list_mode_var, state=cleaning_state, command=self.toggle_list_mode)
elif widget_in_focus == self.info_text:
text_context_menu.add_command(label="Copy", command=lambda: widget_in_focus.event_generate('<<Copy>>'))
text_context_menu.tk_popup(event.x_root, event.y_root)
# --------------------------------------
# Image Context Menu
# --------------------------------------
def show_image_context_menu(self, event):
self.image_context_menu = Menu(self.root, tearoff=0)
# Open
self.image_context_menu.add_command(label="Open Current Directory...", command=self.open_image_directory)
self.image_context_menu.add_command(label="Open Current Image...", command=self.open_image)
self.image_context_menu.add_command(label="Open Image-Grid...", accelerator="F2", command=self.open_image_grid)
self.image_context_menu.add_command(label="Edit Image...", accelerator="F4", command=self.open_image_in_editor)
self.image_context_menu.add_command(label="AutoTag", command=self.text_controller.interrogate_image_tags)
self.image_context_menu.add_separator()
# File
self.image_context_menu.add_command(label="Duplicate img-txt pair", command=self.duplicate_pair)
self.image_context_menu.add_command(label="Delete img-txt Pair", accelerator="Shift+Del", command=self.delete_pair)
self.image_context_menu.add_command(label="Undo Delete", command=self.undo_delete_pair, state=self.undo_state.get())
self.image_context_menu.add_separator()
# Edit
self.image_context_menu.add_command(label="Rename Pair", command=self.manually_rename_single_pair)
self.image_context_menu.add_command(label="Upscale...", command=lambda: self.upscale_image(batch=False))
self.image_context_menu.add_command(label="Resize...", command=self.resize_image)
self.image_context_menu.add_command(label="Crop...", command=self.show_crop_ui)
if not self.image_file.lower().endswith('.gif'):
self.image_context_menu.add_command(label="Expand", command=self.expand_image)
else:
self.image_context_menu.add_command(label="Expand", state="disabled", command=self.expand_image)
self.image_context_menu.add_command(label="Rotate", command=self.rotate_current_image)
self.image_context_menu.add_command(label="Flip", command=self.flip_current_image)
self.image_context_menu.add_separator()
# Misc
self.image_context_menu.add_checkbutton(label="Toggle Zoom", accelerator="F1", variable=self.toggle_zoom_var, command=self.toggle_zoom_popup)
self.image_context_menu.add_checkbutton(label="Toggle Thumbnail Panel", variable=self.thumbnails_visible, command=self.update_thumbnail_panel)
self.image_context_menu.add_checkbutton(label="Toggle Edit Panel", variable=self.edit_panel_visible_var, command=self.edit_panel.toggle_edit_panel)
self.image_context_menu.add_checkbutton(label="Vertical View", underline=0, variable=self.panes_swap_ns_var, command=self.swap_pane_orientation)
self.image_context_menu.add_checkbutton(label="Swap img-txt Sides", underline=0, variable=self.panes_swap_ew_var, command=self.swap_pane_sides)
# Image Display Quality
image_quality_menu = Menu(self.optionsMenu, tearoff=0)
self.image_context_menu.add_cascade(label="Image Display Quality", menu=image_quality_menu)
for value in ["High", "Normal", "Low"]:
image_quality_menu.add_radiobutton(label=value, variable=self.image_quality_var, value=value, command=self.set_image_quality)
self.image_context_menu.tk_popup(event.x_root, event.y_root)
# --------------------------------------
# Suggestion Context Menu
# --------------------------------------
def show_suggestion_context_menu(self, event=None, button=False):
suggestion_context_menu = Menu(self.root, tearoff=0)
suggestion_context_menu.add_command(label="Suggestion Options", state="disabled")
suggestion_context_menu.add_separator()
# Selected Dictionary
dictionary_menu = Menu(suggestion_context_menu, tearoff=0)
suggestion_context_menu.add_cascade(label="Dictionary", menu=dictionary_menu)
dictionary_menu.add_checkbutton(label="English Dictionary", underline=0, variable=self.csv_english_dictionary, command=self.autocomplete.update_autocomplete_dictionary)
dictionary_menu.add_checkbutton(label="Danbooru", underline=0, variable=self.csv_danbooru, command=self.autocomplete.update_autocomplete_dictionary)
dictionary_menu.add_checkbutton(label="Danbooru (Safe)", underline=0, variable=self.csv_danbooru_safe, command=self.autocomplete.update_autocomplete_dictionary)
dictionary_menu.add_checkbutton(label="Derpibooru", underline=0, variable=self.csv_derpibooru, command=self.autocomplete.update_autocomplete_dictionary)
dictionary_menu.add_checkbutton(label="e621", underline=0, variable=self.csv_e621, command=self.autocomplete.update_autocomplete_dictionary)
dictionary_menu.add_separator()
dictionary_menu.add_command(label="Clear Selection", underline=0, command=self.autocomplete.clear_dictionary_csv_selection)
# Suggestion Threshold
suggestion_threshold_menu = Menu(suggestion_context_menu, tearoff=0)
suggestion_context_menu.add_cascade(label="Threshold", menu=suggestion_threshold_menu)
threshold_levels = ["Slow", "Normal", "Fast", "Faster"]
for level in threshold_levels:
suggestion_threshold_menu.add_radiobutton(label=level, variable=self.suggestion_threshold_var, value=level, command=self.autocomplete.set_suggestion_threshold)
# Suggestion Quantity
suggestion_quantity_menu = Menu(suggestion_context_menu, tearoff=0)
suggestion_context_menu.add_cascade(label="Quantity", menu=suggestion_quantity_menu)
for quantity in range(0, 10):
suggestion_quantity_menu.add_radiobutton(label=str(quantity), variable=self.suggestion_quantity_var, value=quantity, command=lambda suggestion_quantity=quantity: self.autocomplete.set_suggestion_quantity(suggestion_quantity))
# Match Mode
match_mode_menu = Menu(suggestion_context_menu, tearoff=0)
suggestion_context_menu.add_cascade(label="Match Mode", menu=match_mode_menu)
match_modes = {"Match Whole String": False, "Match Last Word": True}
for mode, value in match_modes.items():
match_mode_menu.add_radiobutton(label=mode, variable=self.last_word_match_var, value=value)
# Position
x, y = (event.x_root, event.y_root) if not button else (self.suggestion_menubutton.winfo_rootx(), self.suggestion_menubutton.winfo_rooty())
suggestion_context_menu.tk_popup(x, y)
# --------------------------------------
# Misc UI logic
# --------------------------------------
def custom_select_word_for_text(self, event, text_widget):
widget = text_widget
separators = " ,.-|()[]<>\\/\"'{}:;!@#$%^&*+=~`?"
click_index = widget.index(f"@{event.x},{event.y}")
line, char_index = map(int, click_index.split("."))
line_text = widget.get(f"{line}.0", f"{line}.end")
if char_index >= len(line_text):
return "break"
if line_text[char_index] in separators:
widget.tag_remove("sel", "1.0", "end")
widget.tag_add("sel", f"{line}.{char_index}", f"{line}.{char_index + 1}")
else:
word_start = char_index
while word_start > 0 and line_text[word_start - 1] not in separators:
word_start -= 1
word_end = char_index
while word_end < len(line_text) and line_text[word_end] not in separators:
word_end += 1
widget.tag_remove("sel", "1.0", "end")
widget.tag_add("sel", f"{line}.{word_start}", f"{line}.{word_end}")
widget.mark_set("insert", f"{line}.{char_index + 1}")
return "break"
def custom_select_line_for_text(self, event, text_widget):
widget = text_widget
click_index = widget.index(f"@{event.x},{event.y}")
line, _ = map(int, click_index.split("."))
widget.tag_remove("sel", "1.0", "end")
widget.tag_add("sel", f"{line}.0", f"{line}.end")
widget.mark_set("insert", f"{line}.0")
return "break"
def get_default_font(self):
self.current_font = self.text_box.cget("font")
self.current_font_name = self.text_box.tk.call("font", "actual", self.current_font, "-family")
self.current_font_size = self.text_box.tk.call("font", "actual", self.current_font, "-size")
self.default_font = self.current_font_name
self.default_font_size = self.current_font_size
#endregion
################################################################################################################################################
#region - Additional Interface Setup
# --------------------------------------
# Browse button context menu
# --------------------------------------
def open_browse_context_menu(self, event):
try:
self.browse_context_menu.tk_popup(event.x_root, event.y_root)
finally:
self.browse_context_menu.grab_release()
def set_text_file_path(self, path=None, silent=False):
if path == None:
self.text_dir = filedialog.askdirectory()
else:
self.text_dir = path
if not self.text_dir:
return
self.text_files = []
for image_file in self.image_files:
text_filename = os.path.splitext(os.path.basename(image_file))[0] + ".txt"
text_file_path = os.path.join(self.text_dir, text_filename)
if not os.path.exists(text_file_path):
self.new_text_files.append(text_filename)
self.text_files.append(text_file_path)
if not silent:
self.show_pair()
self.update_text_path_indicator()
def update_text_path_indicator(self):
if os.path.normpath(self.text_dir) != os.path.normpath(self.image_dir.get()):
self.text_path_indicator.config(bg="#5da9be")
self.text_path_tooltip.config(f"Text Path: {os.path.normpath(self.text_dir)}", 10, 6, 12)
else:
self.text_path_indicator.config(bg="#f0f0f0")
self.text_path_tooltip.config("Text Path: Same as image path", 10, 6, 12)
# --------------------------------------
# Directory entry context menu helpers
# --------------------------------------
def open_directory_context_menu(self, event):
try:
self.dir_context_menu.tk_popup(event.x_root, event.y_root)
finally:
self.dir_context_menu.grab_release()