-
Notifications
You must be signed in to change notification settings - Fork 2
/
difbrow.pyw
2620 lines (2064 loc) · 99 KB
/
difbrow.pyw
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
# Diffuse Browser v3.1
# Fred Rique (c) 2022 - 2024.
# github.com/farique1/diffusion-browser
# An easy way to view embedded image metadata of most AI generators.
# CHANGES
# v3.0
# Load image information and save for further use
# Read image file on demand, threaded
# Multiple paths
# ALT+... > Search or expose exact
# CONTROL+ALT+... > Search or expose exact inverted
# HOME > Go to the top of the grid
# END > Go to the bottom of the grid
# SHIFT+UP > Go to the image one page above
# SHIFT+DOWN > Go to the image one page below
# CONTROL+UP > Go to the first image
# CONTROL+DOWN > Go to the last image
# Searching using PATH as a parameter will normalize the path
# v3.1
# Paths requester
# Toggle active or inactive folders
# Double clicking on subfolders or active on the paths requester will toggle them
# Double clicking on the path name will change it
# RETURN, SPACE on the paths requester will toggle subfolders
# SHIFT+RETURN, SHIFT+SPACE on the paths requester will toggle active
# Button to change the selected path
# Image grid
# Right click an image now selects it
# SHIFT+UP became ALT+UP
# SHIFT+DOWN became ALT+DOWN
# Multi select images
# SHIFT+UP add select up
# SHIFT+DOWN add select down
# SHIFT+LEFT add select left
# SHIFT+RIGHT add select right
# shift+click select more
# control+click select toggle
# Menu title copy all selected
# Menu item perform on all images
# Keyboard shortcuts affects all selected images
# Removed seed from the internal image viewer header
# Optimizations
# Load images one by one instead of by rows
# Functions to consolidate selected and unselected button state
# Several small tweaks on the GUI
# Added Scrollbar to the information window
# Themed the scrollbars
# Exchanged open path and paths buttons positions
# Moved refresh and open path buttons
# Menu appearance
# Some state color changes
# Added save batch to folder menu item
# SHIFT+CTRL+S activate batch copy
# Paths combobox show all paths containing images
# Metadata errors bunched together for display.
# Change readme: ctr+l=overlay, ctrl+i=save info
# Metadata reading more robust
# Added support for Fooocus and Fooocus a1111 native embedded metadata
# FIX
# Sometimes when searching for a word and after it sorting and overlaying,
# the overlaying stops working on all shown images. (thesis: maybe it is
# only overlaying the images that are "visible" on the grid if the grid
# did not had been reduced by the search. Images that are farthest from
# the first searched image than the height of the grid in images)
# ADD
# Use im.get_format_mimetype() or Image.MIME[img.format] or img.format
# to determine the image type. Also to load images regardless of extension
# Undock and dock the image and embedded info viewers (see teste.py)
# Multiple projects
# Images Heart
# Images Starts
# Images Tags
# Images Sets
# Mute folders to prevent them from appearing without changing the database
# Rebuild the order of the parameters without needing to rebuild the database
# Keep metadata reading functions independent, delivering a standard format
# Allow consolidation of multiple parameters into a single label
import re
import os
import bz2
import glob
import json
import math
import time
import pickle
import shutil
import platform
import datetime
import threading
import subprocess
import collections
import configparser
import tkinter as tk
from operator import itemgetter
from collections import OrderedDict
from tkinter.colorchooser import askcolor
from tkinter import ttk, font, filedialog
from PIL import Image, ImageTk, ImageOps, UnidentifiedImageError
# Constants
COL_NBR = 5
ROW_NBR = 5
GRID_IMG_SZ = 100
INFO_IMG_SZ = 250
BUTT_HEIGHT = 26
FONT_NAME = 'Tahoma'
FONT_SIZE = 10
FONT_WEIGHT = 'normal'
BG_COLOR = 'black'
FONT_COLOR = 'teal'
ACC_COLOR1 = 'goldenrod'
ACC_COLOR2 = 'grey70'
ALERT_COLOR = 'dark red'
# TOP_PATH = 'D:/Stable Diffusion WebUI/stable-diffusion-webui/outputs/test'
FONT = [FONT_NAME, FONT_SIZE, FONT_WEIGHT]
BORDER = 1
PROGRAM_NAME = 'Diffusion\nBrowser'
ALL_PARAMETERS = 'all parameters'
ALL_FOLDERS = 'all paths'
SEARCH_HELP = 'enter search'
TEXT_INFO_DEFAULT = ('Diffusion Browser v3.0\n'
'github.com/farique1/diffusion-browser\n'
'(c) Fred Rique 2022 - 2024\n\n'
'Browse pictures and metadata generated by Stable Diffusion.\n'
'Works with embedded data from most generators in the style of Automatic1111.\n'
'Converter provided for Fooocus log.html')
LOCAL_PATH = os.path.split(os.path.abspath(__file__))[0]
PROJECT_PATH = 'Projects'
current_project = 'default'
INI_FILE = os.path.join(LOCAL_PATH, PROJECT_PATH, current_project, 'difbrowser.ini')
PARAMETERS_FILE = os.path.join(LOCAL_PATH, PROJECT_PATH, current_project, 'parameters.txt')
DATA_FILE = os.path.join(LOCAL_PATH, PROJECT_PATH, current_project, 'data.pickle')
FOLDERS_FILE = os.path.join(LOCAL_PATH, PROJECT_PATH, current_project, 'folders.json')
OS = platform.system()
with open(PARAMETERS_FILE, 'r') as file:
TEXT_PARS = file.read().splitlines()
COMBO_VALUES = TEXT_PARS
COMBO_VALUES.insert(0, ALL_PARAMETERS)
# Variable initialization
folders = []
image_list = []
new_pars = []
is_overlay = ''
current_index = 0
current_seed = ''
current_image = ''
multi_index = []
sort_reverse = True
time_format = '%Y-%m-%d %H:%M:%S'
prev_button = None
# .ini file handling
ini_path = os.path.join(LOCAL_PATH, INI_FILE)
config_ini = configparser.ConfigParser()
if os.path.isfile(ini_path):
try:
config_ini.read(ini_path)
config_sec = config_ini['CONFIGS']
COL_NBR = int(config_sec.get('number_of_columns'))
ROW_NBR = int(config_sec.get('number_of_lines'))
GRID_IMG_SZ = int(config_sec.get('grid_image_size'))
INFO_IMG_SZ = int(config_sec.get('preview_image_size'))
BUTT_HEIGHT = int(config_sec.get('button_height'))
FONT_NAME = config_sec.get('font_name')
FONT_SIZE = int(config_sec.get('font_size'))
FONT_WEIGHT = config_sec.get('font_weight')
BG_COLOR = config_sec.get('background_color')
FONT_COLOR = config_sec.get('main_color')
ACC_COLOR1 = config_sec.get('accent_color_1')
ACC_COLOR2 = config_sec.get('accent_color_2')
ALERT_COLOR = config_sec.get('alert_color')
# TOP_PATH = config_sec.get('default_path')
FONT = [FONT_NAME, FONT_SIZE, FONT_WEIGHT]
# TOP_PATH = os.path.normpath(TOP_PATH)
except (ValueError, configparser.NoOptionError) as e:
print(f'.INI file problem: {str(e)}')
raise SystemExit(0)
# Initialize
root = tk.Tk()
root.configure(background='black')
root.title('Diffusion Browser')
root.protocol("WM_DELETE_WINDOW", lambda: root.destroy())
root.bind_class("Button", "<Key-Return>", lambda event: event.widget.invoke())
if OS == 'Linux':
root.resizable(True, True)
else:
root.resizable(True, True)
def resize_image(image, maxsize):
'''Resize image maintaining aspect ratio and maximum size'''
r1 = image.size[0] / maxsize[0] # width ratio
r2 = image.size[1] / maxsize[1] # height ratio
ratio = max(r1, r2)
newsize = (int(image.size[0] / ratio), int(image.size[1] / ratio))
image = image.resize(newsize, Image.Resampling.LANCZOS)
return image
def get_canvas_boundaries():
try:
canvas_height = canvas.winfo_height()
y_srt = canvas.yview()[0]
y_end = canvas.yview()[1]
y_len = y_end - y_srt
total_height = canvas_height / y_len
canvas_y_top = int(total_height * y_srt / (GRID_IMG_SZ + BORDER * 2))
canvas_y_bot = int(total_height * y_end / (GRID_IMG_SZ + BORDER * 2)) + 1
slice_start = canvas_y_top * COL_NBR
slice_end = canvas_y_bot * COL_NBR + COL_NBR
slice_end = min(slice_end, len(image_list))
return slice_start, slice_end
except tk.TclError:
raise SystemExit(0)
def render_buttons(image_data, n):
slice_start, slice_end = get_canvas_boundaries()
if n < slice_start or n > slice_end:
image_data['has_image'] = False
return
image_data['button'].update()
try:
image = Image.open(image_data['file'])
image = resize_image(image, (GRID_IMG_SZ, GRID_IMG_SZ))
overlay = ''
if is_overlay:
image = image.convert("L")
image = ImageOps.colorize(image, black=BG_COLOR, white=FONT_COLOR)
embed_dict = image_data['dic_info']
overlay = embed_dict.get(is_overlay, '')
image = ImageTk.PhotoImage(image)
image_data['button'].config(image=image, text=overlay)
image_data['button'].image = image
except tk.TclError:
raise SystemExit(0)
def refresh_images(x, y):
'''Refresh images on the grid buttons'''
if not image_list:
return
vsb.set(x, y)
slice_start, slice_end = get_canvas_boundaries()
for n in range(slice_start, slice_end):
image_data = image_list[n]
if not image_data['has_image'] and len(threading.enumerate()) < 900:
image_data['has_image'] = True
t = threading.Thread(target=render_buttons, args=(image_data, n,))
t.daemon = True
t.start()
def on_mousewheel(event):
'''Handles mouse wheel'''
if OS == 'Linux':
y_steps = 5
if event.num == 4:
y_steps *= -1
elif OS == 'Darwin':
y_steps = event.delta
elif OS == 'Windows':
y_steps = int(-1 * (event.delta / 120))
if 'buttons_frame' in str(event.widget):
canvas.yview_scroll(y_steps, 'units')
def button_select(button):
button.config(bg=ACC_COLOR1, width=GRID_IMG_SZ - 6, height=GRID_IMG_SZ - 6, bd=3, relief='ridge')
def button_unselect(button):
button.config(bg=BG_COLOR, width=GRID_IMG_SZ, height=GRID_IMG_SZ, bd=0, relief='flat')
def click_grid_image(idx, shift=False, control=False, right=False):
'''Handles clicking on a image on the grid'''
global current_seed
global prev_button
global current_index
global multi_index
button = image_list[idx]['button']
if control:
if button.cget('bg') == BG_COLOR:
button_select(button)
multi_index.append(idx)
button.focus_set()
else:
button_unselect(button)
multi_index.remove(idx)
return
if current_index != idx and shift:
if current_index < idx:
idx_start, idx_end = current_index, idx
else:
idx_start, idx_end = idx, current_index
for i in range(idx_start, idx_end + 1):
if i not in multi_index:
multi_index.append(i)
button = image_list[i]['button']
button_select(button)
button.focus_set()
return
if (not right and not shift and multi_index) or (right and button.cget('bg') == BG_COLOR):
for i in multi_index:
button = image_list[i]['button']
button_unselect(button)
multi_index = []
if right and button.cget('bg') == ACC_COLOR1:
return
multi_index = [idx]
button = image_list[idx]['button']
embed_text = image_list[idx]['txt_info']
image = Image.open(image_list[idx]['file'])
image = resize_image(image, (INFO_IMG_SZ, INFO_IMG_SZ))
image = ImageTk.PhotoImage(image)
img_info['image'] = image
img_info.image = image
img_info.config(bg=BG_COLOR)
# Get tag information for colorizing
matches = []
for i, line in enumerate(embed_text.splitlines(), 1):
for tag in TEXT_PARS:
tag_colon = f'{tag}:'
if line.startswith(tag_colon):
start = f'{str(i)}.{len(tag_colon)}'
end = f'{str(i)}.{len(line)}'
content = line[len(tag_colon):]
matches.append((tag_colon, start, end, content))
# Draw text
text_info['state'] = 'normal'
text_info.delete('1.0', 'end')
text_info.insert('insert', embed_text)
for hit in matches:
if hit[0].startswith('seed:'):
current_seed = hit[3]
color = ACC_COLOR2
if hit[3].strip().replace('.', '').isdigit() \
or hit[3].strip().replace(' x ', '').isdigit() \
or hit[3].strip().replace(' ', '').isdigit():
color = ACC_COLOR1
if hit[0].startswith('embedded info'):
color = ACC_COLOR2
text_info.tag_add(hit[0], hit[1], hit[2])
text_info.tag_config(hit[0], foreground=color)
text_info['state'] = 'disable'
if not prev_button:
prev_button = button
# image_keep = button.image
button_unselect(prev_button)
button_select(button)
button.focus_set()
# button.update()
# Give a little time for Python to come to it's senses
time.sleep(0.05)
prev_button = button
current_index = idx
def grid_keys(event, delta, absolute=False, select=False):
'''Navigate grid with the arrow keys.
event: TK internal
delta: Image amout to jump
absolute: if the jump is relative or absolute (to the first or last image)'''
global current_index
prev_current_index = current_index
if absolute:
current_index = (len(image_list) - 1) * delta
else:
current_index = current_index + delta
if (current_index < 0) or (current_index > len(image_list) - 1) or \
not image_list[current_index]['search']:
current_index = prev_current_index
return
image_amount = len(image_list)
image_y = math.floor(current_index / COL_NBR)
rows = math.ceil(image_amount / COL_NBR)
button = image_list[current_index]['button']
button_y = button.winfo_y()
canvas_height = canvas.winfo_height()
y_srt = canvas.yview()[0]
y_end = canvas.yview()[1]
y_len = y_end - y_srt
total_height = int(canvas_height / y_len)
canvas_y_top = int(total_height * y_srt)
canvas_y_bot = int(total_height * y_end)
canvas_position = image_y / rows
img_len = 1 / rows
# Only move if selection is outside the grid frame
if (button_y > canvas_y_bot - GRID_IMG_SZ):
canvas.yview_moveto(canvas_position - y_len + img_len)
if (button_y <= canvas_y_top):
canvas.yview_moveto(canvas_position)
if select:
click_grid_image(current_index, control=True)
else:
click_grid_image(current_index)
# button.invoke()
# button.focus_set()
def maintain_aspect_ratio(event, original, c_full_img, aspect_ratio):
'''Maintains aspect ratio when resizing the image window'''
new_aspect_ratio = event.width / event.height
if new_aspect_ratio > aspect_ratio:
desired_width = event.width
desired_height = int(event.width / aspect_ratio)
else:
desired_height = event.height
desired_width = int(event.height * aspect_ratio)
if event.width != desired_width or event.height != desired_height:
try:
event.widget.geometry(f'{desired_width}x{desired_height}')
size = (desired_width, desired_height)
resized = original.resize(size, Image.Resampling.LANCZOS)
image = ImageTk.PhotoImage(resized)
c_full_img.delete('IMG')
c_full_img.create_image(0, 0, image=image, anchor='nw', tags='IMG')
c_full_img.image = image
except AttributeError:
pass
return 'break'
def show_full_image_multi(i):
'''Its is here so each window can have its own variable reference'''
if not image_list:
return
image_window = tk.Toplevel()
image_window.title(f'{image_list[i]["file"]}')
original = Image.open(image_list[i]['file'])
# Prevent showing images bigger than the screen size
max_width = min(original.size[0], image_window.winfo_screenwidth())
max_height = min(original.size[1], image_window.winfo_screenheight())
original = resize_image(original, (max_width, max_height))
image = ImageTk.PhotoImage(original)
x = root.winfo_x()
y = root.winfo_y() + 30 + BUTT_HEIGHT
dimensions = f'{image.width()}x{image.height()}+{x}+{y}'
image_window.geometry(dimensions)
frame = tk.Frame(image_window)
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
c_full_img = tk.Canvas(image_window, bd=0, highlightthickness=0)
c_full_img.create_image(0, 0, image=image, anchor='nw', tags='IMG')
c_full_img.image = image
c_full_img.grid(row=0, sticky='news')
c_full_img.pack(fill='both', expand=1)
image_window.update()
width = image_window.winfo_width()
height = image_window.winfo_height()
image_window.bind('<Configure>', lambda event: maintain_aspect_ratio(event, original, c_full_img, width / height))
image_window.bind('<Escape>', lambda event: image_window.destroy())
image_window.focus_set()
def show_full_image(idx):
'''Handles clicking on the image preview'''
if idx is None:
return
# Calling a new function each time so each window has its own variable reference
for i in idx:
show_full_image_multi(i)
def show_image(idx):
if idx is None:
return
for i in idx:
path = image_list[i]['file']
if OS == 'Linux':
default_app = subprocess.run(['xdg-mime', 'query', 'default', 'inode/directory'],
stdout=subprocess.PIPE).stdout.decode('utf-8').strip()
if default_app == 'org.kde.dolphin.desktop':
subprocess.Popen(['dolphin', path])
else:
default_app == 'nautilus.desktop'
subprocess.Popen(['nautilus', path])
elif OS == 'Darwin':
subprocess.Popen(["open", path])
else:
subprocess.Popen(["explorer", '/open,', path])
def config_requester():
'''Main configuration window'''
def test_weight(weight):
weight = weight.strip()
if weight != 'normal' and weight != 'bold' and weight != 'italic' and weight != '':
conf_entries[7].config(bg=ALERT_COLOR)
else:
conf_entries[7].config(bg=ACC_COLOR1)
def test_int(widget):
entry = widget.get()
if not entry.isnumeric():
widget.config(bg=ALERT_COLOR)
else:
widget.config(bg=ACC_COLOR1)
def change_button_height(size):
'''Update the button height configuration box'''
test_int(conf_entries[6])
if conf_entries[6]['bg'] != ALERT_COLOR:
conf_entries[4].delete(0, 'end')
conf_entries[4].insert('insert', int(int(size) * 2.5))
def pick_color(r, cur_col):
'''Open a color picker'''
# Open an inactive window to be able to disable the main interface
dummy_window = tk.Toplevel()
dummy_window.withdraw()
config.grab_release()
dummy_window.grab_set()
conf_entries[r - 1].delete(0, 'end')
color = askcolor(color=cur_col, title=conf_labels[r - 1]['text'], parent=config)[1]
if not color:
color = cur_col
conf_entries[r - 1].insert('insert', color)
dummy_window.destroy()
config.grab_set()
change_color(r)
def change_color(r):
'''Change the selected color'''
if r < 9 or r > 13:
return
try:
bt_color_list[r - 9]['bg'] = conf_entries[r - 1].get()
conf_entries[r - 1].config(bg=ACC_COLOR1)
except tk.TclError:
conf_entries[r - 1].config(bg=ALERT_COLOR)
def accept_config(button, conf_entries):
'''Close the configuration window applying changes'''
global COL_NBR
global ROW_NBR
global GRID_IMG_SZ
global INFO_IMG_SZ
global BUTT_HEIGHT
global FONT
global BG_COLOR
global FONT_COLOR
global ACC_COLOR1
global ACC_COLOR2
global ALERT_COLOR
# global TOP_PATH
change_button_height(conf_entries[6].get())
button.focus_set()
config.update()
if conf_entries[0]['bg'] != ALERT_COLOR:
COL_NBR = int(conf_entries[0].get())
if conf_entries[1]['bg'] != ALERT_COLOR:
ROW_NBR = int(conf_entries[1].get())
if conf_entries[2]['bg'] != ALERT_COLOR:
GRID_IMG_SZ = int(conf_entries[2].get())
if conf_entries[3]['bg'] != ALERT_COLOR:
INFO_IMG_SZ = int(conf_entries[3].get())
if conf_entries[4]['bg'] != ALERT_COLOR:
BUTT_HEIGHT = int(conf_entries[4].get())
if conf_entries[6]['bg'] != ALERT_COLOR \
and conf_entries[7]['bg'] != ALERT_COLOR:
FONT = (conf_entries[5].get(),
int(conf_entries[6].get()),
conf_entries[7].get())
BG_COLOR = bt_color_list[0]['bg']
FONT_COLOR = bt_color_list[1]['bg']
ACC_COLOR1 = bt_color_list[2]['bg']
ACC_COLOR2 = bt_color_list[3]['bg']
ALERT_COLOR = bt_color_list[4]['bg']
# if conf_entries[13]['bg'] != ALERT_COLOR:
# TOP_PATH = conf_entries[13].get()
FONT_NAME = FONT[0]
FONT_SIZE = FONT[1]
FONT_WEIGHT = FONT[2]
t_scr_width = root.winfo_screenwidth() * 0.9
t_scr_height = root.winfo_screenheight() * 0.9
# Check if the interface will fit on the current screen size
if (COL_NBR * GRID_IMG_SZ + INFO_IMG_SZ) > t_scr_width \
or (ROW_NBR * GRID_IMG_SZ) > t_scr_height \
or INFO_IMG_SZ > t_scr_height:
tk.messagebox.showinfo(title='Bad configuration',
message='Interface elements too big or too many.\n'
'Will not fit within 90% of the screen.',
parent=config)
return
if not config_ini.has_section('CONFIGS'):
config_ini.add_section('CONFIGS')
config_ini.set('CONFIGS', 'number_of_columns', str(COL_NBR))
config_ini.set('CONFIGS', 'number_of_lines', str(ROW_NBR))
config_ini.set('CONFIGS', 'grid_image_size', str(GRID_IMG_SZ))
config_ini.set('CONFIGS', 'preview_image_size', str(INFO_IMG_SZ))
config_ini.set('CONFIGS', 'button_height', str(BUTT_HEIGHT))
config_ini.set('CONFIGS', 'font_name', FONT_NAME)
config_ini.set('CONFIGS', 'font_size', str(FONT_SIZE))
config_ini.set('CONFIGS', 'font_weight', FONT_WEIGHT)
config_ini.set('CONFIGS', 'background_color', BG_COLOR)
config_ini.set('CONFIGS', 'main_color', FONT_COLOR)
config_ini.set('CONFIGS', 'accent_color_1', ACC_COLOR1)
config_ini.set('CONFIGS', 'accent_color_2', ACC_COLOR2)
config_ini.set('CONFIGS', 'alert_color', ALERT_COLOR)
# config_ini.set('CONFIGS', 'default_path', TOP_PATH)
with open(ini_path, 'w') as configfile:
config_ini.write(configfile)
config.destroy()
# update_grid()
reset_interface()
def font_requester(r, cur_col):
'''Create a font requester'''
def siz_min_pls(delta, entry):
'''Buttons to change the font size'''
size = int(entry.get())
size += delta
if size < 1:
size = 1
entry.delete(0, 'end')
entry.insert('insert', size)
change_font([font_temp[0], int(size), font_temp[2]])
def font_weight(weight, weight_list):
'''Handles clicking on the font weight buttons'''
global font_temp
for item in weight_list:
item[0]['bg'] = FONT_COLOR
item[0]['fg'] = BG_COLOR
weight_list[weight][0]['bg'] = BG_COLOR
weight_list[weight][0]['fg'] = FONT_COLOR
font_temp[2] = weight_list[weight][1]
font_temp[1] = int(size_entry.get())
change_font(font_temp)
def change_font(font_arg):
'''Change the current font'''
global font_temp
font_temp = font_arg
font_preview.config(font=font_temp)
def accept_font():
'''Close the font requester accepting the changes'''
conf_entries[4].delete(0, 'end')
conf_entries[4].insert('insert', int(int(size_entry.get()) * 2.5))
conf_entries[5].delete(0, 'end')
conf_entries[5].insert('insert', font_temp[0])
conf_entries[6].delete(0, 'end')
conf_entries[6].insert('insert', size_entry.get())
conf_entries[7].delete(0, 'end')
conf_entries[7].insert('insert', font_temp[2])
config.grab_set()
config.focus_set()
folders_req.destroy()
dummy.focus_set()
config.update()
if conf_entries[5]['bg'] == ALERT_COLOR \
or conf_entries[6]['bg'] == ALERT_COLOR \
or conf_entries[7]['bg'] == ALERT_COLOR:
return
# global font_box
global font_preview
global size_entry
global font_temp
global folders_req
font_temp = [conf_entries[5].get(),
int(conf_entries[6].get()),
conf_entries[7].get()]
folders_req = tk.Toplevel()
folders_req.title('Font')
available_fonts = font.families()
available_fonts = sorted(available_fonts)
font_box = tk.Listbox(folders_req, highlightthickness=0, relief='flat', name='font_list',
bg=ACC_COLOR1, fg=BG_COLOR, selectbackground=FONT_COLOR)
font_box.grid(row=0, columnspan=3, sticky='news')
font_box.option_add('font', FONT)
sb = ttk.Scrollbar(folders_req, orient='vertical')
sb.grid(row=0, column=3, sticky='news')
font_box.configure(yscrollcommand=sb.set)
sb.config(command=font_box.yview)
config.grab_release()
folders_req.grab_set()
folders_req.focus_set()
for fonts in available_fonts:
font_box.insert('end', fonts)
# Duplicate the last element to prevent down key from overflowing the listbox items
available_fonts.append(available_fonts[-1])
font_box.bind("<ButtonRelease-1>", lambda e: change_font(
[available_fonts[font_box.curselection()[0]], int(size_entry.get()), font_temp[2]]))
font_box.bind("<Up>", lambda e: change_font(
[available_fonts[font_box.curselection()[0] - 1], int(size_entry.get()), font_temp[2]]))
font_box.bind("<Down>", lambda e: change_font(
[available_fonts[font_box.curselection()[0] + 1], int(size_entry.get()), font_temp[2]]))
weight_list = []
brd_norm_butt = tk.Frame(folders_req, bg=BG_COLOR)
brd_norm_butt.grid(row=1, column=0, sticky='nsew')
norm_butt = tk.Button(brd_norm_butt, text="normal", bg=FONT_COLOR, fg=BG_COLOR,
activebackground=ACC_COLOR1, bd=0, command=lambda: font_weight(0, weight_list))
norm_butt.pack(expand=True, fill='both', pady=1, padx=1)
weight_list.append([norm_butt, 'normal'])
brd_norm_bold = tk.Frame(folders_req, bg=BG_COLOR)
brd_norm_bold.grid(row=1, column=1, sticky='nsew')
bold_butt = tk.Button(brd_norm_bold, text="bold", bg=FONT_COLOR, fg=BG_COLOR,
activebackground=ACC_COLOR1, bd=0, command=lambda: font_weight(1, weight_list))
bold_butt.pack(expand=True, fill='both', pady=1, padx=1)
weight_list.append([bold_butt, 'bold'])
brd_norm_ital = tk.Frame(folders_req, bg=BG_COLOR)
brd_norm_ital.grid(row=1, column=2, columnspan=2, sticky='nsew')
ital_butt = tk.Button(brd_norm_ital, text="italic", bg=FONT_COLOR, fg=BG_COLOR,
activebackground=ACC_COLOR1, bd=0, command=lambda: font_weight(2, weight_list))
ital_butt.pack(expand=True, fill='both', pady=1, padx=1)
weight_list.append([ital_butt, 'italic'])
size_entry = tk.Entry(folders_req, text="cancel", bd=0, bg=ACC_COLOR1, fg=BG_COLOR)
size_entry.delete(0, 'end')
size_entry.insert('insert', conf_entries[6].get())
size_entry.bind('<Return>', lambda e: change_font([font_temp[0], int(size_entry.get()), font_temp[2]]))
size_entry.bind('<Tab>', lambda e: change_font([font_temp[0], int(size_entry.get()), font_temp[2]]))
size_entry.bind('<FocusOut>', lambda e: change_font([font_temp[0], int(size_entry.get()), font_temp[2]]))
size_entry.grid(row=2, column=0, columnspan=2, sticky='nsew')
brd_siz_frm = tk.Frame(folders_req, bg=BG_COLOR)
brd_siz_frm.grid(row=2, column=2, columnspan=2, sticky='nsew')
brd_siz_min = tk.Frame(brd_siz_frm, bg=BG_COLOR)
brd_siz_min.grid(row=0, column=0, sticky='nsew')
size_min = tk.Button(brd_siz_min, text="<", bd=0, bg=FONT_COLOR, fg=BG_COLOR,
command=lambda: siz_min_pls(-1, size_entry))
size_min.pack(expand=True, fill='both', pady=1, padx=1)
brd_siz_pls = tk.Frame(brd_siz_frm, bg=BG_COLOR)
brd_siz_pls.grid(row=0, column=1, sticky='nsew')
size_pls = tk.Button(brd_siz_pls, text=">", bd=0, bg=FONT_COLOR, fg=BG_COLOR,
command=lambda: siz_min_pls(1, size_entry))
size_pls.pack(expand=True, fill='both', pady=1, padx=1)
brd_siz_frm.columnconfigure(0, weight=1)
brd_siz_frm.columnconfigure(1, weight=1)
brd_ok_butt = tk.Frame(folders_req, bg=BG_COLOR)
brd_ok_butt.grid(row=3, column=0, columnspan=2, sticky='nsew')
ok_butt = tk.Button(brd_ok_butt, text="OK", bd=0, bg=FONT_COLOR, fg=BG_COLOR,
activebackground=ACC_COLOR1, command=accept_font)
ok_butt.pack(expand=True, fill='both', pady=1, padx=1)
brd_cancel_butt = tk.Frame(folders_req, bg=BG_COLOR)
brd_cancel_butt.grid(row=3, column=2, columnspan=2, sticky='nsew')
cancel_butt = tk.Button(brd_cancel_butt, text="cancel", bd=0, bg=FONT_COLOR, fg=BG_COLOR,
activebackground=ACC_COLOR1, command=folders_req.destroy)
cancel_butt.pack(expand=True, fill='both', pady=1, padx=1)
font_preview = tk.Entry(folders_req, justify='center', bd=0,
bg=BG_COLOR, fg=FONT_COLOR, font=(FONT[0], FONT[1], FONT[2]))
font_preview.insert('insert', 'Diffusion')
font_preview.grid(row=4, columnspan=4, sticky='nsew')
folders_req.rowconfigure(0, weight=1)
folders_req.columnconfigure(0, weight=1)
folders_req.columnconfigure(1, weight=1)
folders_req.columnconfigure(2, weight=1)
folders_req.columnconfigure(3, weight=0)
folders_req.resizable(True, True)
folders_req.update_idletasks()
font_req_width = int(config.winfo_width() / 2)
folders_req.geometry(f'{font_req_width}x{config.winfo_height()}+{config.winfo_x()}+{config.winfo_y()}')
global config
global conf_entries
global conf_labels
global bt_color_list
global dummy
# Create window
config = tk.Toplevel()
config.title('Configuration')
config.grab_set()
config.focus_set()
config.option_add('*font', FONT)
config.resizable(True, True)
config_frame = tk.Frame(config, bg=BG_COLOR)
config_frame.pack(expand=True, fill='both')
# Blank label to separate interface fro window top
dummy = tk.Label(config_frame, text=' ', bg=BG_COLOR, fg=FONT_COLOR)
dummy.grid(row=0)
config_frame.grid_columnconfigure(0, weight=0)
# config_frame.grid_columnconfigure(1, weight=0)
config_frame.grid_columnconfigure(1, weight=1)
# Interface widgets content
conf_cont = [['number of columns', COL_NBR, None, None],
['number of rows', ROW_NBR, None, None],
['gird image size', GRID_IMG_SZ, None, None],
['preview image size', INFO_IMG_SZ, None, None],
['button height', BUTT_HEIGHT, None, None],
['font name', FONT[0], 'get', None, font_requester],
['font size', FONT[1], 'get', None, font_requester],
['font weight', FONT[2], 'get', None, font_requester],
['background color', BG_COLOR, 'pick', BG_COLOR, pick_color],
['main color', FONT_COLOR, 'pick', FONT_COLOR, pick_color],
['accent color 1', ACC_COLOR1, 'pick', ACC_COLOR1, pick_color],
['accent color 2', ACC_COLOR2, 'pick', ACC_COLOR2, pick_color],
['alert color', ALERT_COLOR, 'pick', ALERT_COLOR, pick_color]]
# ['Default path', TOP_PATH, 'get', None, change_config_path]]
brd_bt_color_list = []
bt_color_list = []
conf_entries = []
conf_labels = []
for r, cont in enumerate(conf_cont, 1):
label = tk.Label(config_frame, text=cont[0], bg=BG_COLOR, fg=FONT_COLOR)
label.grid(row=r, column=0, sticky='e', padx=(20, 0))
conf_labels.append(label)
brd_bt_tbox = tk.Frame(config_frame, bg=BG_COLOR)
brd_bt_tbox.grid(row=r, column=1, sticky='wens')
tbox = tk.Entry(brd_bt_tbox, bg=ACC_COLOR1, fg=BG_COLOR, width=30, bd=0, name=str(r),
selectbackground=FONT_COLOR, selectforeground=ACC_COLOR2)
tbox.insert('insert', cont[1])
tbox.pack(expand=True, fill='both', pady=1, padx=1)
conf_entries.append(tbox)
config_frame.rowconfigure(r, weight=1)
if r > 8 and r < 14:
tbox.bind('<Return>', lambda event, nbr=r: change_color(nbr))
tbox.bind('<FocusOut>', lambda event, nbr=r: change_color(nbr))
if (r > 0 and r < 6):
tbox.bind('<Return>', lambda event, widget=tbox: test_int(widget))
tbox.bind('<FocusOut>', lambda event, widget=tbox: test_int(widget))
if cont[2]:
brd_bt_action = tk.Frame(config_frame, bg=BG_COLOR)
brd_bt_action.grid(row=r, column=2, sticky='wens')
action = tk.Button(brd_bt_action, text=cont[2], bd=0,
bg=FONT_COLOR, fg=BG_COLOR, activebackground=ACC_COLOR1)
action.bind('<ButtonRelease-1>', lambda event, func=cont[4], nbr=r, cur_col=cont[3]: func(nbr, cur_col))
action.pack(expand=True, fill='both', pady=1, padx=1)
if cont[3]:
brd_bt_color = tk.Frame(config_frame, bg=BG_COLOR)
brd_bt_color.grid(row=r, column=3, sticky='wens', padx=(0, 20))
color = tk.Button(brd_bt_color, text=' ', bd=0, bg=cont[3], activebackground=cont[3])
color.pack(expand=True, fill='both', pady=1, padx=1)
color.bind('<ButtonRelease-1>', lambda event, func=cont[4], nbr=r, cur_col=cont[3]: func(nbr, cur_col))
brd_bt_color_list.append(brd_bt_color)
bt_color_list.append(color)
brd_bt_color_list[0]['bg'] = FONT_COLOR
# Align path text to the right
# conf_entries[13].xview_moveto(1)
conf_entries[6].bind('<Return>', lambda e: change_button_height(conf_entries[6].get()))
conf_entries[6].bind('<FocusOut>', lambda e: change_button_height(conf_entries[6].get()))
conf_entries[7].bind('<Return>', lambda e: test_weight(conf_entries[7].get()))
conf_entries[7].bind('<FocusOut>', lambda e: test_weight(conf_entries[7].get()))
# conf_entries[r - 1].bind('<Return>', lambda e, nbr=r: test_path(nbr, conf_entries[r - 1].get()))
# conf_entries[r - 1].bind('<FocusOut>', lambda e, nbr=r: test_path(nbr, conf_entries[r - 1].get()))
btn_frame = tk.Frame(config_frame, bg=BG_COLOR)
btn_frame.grid(row=r + 1, columnspan=4, sticky='ew', pady=(20, 20))
btn_frame.grid_columnconfigure(0, weight=1)
btn_frame.grid_columnconfigure(1, weight=1)
brd_bt_btn_accept = tk.Frame(btn_frame, bg=BG_COLOR)
brd_bt_btn_accept.grid(row=0, column=0, sticky='wens', padx=(20, 0))
btn_accept = tk.Button(brd_bt_btn_accept, text='OK (restart)',
bg=FONT_COLOR, fg=BG_COLOR, bd=0, activebackground=ACC_COLOR1)
btn_accept['command'] = lambda conf_entries=conf_entries: accept_config(btn_accept, conf_entries)
btn_accept.pack(expand=True, fill='both', pady=1, padx=1)
brd_btn_cancel = tk.Frame(btn_frame, bg=BG_COLOR)
brd_btn_cancel.grid(row=0, column=1, sticky='wens', padx=(0, 20))
btn_cancel = tk.Button(brd_btn_cancel, text='cancel', bd=0, command=config.destroy,
bg=FONT_COLOR, fg=BG_COLOR, activebackground=ACC_COLOR1)
btn_cancel.pack(expand=True, fill='both', pady=1, padx=1)