-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctk_theme_builder.py
1433 lines (1193 loc) · 61 KB
/
ctk_theme_builder.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
import argparse
import tkinter as tk
import customtkinter as ctk
from customtkinter import ThemeManager
from configparser import ConfigParser
import json
import subprocess as sp
from argparse import HelpFormatter
from operator import attrgetter
from PIL import Image, ImageTk
import os
from os.path import exists
import operator
from pathlib import Path
import pyperclip
import shutil
import sys
import textwrap
from tkinter import filedialog
from tkinter.colorchooser import askcolor
from pathlib import Path
HEADING_FONT = 'Roboto 12'
# from multiprocessing.connection import Listener
# from multiprocessing.connection import Client
prog = os.path.basename(__file__)
prog_dir = Path(os.path.dirname(os.path.realpath(__file__)))
assets_dir = prog_dir / 'assets'
etc_dir = assets_dir / 'etc'
views_dir = assets_dir / 'views'
home_dir = os.getenv("HOME")
PATH = os.path.dirname(os.path.realpath(__file__))
IMAGES = Path(f'{PATH}/assets/images')
default_view_file = views_dir / 'All.json'
with open(default_view_file) as f:
DEFAULT_WIDGET_ATTRIBUTES = json.load(f)
def str_mode_to_int():
appearance_mode = ctk.get_appearance_mode()
if appearance_mode == "Light":
return 0
return 1
def get_color_from_name(name: str):
int_mode = str_mode_to_int()
return ThemeManager.theme["color"][name][int_mode]
def load_image(path, image_size):
""" load rectangular image with path relative to PATH """
return ImageTk.PhotoImage(Image.open(path).resize((image_size, image_size)))
class CBtkMessageBox(object):
"""Message box class for customtkinter. Up to 4 buttons are rendered where their respective buttonN_text
parameter has a value. An integer value us returned, dependant upon the respective button number, of the button
pressed. """
def __init__(self, title='CBtkMessageBox',
message='',
button_height=2,
button1_text='OK',
button2_text='',
button3_text='',
button4_text=''):
button_width = 100
self.message = wrap_string(text_string=message, wrap_width=40) # Is message to display
self.button1_text = button1_text # Button 1 (outputs '1')
self.button2_text = button2_text # Button 2 (outputs '2')
self.button3_text = button3_text # Button 3 (outputs '3')
self.button4_text = button4_text # Button 4 (outputs '4')
self.choice = '' # it will be the return of messagebox according to button press
# Create TopLevel dialog for the messagebox
self.root = ctk.CTkToplevel()
self.root.title(title)
# Setting Geometry
self.frm_main = ctk.CTkFrame(master=self.root)
self.frm_main.pack(fill=tk.BOTH)
self.frm_main.configure(corner_radius=0)
# self.frm_main.columnconfigure(0, weight=1)
# self.root.rowconfigure(0, weight=1)
# self.frm_main.rowconfigure(0, weight=1)
self.frm_message = ctk.CTkFrame(master=self.frm_main)
self.frm_message.pack(expand=True, fill=tk.BOTH)
self.frm_message.configure(corner_radius=0)
self.frm_buttons = ctk.CTkFrame(master=self.frm_main, corner_radius=0)
self.frm_buttons.pack(side=tk.BOTTOM, fill=tk.X, ipady=20)
self.frm_buttons.configure(corner_radius=0)
# self.frm_main.rowconfigure(1, weight=0)
# Creating Label For message
self.lbl_message = ctk.CTkLabel(self.frm_message, text=self.message)
self.lbl_message.pack(fill=tk.BOTH, padx=10, pady=(20, 10))
button_count = 2
buttons_width = button_count * button_width
# self.root.update_idletasks()
# width = self.frm_buttons.winfo_width()
button_count = 1
if button2_text:
button_count += 1
if button3_text:
button_count += 1
if button4_text:
button_count += 1
if button_count == 1:
pad_x = 50
self.root.geometry("320x120")
elif button_count == 2:
pad_x = 30
self.root.geometry("320x120")
elif button_count == 3:
pad_x = 20
self.root.geometry("420x120")
else:
self.root.geometry("440x120")
pad_x = 5
pad_y = (10, 0)
# Create a button, corresponding to button1_text
self.button1_text = ctk.CTkButton(self.frm_buttons,
text=self.button1_text,
command=self.click1,
width=button_width,
height=button_height)
self.button1_text.grid(row=0, column=0, padx=pad_x, pady=pad_y)
# Create a button, corresponding to button1_text
# self.button1_text.info = self.button1_text.place_info()
# Create a button, corresponding to button2_text
if button2_text:
self.button2_text = ctk.CTkButton(self.frm_buttons,
text=self.button2_text,
command=self.click2,
width=button_width,
height=button_height)
self.button2_text.grid(row=0, column=1, padx=pad_x, pady=pad_y)
# Create a button, corresponding to button3_text
if button3_text:
self.button3_text = ctk.CTkButton(self.frm_buttons,
text=self.button3_text,
command=self.click3,
width=button_width,
height=button_height)
self.button3_text.grid(row=0, column=2, padx=pad_x, pady=pad_y)
# Create a button, corresponding to button4_text
if button4_text:
self.button4_text = ctk.CTkButton(self.frm_buttons,
text=self.button4_text,
command=self.click4,
width=button_width,
height=button_height)
self.button4_text.grid(row=0, column=3, padx=pad_x, pady=pad_y)
# Make the message box visible
self.frm_main.update_idletasks()
width = self.frm_main.winfo_width()
height = self.frm_main.winfo_height()
self.root.wait_window()
# Function on Closing MessageBox
def closed(self):
self.root.destroy() # Destroying Dialogue
self.choice = 'closed' # Assigning Value
# Function on pressing button1_text
def click1(self):
self.root.destroy() # Destroying Dialogue
self.choice = 1 # Assigning Value
# Function on pressing button2_text
def click2(self):
self.root.destroy() # Destroying Dialogue
self.choice = 2 # Assigning Value
# Function on pressing button3_text
def click3(self):
self.root.destroy() # Destroying Dialogue
self.choice = 3 # Assigning Value
# Function on pressing button4_text
def click4(self):
self.root.destroy() # Destroying Dialogue
self.choice = 4 # Assigning Value
def all_widget_attributes(widget_attributes):
all_attributes = []
for value_list in widget_attributes.values():
all_attributes = all_attributes + value_list
return all_attributes
def all_widget_categories(widget_attributes):
categories = []
for category in widget_attributes:
categories.append(category)
categories.sort()
return categories
def wrap_string(text_string: str, wrap_width=80):
"""Function which takes a string of text and wraps it, at word boundaries, based on a specified width.
:rtype@ str
:param@ text_string:
:param@ wrap_width:
"""
wrapper = textwrap.TextWrapper(width=wrap_width)
word_list = wrapper.wrap(text=text_string)
string = ''
for element in word_list:
string = string + element + '\n'
return string
# Add a category of All to the DEFAULT_WIDGET_ATTRIBUTES already defined. This lists every widget property under the one key.
DEFAULT_WIDGET_ATTRIBUTES['All'] = all_widget_attributes(DEFAULT_WIDGET_ATTRIBUTES)
bespoke_themes = ['oceanix', 'oceanic']
def launch_preview_panel(appearance_mode, theme):
preview_panel = PreviewPanel(appearance_mode=appearance_mode, theme=theme)
class SortingHelpFormatter(HelpFormatter):
def add_arguments(self, actions):
actions = sorted(actions, key=attrgetter('option_strings'))
super(SortingHelpFormatter, self).add_arguments(actions)
class CBtkToolTip(object):
"""
Create a tooltip for a given widget.
"""
def __init__(self, widget, text='widget info', bg_colour='#777777'):
self._bg_colour = bg_colour
self._wait_time = 400 # milli-seconds
self._wrap_length = 300 # pixels
self._widget = widget
self._text = text
self._widget.bind("<Enter>", self.enter)
self._widget.bind("<Leave>", self.leave)
self._widget.bind("<ButtonPress>", self.leave)
self._id = None
self._tw = None
def enter(self, event=None):
self._schedule()
def leave(self, event=None):
self._unschedule()
self.hide_tooltip()
def _schedule(self):
self._unschedule()
self._id = self._widget.after(self._wait_time, self.show_tooltip)
def _unschedule(self):
id = self._id
self._id = None
if id:
self._widget.after_cancel(id)
def show_tooltip(self, event=None):
x = y = 0
x, y, cx, cy = self._widget.bbox("insert")
x += self._widget.winfo_rootx() + 40
y += self._widget.winfo_rooty() + 20
# creates a toplevel window
self._tw = tk.Toplevel(self._widget)
# Leaves only the label and removes the app window
self._tw.wm_overrideredirect(True)
self._tw.wm_geometry("+%d+%d" % (x, y))
label = tk.Label(self._tw, text=self._text, justify='left',
background=self._bg_colour, relief='solid', borderwidth=1,
wraplength=self._wrap_length)
label.pack(ipadx=1)
def hide_tooltip(self):
tw = self._tw
self._tw = None
if tw:
tw.destroy()
class CBtkStatusBar(tk.Entry):
"""Create a status bar on the parent window. Messages can be writtento the status bar using the set_status_text
method. The status_text_life can be used to auto-erase the status text after the specified number of seconds. The
default value, 0, disables the auto-erase feature."""
def __init__(self,
master,
status_text_life=10,
use_grid=True):
super().__init__()
self._message_id = None
self._master = master
grid_size = master.grid_size()
grid_columns = grid_size[0]
grid_rows = grid_size[1]
self._master.update_idletasks()
self._app_width = self._master.winfo_width()
self._status_text_life = status_text_life
assert isinstance(self._status_text_life, int)
self._default_fg_color = get_color_from_name('frame_low')
self._status_bar = ctk.CTkLabel(master, relief=tk.SUNKEN, text='', anchor='w', width=self._app_width,
fg_color=self._default_fg_color)
# breadcrumb
if use_grid:
self._status_bar.grid(row=grid_rows + 1, column=0, padx=0, pady=0, columnspan=grid_columns, sticky='ew')
else:
self._status_bar.pack(fill="both", expand=0)
self._orig_app_width = self._master.winfo_width()
def auto_size_status_bar(self, event):
# self._master.update_idletasks()
self._app_width = self._master.winfo_width()
if self._app_width > self._orig_app_width:
self._status_bar.configure(width=self._app_width)
self._master.update_idletasks()
def clear_status(self):
self.set_status_text(status_text=' ')
def set_status_text(self, status_text: str,
status_text_life=None):
message_life = 0
self._status_bar.configure(text=' ' + status_text)
if status_text_life is not None:
message_life = status_text_life
elif self._status_text_life:
message_life = self._status_text_life
else:
message_life = 0
if self._status_text_life:
self._message_id = self.after(message_life * 1000, self.clear_status)
def set_text_color(self, text_color):
self._status_bar.configure(text_color=text_color)
def cancel_message_timer(self):
"""If using the status message timeout feature, it is important to use the cancel_message_timer function,
immediately prior to closing the window. This prevents the later reference and exception, associated with an
"after" method resource reference to an object which is destroyed. """
if hasattr(self, '_message_id'):
self.after_cancel(id=self._message_id)
@staticmethod
def _get_property_by_name(prop_name: str):
return ThemeManager.theme[prop_name]
def set_status_text_life(self, status_text_life):
self._status_text_life = status_text_life
class ControlPanel:
initial_height = 840
expanded_height = initial_height
# initial_width = 180
initial_width = 555
expanded_width_small = 555
expanded_width_large = 555
def __init__(self):
self.app = ctk.CTk()
platform = sys.platform
if platform == "win32":
self._platform = "Windows"
elif platform == "darwin":
self._platform = "MacOS"
else:
self._platform = "Linux"
if platform == "Windows":
self._home_dir = os.getenv("UserProfile")
self.user_name = os.getenv("LOGNAME")
else:
self.user_name = os.getenv("USER")
self._home_dir = os.getenv("HOME")
# Initialise class properties
self._home_dir = Path(self._home_dir)
self._app_home = self._home_dir / '.ctk_theme_maker'
self._appearance_mode = 'Light'
self.process = None
self.app.protocol("WM_DELETE_WINDOW", self._close_panels)
self._json_state = 'clean'
self.widgets = {}
self._properties_view = 'All'
self._widget_attributes = DEFAULT_WIDGET_ATTRIBUTES
# If this is the first time the app is run, create an app home directory.
if not exists(self._app_home):
print(f'Initialising application: {self._app_home}')
os.mkdir(self._app_home)
self._config_file = self._app_home / 'ctk_theme_maker.ini'
# If we don't have an ini file, create one.
if not exists(self._config_file):
self._create_config_file(platform=platform)
self._enable_tooltips = int(self._config_property_val('preferences', 'enable_tooltips'))
self._theme_json_dir = Path(self._config_property_val('preferences', 'theme_json_dir'))
control_panel_theme = self._config_property_val('preferences', 'control_panel_theme')
control_panel_theme = control_panel_theme + '.json'
self._control_panel_theme = str(self._theme_json_dir / control_panel_theme)
# The control_panel_mode holds the customtkinter appearance mode (Dark / Light)
self._control_panel_mode = self._config_property_val('preferences', 'control_panel_mode')
self._temp_dir = Path(self._config_property_val('system', 'temp_dir'))
self._tooltips_enabled_setting = self._config_property_val('preferences', 'enable_tooltips')
try:
ctk.set_default_color_theme(self._control_panel_theme)
except FileNotFoundError:
ctk.set_default_color_theme('blue')
print(f'Preferred Control Panel, theme file not found. Falling back to "blue" theme.')
ctk.set_appearance_mode(self._control_panel_mode)
self._restore_controller_geometry()
# self.app.geometry(f'{180}x{ControlPanel.initial_height}+{winfo_x}+{winfo_y}')
self.app.rowconfigure(2, weight=1)
self.app.columnconfigure(0, weight=1)
self.app.title('CTk Theme Builder')
# Instantiate Frames
title_frame = ctk.CTkFrame(master=self.app)
# title_frame.grid(row=0, column=0, columnspan=2, sticky='w', padx=(5, 5), pady=(5, 0))
title_frame.pack(fill="both", expand=0)
self._control_frame = ctk.CTkFrame(master=self.app)
self._control_frame.columnconfigure(1, weight=1)
self._control_frame.pack(fill="both", expand=1)
self._control_frame.rowconfigure(1, weight=1)
self._button_frame = ctk.CTkFrame(master=self._control_frame)
button_frame = self._button_frame
button_frame.grid(row=1, column=0, columnspan=1, sticky='ns', padx=(5, 5), pady=(5, 5))
self._widget_frame = ctk.CTkFrame(master=self._control_frame)
self._widget_frame.grid(row=1, column=1, rowspan=1, sticky='nswe', padx=(0, 5), pady=(5, 5))
self._status_bar = CBtkStatusBar(master=self.app,
status_text_life=10,
use_grid=False)
self.app.bind("<Configure>", self._status_bar.auto_size_status_bar)
# Populate Frames
self.lbl_title = ctk.CTkLabel(master=title_frame, text='Control Panel', text_font=HEADING_FONT)
self.lbl_title.grid(row=0, column=0, columnspan=2, sticky='ew', pady=(0, 5))
master = title_frame.columnconfigure(0, weight=1)
self.lbl_theme = ctk.CTkLabel(master=self._button_frame, text='Select Theme:')
self.lbl_theme.grid(row=1, column=0, sticky='w', pady=(10, 0), padx=(10, 10))
self._json_files = self._themes_list()
initial_display = self._themes_list()
initial_display.insert(0, '-- Select Theme --')
self.opm_theme = ctk.CTkOptionMenu(master=self._button_frame,
values=initial_display,
command=self._load_theme)
self.opm_theme.grid(row=3, column=0)
self.lbl_mode = ctk.CTkLabel(master=self._button_frame, text='Select Mode:')
self.lbl_mode.grid(row=5, column=0, sticky='w', pady=(10, 0), padx=(10, 10))
self.opm_mode = ctk.CTkOptionMenu(master=self._button_frame, values=['Dark', 'Light'],
command=self.render_widget_properties_preview,
state=tk.DISABLED)
self.opm_mode.grid(row=6, column=0)
self.lbl_filter_view = ctk.CTkLabel(master=self._button_frame,
text='Properties View:')
self.lbl_filter_view.grid(row=7, column=0, sticky='w', pady=(10, 0), padx=(10, 10))
self._widget_categories = all_widget_categories(DEFAULT_WIDGET_ATTRIBUTES)
self._views_list = self._view_list()
self.tk_filter_view = tk.StringVar(value='All')
self._opm_properties_filter_view = ctk.CTkOptionMenu(master=self._button_frame,
command=self._update_properties_filter,
variable=self.tk_filter_view,
values=self._views_list,
state=tk.DISABLED)
self._opm_properties_filter_view.grid(row=8, column=0)
self.lbl_filter = ctk.CTkLabel(master=self._button_frame, text='Filter Properties:')
self.lbl_filter.grid(row=9, column=0, sticky='w', pady=(10, 0), padx=(10, 10))
self._widget_categories = all_widget_categories(DEFAULT_WIDGET_ATTRIBUTES)
self._opm_properties_filter = ctk.CTkOptionMenu(master=self._button_frame,
values=self._widget_categories,
command=self.set_filtered_widget_display,
state=tk.DISABLED)
self._opm_properties_filter.grid(row=10, column=0)
# btn_launch = ctk.CTkButton(master=frame, text='Close Colours', command=self.remove_colours)
# btn_launch.grid(row=0, column=1, padx=5, pady=5)
self._btn_refresh = ctk.CTkButton(master=button_frame, text='Update Preview',
command=self._refresh_preview,
state=tk.DISABLED)
self._btn_refresh.grid(row=11, column=0, padx=5, pady=(60, 0))
# We don't render the refresh just yet. This is to replace the preview button once initial preview is elected.
self._btn_reset = ctk.CTkButton(master=button_frame,
text='Reset',
state=tk.DISABLED,
command=self.reset_theme)
self._btn_reset.grid(row=12, column=0, padx=5, pady=(60, 5))
self._btn_create = ctk.CTkButton(master=button_frame,
text='Create',
command=self._create_theme)
self._btn_create.grid(row=14, column=0, padx=5, pady=(5, 5))
self._btn_mirror = ctk.CTkButton(master=button_frame,
text='Mirror Mode',
state=tk.DISABLED,
command=self._mirror_appearance_mode)
self._btn_mirror.grid(row=15, column=0, padx=5, pady=(5, 5))
self._btn_save = ctk.CTkButton(master=button_frame,
text='Save',
state=tk.DISABLED,
command=self._save_theme)
self._btn_save.grid(row=18, column=0, padx=5, pady=(30, 5))
self._btn_save_as = ctk.CTkButton(master=button_frame,
text='Save As',
state=tk.DISABLED,
command=self._save_theme_as)
self._btn_save_as.grid(row=20, column=0, padx=5, pady=(5, 5))
btn_quit = ctk.CTkButton(master=button_frame, text='Quit', command=self._close_panels)
btn_quit.grid(row=30, column=0, padx=5, pady=(60, 5))
self._create_menu()
self.app.mainloop()
def _appearance_mode_index(self, mode=None):
if mode is None:
appearance_mode = ctk.get_appearance_mode()
else:
appearance_mode = mode
if appearance_mode == "Light":
return 0
# self.app.geometry = ''
return 1
def colour_picker(self, widget_property):
prev_colour = self.widgets[widget_property]["colour"]
new_colour = askcolor(master=self.app, title='Pick colour for : ' + widget_property,
initialcolor=prev_colour)
if new_colour[1] is not None:
new_colour = new_colour[1]
self.widgets[widget_property]['button'].configure(fg_color=new_colour)
self.widgets[widget_property]['colour'] = new_colour
appearance_mode_index = self._appearance_mode_index(self._appearance_mode)
self.json_data['color'][widget_property][appearance_mode_index] = new_colour
if prev_colour != new_colour:
self._btn_reset.configure(state=tk.NORMAL)
self._btn_save.configure(state=tk.NORMAL)
self._btn_save_as.configure(state=tk.NORMAL)
self._btn_mirror.configure(state=tk.NORMAL)
self._json_state = 'dirty'
def _config_property_val(self, section: str, key: str):
"""Accept a config file section and key then return the associated value last stored in theme_make.ini"""
config = ConfigParser()
config.read(self._config_file)
config_value = config.get(section, key)
return config_value
def _create_config_file(self, platform):
with open(self._config_file, 'w') as f:
f.write('[system]\n')
if platform in ['darwin', 'linux']:
f.write('temp_dir = /tmp\n')
else:
f.write(f'temp_dir = {self._home_dir}\AppData\Local\Temp\n')
f.write('[auto_save]\n')
f.write('expand_palette = 1\n')
f.write('render_disabled = 1\n')
f.write('[preferences]\n')
f.write(f'theme_author = {self.user_name}\n')
f.write('control_panel_theme = oceanix\n')
f.write('control_panel_mode = Dark\n')
f.write(f'theme_json_dir = {assets_dir}/themes\n')
f.write(f'enable_tooltips = 1\n')
def _create_menu(self):
# Set up the core of our menu
des_menu = tk.Menu(self.app)
foreground = self._get_color_from_name('text')
background = self._get_color_from_name('frame_low')
des_menu.config(background=background, foreground=foreground)
self.app.config(menu=des_menu)
# Now add a File sub-menu option
file_menu = tk.Menu(des_menu)
file_menu.config(background=background, foreground=foreground)
des_menu.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='Quit', command=self._close_panels)
# Now add a Tools sub-menu option
tools_menu = tk.Menu(des_menu)
tools_menu.config(background=background, foreground=foreground)
des_menu.add_cascade(label='Tools', menu=tools_menu)
tools_menu.add_command(label='Preferences', command=self._launch_preferences)
def _launch_preferences(self):
self._top_prefs = ctk.CTkToplevel(master=self.app)
self._top_prefs.title('Theme Builder Preferences')
# Make preferences dialog modal
self._top_prefs.grab_set()
self._top_prefs.rowconfigure(0, weight=1)
self._top_prefs.rowconfigure(1, weight=0)
self._top_prefs.columnconfigure(0, weight=1)
self._new_theme_json_dir = None
frm_main = ctk.CTkFrame(master=self._top_prefs, corner_radius=0)
frm_main.grid(column=0, row=0, sticky='ew')
frm_widgets = ctk.CTkFrame(master=frm_main, corner_radius=0)
frm_widgets.grid(column=0, row=0, padx=5, pady=5, sticky='ew')
frm_buttons = ctk.CTkFrame(master=frm_main, corner_radius=0)
frm_buttons.grid(column=0, row=1, padx=5, pady=(5, 0), sticky='ew')
widget_start_row = 0
lbl_author_name = ctk.CTkLabel(master=frm_widgets, text='Author')
lbl_author_name.grid(row=widget_start_row, column=0, padx=(80, 0), pady=(0, 5), sticky='w')
self.tk_author_name = tk.StringVar(value=self.user_name)
self.ent_author_name = ctk.CTkEntry(master=frm_widgets,
textvariable=self.tk_author_name,
width=160)
self.ent_author_name.grid(row=widget_start_row, column=1, sticky='w')
widget_start_row += 1
lbl_theme = ctk.CTkLabel(master=frm_widgets, text='Control Panel Theme')
lbl_theme.grid(row=widget_start_row, column=0, pady=(0, 5))
control_panel_theme = os.path.splitext(self._control_panel_theme)[0]
control_panel_theme = os.path.basename(control_panel_theme)
self._tk_control_panel_theme = tk.StringVar(value=control_panel_theme)
self._opm_control_panel_theme = ctk.CTkOptionMenu(master=frm_widgets,
variable=self._tk_control_panel_theme,
values=self._themes_list())
self._opm_control_panel_theme.grid(row=widget_start_row, column=1, pady=5, sticky='w')
widget_start_row += 1
lbl_mode = ctk.CTkLabel(master=frm_widgets, text='Appearance Mode')
lbl_mode.grid(row=widget_start_row, column=0, padx=(25, 0), sticky='w')
# The control_panel_mode holds the customtkinter appearance mode (Dark / Light)
self._tk_appearance_mode_var = tk.StringVar(value=self._control_panel_mode)
rdo_light = ctk.CTkRadioButton(master=frm_widgets, text='Light', variable=self._tk_appearance_mode_var,
value='Light')
rdo_light.grid(row=widget_start_row, column=1, sticky='w')
widget_start_row += 1
rdo_dark = ctk.CTkRadioButton(master=frm_widgets, text='Dark', variable=self._tk_appearance_mode_var,
value='Dark')
rdo_dark.grid(row=widget_start_row, column=1, pady=5, sticky='w')
widget_start_row += 1
lbl_enable_tooltips = ctk.CTkLabel(master=frm_widgets, text='Enable tooltips')
lbl_enable_tooltips.grid(row=widget_start_row, column=0, padx=(40, 0), sticky='e')
self._tk_enable_tooltips = tk.IntVar(master=frm_widgets)
self._tk_enable_tooltips.set(self._enable_tooltips)
self._swt_enable_tooltips = ctk.CTkSwitch(master=frm_widgets,
text='',
variable=self._tk_enable_tooltips,
command=self._get_tooltips_setting)
self._swt_enable_tooltips.grid(row=widget_start_row, column=1, pady=10, sticky='w')
widget_start_row += 1
self._folder_image = load_image(IMAGES / 'folder.png', 20)
lbl_theme_json_dir = ctk.CTkLabel(master=frm_widgets, text='Theme JSON location')
lbl_theme_json_dir.grid(row=widget_start_row, column=0, pady=5)
btn_theme_json_dir = ctk.CTkButton(master=frm_widgets,
text='',
width=30,
height=30,
fg_color='#748696',
image=self._folder_image,
command=self._preferred_json_location)
btn_theme_json_dir.grid(row=widget_start_row, column=1, pady=5, sticky='w')
widget_start_row += 1
# Control buttons
btn_close = ctk.CTkButton(master=frm_buttons, text='Cancel', command=self._top_prefs.destroy)
btn_close.grid(row=0, column=0, padx=(5, 35), pady=5)
btn_save = ctk.CTkButton(master=frm_buttons, text='Save', command=self._save_preferences)
btn_save.grid(row=0, column=1, padx=(35, 5), pady=5)
def _save_preferences(self):
# Save JSON Directory:
if self._new_theme_json_dir is not None:
self._theme_json_dir = self._new_theme_json_dir
self._update_config(section='preferences', option='theme_json_dir', value=self._theme_json_dir)
self._json_files = self._themes_list()
self.opm_theme.configure(values=self._json_files)
self.user_name = self.tk_author_name.get()
self._update_config(section='preferences', option='theme_author',
value=self.user_name)
self._update_config(section='preferences', option='control_panel_theme',
value=self._opm_control_panel_theme.get())
self._update_config(section='preferences', option='control_panel_mode',
value=self._tk_appearance_mode_var.get())
self._top_prefs.destroy()
self._status_bar.set_status_text(status_text=f'Preferences saved.')
self._enable_tooltips = self._tooltips_enabled_setting
self._update_config(section='preferences', option='enable_tooltips',
value=self._enable_tooltips)
def _update_properties_filter(self, view_name):
"""When a different view is selected, we need to update the Properties Filter list accordingly. This method,
loads the requisite JSON files and derives the new list for us. """
view_file = str(views_dir / view_name) + '.json'
view_file = Path(view_file)
with open(view_file) as json_file:
self._widget_attributes = json.load(json_file)
self._widget_categories = all_widget_categories(self._widget_attributes)
self._opm_properties_filter.configure(values=self._widget_categories)
def _preferred_json_location(self):
"""A simple method which asks the themes author to navigate to where
the themes JSON are to be stored/maintained."""
self._new_theme_json_dir = Path(tk.filedialog.askdirectory(initialdir=self._theme_json_dir))
def _themes_list(self):
"""This method generates a list of theme names, based on the json files found in the themes folder
(i.e. self._theme_json_dir). These are basically the theme file names, with the .json extension stripped out."""
json_files = [file for file in os.listdir(self._theme_json_dir) if file.endswith('.json')]
theme_names = []
for file in json_files:
theme_name = os.path.splitext(file)[0]
theme_names.append(theme_name)
theme_names.sort()
return theme_names
@staticmethod
def _view_list():
"""This method generates a list of view names, based on the json files found in the assets/views folder.
These are basically the theme file names, with the .json extension stripped out."""
json_files = [file for file in os.listdir(views_dir) if file.endswith('.json')]
theme_names = []
for file in json_files:
theme_name = os.path.splitext(file)[0]
theme_names.append(theme_name)
theme_names.sort()
return theme_names
@staticmethod
def _get_color_from_name(name: str):
mode = ctk.get_appearance_mode()
if mode == 'Light':
mode = 0
else:
mode = 1
return ThemeManager.theme["color"][name][mode]
def _load_theme(self, dummy=None):
if self._json_state == 'dirty':
confirm = CBtkMessageBox(title='Confirm Action',
message=f'You have unsaved changes. Are you sure you wish to switch themes?',
button1_text='Yes',
button2_text='No')
if confirm.choice == 2:
return
self._json_state = 'clean'
if self.opm_theme.get() == '-- Select Theme --':
return
self._theme_file = self.opm_theme.get() + '.json'
self._source_json_file = self._theme_json_dir / self._theme_file
if self._source_json_file:
self._wip_json = self._temp_dir / self._theme_file
shutil.copyfile(self._source_json_file, self._wip_json)
with open(self._wip_json) as f:
self.json_data = json.load(f)
self._update_config(section='preferences', option='theme_json_dir', value=self._theme_json_dir)
self.render_widget_properties()
try:
self._btn_refresh.configure(state=tk.NORMAL)
except tk.TclError:
pass
# Enable buttons
self.opm_mode.configure(state=tk.NORMAL)
self._opm_properties_filter.configure(state=tk.NORMAL)
self._btn_save.configure(state=tk.NORMAL)
self._btn_save_as.configure(state=tk.NORMAL)
self._btn_mirror.configure(state=tk.NORMAL)
self._opm_properties_filter_view.configure(state=tk.NORMAL)
self._btn_reset.configure(state=tk.DISABLED)
self._btn_save.configure(state=tk.DISABLED)
self.lbl_title.grid(row=0, column=0, columnspan=2, sticky='ew')
self.app.geometry(f'{ControlPanel.expanded_width_large}x{ControlPanel.expanded_height}')
self.opm_theme.configure(values=self._json_files)
self._refresh_preview()
self._status_bar.set_status_text(status_text_life=10,
status_text=f'Theme file, {self._theme_file}, loaded. ')
def reset_theme(self):
confirm = CBtkMessageBox(title='Confirm Action',
message=f'You have unsaved changes. Are you sure you wish to discard them?',
button1_text='Yes',
button2_text='No')
if confirm.choice == 2:
return
self._json_state = 'clean'
self._load_theme()
def _create_theme(self):
source_file = etc_dir / 'default.json'
dialog = ctk.CTkInputDialog(master=None, text="Enter new theme name:", title="Create New Theme")
new_theme = dialog.get_input()
if new_theme:
# If user has included a ".json" extension, remove it, because we add one below.
new_theme_basename = os.path.splitext(new_theme)[0]
new_theme = new_theme_basename + '.json'
new_theme_path = self._theme_json_dir / new_theme
shutil.copyfile(source_file, new_theme_path)
self._json_files = self._themes_list()
self.opm_theme.configure(values=self._json_files)
self.opm_theme.set(new_theme_basename)
def _save_theme_as(self):
source_file = self._source_json_file
dialog = ctk.CTkInputDialog(master=None, text="Enter new theme name:", title="Create New Theme")
new_theme = dialog.get_input()
if new_theme:
# If user has included a ".json" extension, remove it, because we add one below.
new_theme = os.path.splitext(new_theme)[0]
self.opm_theme.configure(command=None)
self.opm_theme.set(new_theme)
self.opm_theme.configure(command=self._load_theme)
new_theme = new_theme + '.json'
new_theme_path = self._theme_json_dir / new_theme
shutil.copyfile(source_file, new_theme_path)
self._load_theme()
self._json_files = self._themes_list()
self.opm_theme.configure(values=self._json_files)
def _update_config(self, section, option, value):
"""Update our config file with the specified value."""
config = ConfigParser()
config.read(self._config_file)
config.set(section=section, option=option, value=str(value))
with open(self._config_file, 'w') as f:
config.write(f)
def set_filtered_widget_display(self, dummy='dummy'):
filter = self._opm_properties_filter.get()
if filter == 'All':
self.app.geometry(f'{ControlPanel.expanded_width_large}x{ControlPanel.expanded_height}')
else:
self.app.geometry(f'{ControlPanel.expanded_width_small}x{ControlPanel.expanded_height}')
self.render_widget_properties()
def refresh_widget_properties(self, dummy=None):
"""Here we render the widget properties in the control panel"""
self.render_widget_properties()
self._refresh_preview()
def render_widget_properties_preview(self, dummy=None):
"""Here we render the widget properties in the control panel as well as update the preview panel."""
self.render_widget_properties()
self._refresh_preview()
def render_widget_properties(self, dummy=None):
"""Here we render the widget properties in the control panel"""
filter_key = self._opm_properties_filter.get()
self._filter_list = self._widget_attributes[filter_key]
self._appearance_mode = self.opm_mode.get()
js = open(self._wip_json)
json_text = json.load(js)
widget_frame = self._widget_frame
colours = json_text["color"]
sorted_widget_properties = sorted(colours.items(), key=operator.itemgetter(0))
row = 1
# The offset is used to control the column we place the widget details in.
# We aim to stack them into 2 columns.
offset = 0
button_width = 30
button_height = 30
for entry in self.widgets.values():
btn_property = entry['button']
lbl_property = entry['label']
btn_property.grid_remove()
lbl_property.grid_remove()
appearance_mode_index = self._appearance_mode_index(appearance_mode)
for key, value in sorted_widget_properties:
if key not in self._filter_list:
continue
colour = value[appearance_mode_index]
if row > 18:
offset = 4
row = 1
# Light mode colours
if row == 1:
pad_y = (10, 0)
else:
pad_y = 5
lbl_property = ctk.CTkLabel(master=widget_frame, text=' ' + key)
lbl_property.grid(row=row, column=1 + offset, sticky='w', pady=pad_y)
btn_property = ctk.CTkButton(master=widget_frame,
border_width=1,
fg_color=colour,
width=button_width,
height=button_height,
text='',
command=lambda widget_property=key: self.colour_picker(widget_property),
corner_radius=3)
btn_property.grid(row=row, column=0 + offset, padx=5, pady=pad_y)
button_dict = {"button": btn_property, "colour": colour, 'label': lbl_property}
self.widgets[key] = button_dict
# lbl_colour_code = ctk.CTkLabel(master=palette_frame, text=colour)
# lbl_colour_code.grid(row=row, column=2 + offset, sticky='w', pady=pad_y)
row += 1
def _mirror_appearance_mode(self):
"""This method allows us to copy our Dark configuration (if Sark is our current selection, to our Light and
vice-versa """
current_mode = self.opm_mode.get()
if current_mode == 'Light':
from_mode = 0
to_mode = 1
message = "Appearance mode, 'Light', copied to 'Dark."
else:
from_mode = 1
to_mode = 0
message = "Appearance mode, 'Dark', copied to 'Light."
for widget_property, value in self.json_data['color'].items():
pass
self.json_data['color'][widget_property][to_mode] = self.json_data['color'][widget_property][from_mode]
self._status_bar.set_status_text(status_text=message)
self._btn_save.configure(state=tk.NORMAL)
self._btn_reset.configure(state=tk.NORMAL)
self._json_state = 'dirty'
def _refresh_preview(self):
try:
if self.process:
self.process.terminate()
except NameError:
pass
with open(self._wip_json, "w") as f:
json.dump(self.json_data, f, indent=2)
self.process = None
self.launch_preview()
def _close_panels(self):
if self._json_state == 'dirty':
confirm = CBtkMessageBox(title='Confirm Action',
message=f'You have unsaved changes. Do you wish to save these before quitting?',
button1_text='Yes',