-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
827 lines (668 loc) · 29.8 KB
/
Copy pathgui.py
File metadata and controls
827 lines (668 loc) · 29.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
'''
GUI for the config editor, with render and export integrated for conveniency
'''
import json
import copy
import os
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from essentials import *
from mask_to_svg import plot_svg
from norm_config import norm_config
import plotter
# -------------------------------
# Scrollable Frame
# -------------------------------
class ScrollableFrame(ttk.Frame):
_instances = []
_global_mousewheel_bound = False
def __init__(self, container, *args, **kwargs):
super().__init__(container, *args, **kwargs)
ScrollableFrame._instances.append(self)
self.canvas = tk.Canvas(self)
scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.scrollable_frame = ttk.Frame(self.canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: self.canvas.configure(
scrollregion=self.canvas.bbox("all")
)
)
self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.canvas.configure(yscrollcommand=scrollbar.set)
self.canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
if not ScrollableFrame._global_mousewheel_bound:
root = self.winfo_toplevel()
root.bind_all("<MouseWheel>", ScrollableFrame._global_mousewheel)
root.bind_all("<Button-4>", ScrollableFrame._global_mousewheel)
root.bind_all("<Button-5>", ScrollableFrame._global_mousewheel)
ScrollableFrame._global_mousewheel_bound = True
@classmethod
def _global_mousewheel(cls, event):
try:
for instance in list(cls._instances):
if not instance.winfo_exists():
cls._instances.remove(instance)
continue
widget_under_mouse = instance.winfo_containing(event.x_root, event.y_root)
if not widget_under_mouse:
continue
if not cls._is_widget_in_frame(widget_under_mouse, instance):
continue
if "popdown" in str(widget_under_mouse):
continue
instance._on_mousewheel(event)
break
except Exception:
pass
@staticmethod
def _is_widget_in_frame(widget, frame):
current = widget
while current is not None:
if current is frame or current is frame.canvas or current is frame.scrollable_frame:
return True
try:
current = current.master
except Exception:
break
return False
def _on_mousewheel(self, event):
try:
widget_under_mouse = self.canvas.winfo_containing(event.x_root, event.y_root)
if widget_under_mouse and "popdown" in str(widget_under_mouse):
return
if event.num == 4:
self.canvas.yview_scroll(-1, "units")
elif event.num == 5:
self.canvas.yview_scroll(1, "units")
else:
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
except Exception:
pass
# -------------------------------
# UI Variables and Configuration Sync
# -------------------------------
tabs = []
tab_counter = {"next": 1}
SHARED_PREVIEW_HEIGHT = 200 # Default initial uniform height
paned_windows = [] # Add this to track panes across tabs
PANE_MIN_SIZE = 50
empty_state_frame = None
def load_config_file(config_file):
with open(config_file, "r", encoding="utf-8") as f:
raw_config = json.load(f)
return norm_config(raw_config)
def get_current_tab(notebook):
try:
index = notebook.index("current")
except Exception:
return None
if index < 0 or index >= len(tabs):
return None
return tabs[index]
def sync_ui_to_config(config, full_key, ui_vars):
var = ui_vars.get(full_key)
if not var:
return
def _get_parent_and_last(root, keys):
"""Traverse `root` following `keys` until the parent of the final key.
Keys may contain list indices like 'elements[0]'. Returns (parent_obj, last_key_or_index)
"""
obj = root
for part in keys[:-1]:
# handle list index parts like name[0] or nested indices
if "[" in part:
name, rest = part.split("[", 1)
if name:
obj = obj[name]
# process one or multiple indices
idxs = [int(x[:-1]) for x in ("[" + rest).split("[") if x and x.endswith("]")]
for idx in idxs:
obj = obj[idx]
else:
obj = obj[part]
last = keys[-1]
# If last is a list access (e.g. elements[0]) indicate that
if "[" in last:
name, rest = last.split("[", 1)
if name:
parent = obj[name]
else:
parent = obj
# extract final index
final_idx = int(rest[:-1])
return parent, final_idx
else:
return obj, last
keys = full_key.split(".")
parent, last = _get_parent_and_last(config, keys)
parent[last] = convert_numeric_strings(var.get(), last)
def refresh_preview(config, preview_canvas):
try:
grid = plotter.plot(config)
except Exception as msg:
preview_canvas.delete("all")
preview_canvas.create_text(10, 10, text=f"Error when generating destination sign:\n{repr(msg)}", fill="black", font=("Arial", 20, "bold"), anchor="nw")
return
try:
render_preview(config, grid, preview_canvas)
except Exception as msg:
preview_canvas.delete("all")
preview_canvas.create_text(10, 10, text=f"Error when rendering destination sign:\n{repr(msg)}", fill="black", font=("Arial", 20, "bold"), anchor="nw")
# -------------------------------
# Simple Field Renderer (2 columns)
# -------------------------------
def build_simple_field(parent, config, data, key, full_key, preview_canvas, ui_vars):
row = ttk.Frame(parent)
row.grid(sticky="ew", padx=6, pady=2)
row.columnconfigure(1, weight=1)
ttk.Label(row, text=key, width=20).grid(row=0, column=0, sticky="w")
value = data.get(key)
initial = "" if value is None else str(value)
if isinstance(value, bool) or key == "force_caps":
var = tk.BooleanVar(value=value)
ui_vars[full_key] = var
chk = ttk.Checkbutton(row, variable=var)
chk.grid(row=0, column=1, sticky="w")
var.trace_add("write", lambda *args: (sync_ui_to_config(config, full_key, ui_vars), refresh_preview(config, preview_canvas)))
return
if key == "align_type":
var = tk.StringVar(value=initial)
ui_vars[full_key] = var
combo = ttk.Combobox(row, textvariable=var,
values=["top", "middle", "bottom"],
state="readonly")
combo.grid(row=0, column=1, sticky="ew")
for ev in ("<MouseWheel>", "<Button-4>", "<Button-5>"):
combo.bind(ev, lambda e: "break")
combo.bind("<<ComboboxSelected>>", lambda e: (sync_ui_to_config(config, full_key, ui_vars), refresh_preview(config, preview_canvas)))
var.trace_add("write", lambda *args: (sync_ui_to_config(config, full_key, ui_vars), refresh_preview(config, preview_canvas)))
return
if key == "font":
font_list = get_font_list()
var = tk.StringVar(value=initial)
ui_vars[full_key] = var
combo = ttk.Combobox(row, textvariable=var, values=font_list, width=30)
combo.grid(row=0, column=1, sticky="ew")
for ev in ("<MouseWheel>", "<Button-4>", "<Button-5>"):
combo.bind(ev, lambda e: "break")
combo.bind("<<ComboboxSelected>>", lambda e: (sync_ui_to_config(config, full_key, ui_vars), refresh_preview(config, preview_canvas)))
var.trace_add("write", lambda *args: (sync_ui_to_config(config, full_key, ui_vars), refresh_preview(config, preview_canvas)))
return
var = tk.StringVar(value=initial)
ui_vars[full_key] = var
entry = ttk.Entry(row, textvariable=var, width=40)
entry.grid(row=0, column=1, sticky="ew")
var.trace_add("write", lambda *args: (sync_ui_to_config(config, full_key, ui_vars), refresh_preview(config, preview_canvas)))
# -------------------------------
# Recursive Editor
# -------------------------------
def build_editor(parent, config, data, path="", preview_canvas=None, ui_vars=None):
if ui_vars is None:
ui_vars = {}
for key, value in data.items():
full_key = f"{path}.{key}" if path else key
# Special handling for components_middle
if full_key == "components_middle":
build_components_middle(parent, config, value, preview_canvas, ui_vars)
continue
if isinstance(value, dict):
frame = ttk.LabelFrame(parent, text=key)
frame.grid(sticky="ew", padx=6, pady=4)
frame.columnconfigure(1, weight=1)
build_editor(frame, config, value, full_key, preview_canvas, ui_vars)
elif isinstance(value, list):
frame = ttk.LabelFrame(parent, text=f"{key} (list)")
frame.grid(sticky="ew", padx=6, pady=4)
build_list_editor(frame, config, value, full_key, preview_canvas, ui_vars)
else:
build_simple_field(parent, config, data, key, full_key, preview_canvas, ui_vars)
# -------------------------------
# List Editor
# -------------------------------
def build_list_editor(parent, config, lst, path, preview_canvas, ui_vars):
item_frames = []
def get_default_item():
if path in DEFAULT_LIST_ITEMS:
return copy.deepcopy(DEFAULT_LIST_ITEMS[path])
return {}
def render_list():
for f in item_frames:
f.destroy()
item_frames.clear()
for index, item in enumerate(lst):
item_path = f"{path}[{index}]"
frame = ttk.LabelFrame(parent, text=f"Item {index + 1}")
frame.grid(sticky="ew", padx=6, pady=6)
item_frames.append(frame)
# Remove button (top-right)
remove_btn = ttk.Button(
frame,
text="Remove",
width=8,
command=lambda i=index: remove_item(i)
)
remove_btn.grid(row=0, column=1, sticky="e", padx=5, pady=5)
# Container for the item fields
item_container = ttk.Frame(frame)
item_container.grid(row=1, column=0, columnspan=2, sticky="ew", padx=5, pady=5)
build_editor(item_container, config, item, item_path, preview_canvas, ui_vars)
refresh_preview(config, preview_canvas)
def add_item():
lst.append(get_default_item())
render_list()
def remove_item(index):
lst.pop(index)
render_list()
ttk.Button(parent, text="Add Item", command=add_item).grid(pady=4)
render_list()
# -------------------------------
# Middle Section Toggle Logic
# -------------------------------
def build_components_middle(parent, config, middle_dict, preview_canvas, ui_vars):
use_combined_middle = tk.BooleanVar(value="middle" in middle_dict)
frame = ttk.LabelFrame(parent, text="components_middle")
frame.grid(sticky="ew", padx=6, pady=4)
ttk.Checkbutton(
frame,
text="Use combined middle section",
variable=use_combined_middle,
command=lambda: refresh_middle(frame, config, middle_dict, use_combined_middle, preview_canvas, ui_vars)
).grid(sticky="w", padx=6, pady=2)
dynamic = ttk.Frame(frame)
dynamic.grid(sticky="ew")
frame.dynamic_area = dynamic
refresh_middle(frame, config, middle_dict, use_combined_middle, preview_canvas, ui_vars)
# -------------------------------
# Tabs
# -------------------------------
def refresh_middle(frame, config, middle_dict, use_combined_middle, preview_canvas, ui_vars):
dynamic = frame.dynamic_area
for w in dynamic.winfo_children():
w.destroy()
if use_combined_middle.get():
if "middle" not in middle_dict: # up -> middle conversion
middle_dict["middle"] = middle_dict.get("up", DEFAULT_COMPONENTS)
middle_dict.pop("up", None)
build_editor(dynamic, config, {"middle": middle_dict["middle"]}, "components_middle", preview_canvas, ui_vars)
else:
if "middle" in middle_dict: # middle -> up conversion
middle_dict["up"] = middle_dict.get("middle", DEFAULT_COMPONENTS)
middle_dict.pop("middle", None)
if "down" not in middle_dict:
middle_dict["down"] = DEFAULT_COMPONENTS
build_editor(dynamic, config, {"up": middle_dict["up"], "down": middle_dict["down"]}, "components_middle", preview_canvas, ui_vars)
refresh_preview(config, preview_canvas)
def get_tab_title(tab_data):
if tab_data.get("config_file"):
return os.path.basename(tab_data["config_file"])
return tab_data.get("title") or "Untitled"
def save_tab(tab_data, notebook=None, index=None):
config_file = tab_data.get("config_file")
if not config_file:
return save_tab_as(tab_data, notebook=notebook, index=index)
tab_data["title"] = get_tab_title(tab_data)
if notebook is not None and index is not None:
update_tab_title(notebook, index)
save_config(tab_data["config"], config_file)
return config_file
def save_tab_as(tab_data, notebook=None, index=None):
config_file = filedialog.asksaveasfilename(
title="Save Config As",
defaultextension=".json",
filetypes=[("JSON files", "*.json"), ("All files", "*")],
initialdir="./config"
)
if not config_file:
return None
tab_data["config_file"] = config_file
tab_data["title"] = get_tab_title(tab_data)
if notebook is not None and index is not None:
update_tab_title(notebook, index)
save_config(tab_data["config"], config_file)
return config_file
def update_tab_title(notebook, index):
if index is None:
return
if index < 0 or index >= len(tabs):
return
tab_data = tabs[index]
title = get_tab_title(tab_data)
tab_data["title"] = title
try:
notebook.tab(index, text=title)
except Exception:
try:
notebook.tab(notebook.tabs()[index], text=title)
except Exception:
pass
def update_empty_state(notebook):
global empty_state_frame
if empty_state_frame is None or not empty_state_frame.winfo_exists():
return
if len(notebook.tabs()) > 0:
empty_state_frame.pack_forget()
notebook.pack(fill="both", expand=True)
else:
notebook.pack_forget()
empty_state_frame.pack(fill="both", expand=True)
def create_tab(notebook, config=None, config_file=None):
if config is None:
config = copy.deepcopy(DEFAULT_CONFIG)
config = norm_config(config)
ui_vars = {}
frame = ttk.Frame(notebook)
pane = tk.PanedWindow(frame, bg="#888888", sashwidth=15, orient="vertical")
pane.pack(fill="both", expand=True)
paned_windows.append(pane) # Add this tracker line
# LIVE TRACKING FIX: Catch structural position updates as the mouse drags the bar
def on_sash_drag(event):
global SHARED_PREVIEW_HEIGHT
try:
# Look up the actual position pixel coordinate of the top-most sash
coord = pane.sash_coord(0)
if coord and coord[1] > 10:
SHARED_PREVIEW_HEIGHT = coord[1]
except Exception:
pass
# Bind left-mouse drag action on the paned window splitter bar
pane.bind("<B1-Motion>", on_sash_drag)
preview_frame = ttk.Frame(pane, height=SHARED_PREVIEW_HEIGHT)
# Use the shared variable for initialization
preview_canvas = tk.Canvas(preview_frame, height=SHARED_PREVIEW_HEIGHT, bg="white")
preview_canvas.pack(fill="both", expand=True, pady=10)
preview_canvas.bind("<Configure>", lambda e: refresh_preview(config, preview_canvas))
# Use SHARED_PREVIEW_HEIGHT as the exact pane size or minimum size constraint
pane.add(preview_frame, minsize=PANE_MIN_SIZE)
content_frame = ttk.Frame(pane)
pane_hint_frame = ttk.Frame(content_frame)
pane_hint_frame.pack()
pane_hint = ttk.Label(pane_hint_frame, text="Drag gray rectangle up and down to adjust preview's height")
pane_hint.grid(row=0, column=0, pady=2)
tab_data = {
"frame": frame,
"config": config,
"config_file": config_file,
"preview_canvas": preview_canvas,
"ui_vars": ui_vars,
}
scroll = ScrollableFrame(content_frame)
scroll.pack(fill="both", expand=True)
pane.add(content_frame, minsize=PANE_MIN_SIZE)
main_frame = scroll.scrollable_frame
main_frame.columnconfigure(0, weight=1)
main_frame.columnconfigure(1, weight=1)
col1_frame = ttk.Frame(main_frame)
col1_frame.grid(row=1, column=0, sticky="nsew", padx=8, pady=8)
col1_frame.columnconfigure(0, weight=1)
col2_frame = ttk.Frame(main_frame)
col2_frame.grid(row=1, column=1, sticky="nsew", padx=8, pady=8)
col2_frame.columnconfigure(0, weight=1)
col3_frame = ttk.Frame(main_frame)
col3_frame.grid(row=1, column=2, sticky="nsew", padx=8, pady=8)
col3_frame.columnconfigure(0, weight=1)
build_simple_field(col1_frame, config, config, "file_name", "file_name", preview_canvas, ui_vars)
build_editor(col1_frame, config, {"dimensions": config["dimensions"]}, "", preview_canvas, ui_vars)
build_editor(col1_frame, config, {"components_left": config["components_left"]}, "", preview_canvas, ui_vars)
build_editor(col2_frame, config, {"svg_style": config["svg_style"]}, "", preview_canvas, ui_vars)
build_editor(col2_frame, config, {"components_middle": config["components_middle"]}, "", preview_canvas, ui_vars)
build_editor(col3_frame, config, {"components_right": config["components_right"]}, "", preview_canvas, ui_vars)
if config_file:
title = os.path.basename(config_file)
else:
title = f"Untitled {tab_counter['next']}"
tab_counter['next'] += 1
tab_data["title"] = title
tabs.append(tab_data)
notebook.add(frame, text=title)
notebook.select(frame)
update_empty_state(notebook)
return tab_data
def refresh_all_tabs(notebook):
global SHARED_PREVIEW_HEIGHT
# 1. Update only the single active tab's paned layout
current_idx = notebook.index("current")
if current_idx >= 0 and current_idx < len(paned_windows):
try:
pane = paned_windows[current_idx]
if pane.winfo_exists():
pane.sash_place(0, 0, SHARED_PREVIEW_HEIGHT)
except Exception:
pass
# 2. Force structural redrawing of all tabs' graphical canvas plots
for tab_data in tabs:
refresh_preview(tab_data["config"], tab_data["preview_canvas"])
def on_tab_changed(event):
notebook = event.widget
current = get_current_tab(notebook)
if current is None:
return
index = notebook.index("current")
update_tab_title(notebook, index)
# Force alignment of heights when switching tabs
refresh_all_tabs(notebook)
def open_paths(notebook, paths):
broken_paths = []
for path in paths or []:
if not path:
continue
try:
config = load_config_file(path)
except Exception:
broken_paths.append(path)
continue
else:
create_tab(notebook, config, path)
if broken_paths:
messagebox.showerror("Config Error", f"Unable to open or parse the following files:\n" + "\n".join(broken_paths))
def open_files(notebook):
paths = filedialog.askopenfilenames(
title="Open Config Files",
filetypes=[("JSON files", "*.json"), ("All files", "*")],
initialdir="./config"
)
open_paths(notebook, paths)
def close_current_tab(notebook):
try:
index = notebook.index("current")
except Exception:
return
if index < 0 or index >= len(tabs):
return
notebook.forget(index)
del tabs[index]
update_empty_state(notebook)
# -------------------------------
# Save, Render and Export
# -------------------------------
def save_current_tab(notebook):
tab_data = get_current_tab(notebook)
if tab_data is None:
return
try:
index = notebook.index("current")
except Exception:
index = None
save_tab(tab_data, notebook=notebook, index=index)
def save_current_tab_as(notebook):
tab_data = get_current_tab(notebook)
if tab_data is None:
return
try:
index = notebook.index("current")
except Exception:
index = None
save_tab_as(tab_data, notebook=notebook, index=index)
def export_current_tab(notebook):
tab_data = get_current_tab(notebook)
if tab_data is None:
messagebox.showwarning("Export", "No tab open. Create or open a config first.")
return
try:
export_tab(tab_data["config"])
except Exception as e:
messagebox.showerror("Export Error", f"An error occurred while exporting the tab:\n{str(e)}")
def render_preview(config, mask, preview_canvas):
preview_canvas.delete("all")
preview_canvas.create_text(10, 10, text="Refreshing...", fill="black", font=("Arial", 20, "bold"), anchor="nw")
width_px = config["dimensions"].get("width_px", None)
height_px = config["dimensions"].get("height_px", None)
for _ in (width_px, height_px):
if not isinstance(_, int): raise TypeError("Dimension parameter must be integer.")
if _ <= 0: raise ValueError("Dimension parameter must be positive.")
style = config.get("svg_style", {})
legacy_style = config.get("svg_stype", {})
radius = style.get("radius", None)
if radius is None:
radius_width = style.get("radius_width", legacy_style.get("radius_width"))
radius_height = style.get("radius_height", legacy_style.get("radius_height"))
else:
radius_height = radius_width = radius
for _ in (radius_height, radius_width):
if not isinstance(_, (int, float)): raise TypeError("Radius parameter must be numerical.")
if _ <= 0: raise ValueError("Radius dimension must be positive.")
left_padding = style.get("left_padding", None)
right_padding = style.get("right_padding", None)
top_padding = style.get("top_padding", None)
bottom_padding = style.get("bottom_padding", None)
bg_color = normalize_color(style.get("bg_color", None))
for _ in (left_padding, right_padding, top_padding, bottom_padding):
if not isinstance(_, (int, float)): raise TypeError("Padding parameter must be numerical.")
if _ < 0: raise ValueError("Padding parameter must be non negative.")
px_width = radius_width * 2 + left_padding + right_padding
px_height = radius_height * 2 + top_padding + bottom_padding
canvas_width = px_width * width_px
canvas_height = px_height * height_px
GUI_w = preview_canvas.winfo_width()
GUI_h = preview_canvas.winfo_height()
if GUI_w <= 0 or GUI_h <= 0 or canvas_width <= 0 or canvas_height <= 0:
raise ValueError("Canvas and GUI related parameters must be positive")
scale = min(GUI_w / canvas_width, GUI_h / canvas_height)
plot_width = canvas_width * scale
plot_height = canvas_height * scale
plot_lb = (GUI_w - plot_width ) / 2
plot_ub = (GUI_h - plot_height) / 2
plot_rb = GUI_w - plot_lb
plot_db = GUI_h - plot_ub
preview_canvas.delete("all")
# Plot background first (if exists) so that empty pixels will show the bg color instead of white
if bg_color != None:
preview_canvas.create_rectangle(plot_lb,plot_ub,plot_rb,plot_db,fill="#%02x%02x%02x" % bg_color[0:3])
for row_i, row in enumerate(mask):
for col_i, color in enumerate(row):
if not isinstance(color, (tuple,list)): continue
lb = left_padding + col_i * px_width
ub = top_padding + row_i * px_height
rb = lb + radius_width * 2
db = ub + radius_height * 2
ha = lambda x, tot, l, r: l + (r-l) * (x / tot)
preview_canvas.create_oval(
ha(lb,canvas_width,plot_lb,plot_rb),ha(ub,canvas_height,plot_ub,plot_db),
ha(rb,canvas_width,plot_lb,plot_rb),ha(db,canvas_height,plot_ub,plot_db),
fill="#%02x%02x%02x" % color,
outline=""
)
def save_config(config, config_file):
with open(config_file, "w") as f:
json.dump(config, f, indent=4)
messagebox.showinfo("Saved", "Configuration saved!")
def export_tab(config, CLI_mode=False):
# Added support for CLI mode where messagebox is not available when being called in the main module
filename = config.get("file_name") or "LED.svg"
grid = plotter.plot(config)
# Detect if the destination file exists
try:
with open(SCRIPT_DIR + "/output/" + filename, "r") as f:
_ = f.read()
except FileNotFoundError:
# File does not exist - export
pass
else:
# File exist - ask
override_msg = f"{filename} exists in the output folder, are you sure you want to override the file?"
if CLI_mode:
print(override_msg)
resp = input("Type 'yes' or 'y' to override, anything else to cancel: ")
override_resp = resp.strip().lower() in ("yes","y")
else:
override_resp = messagebox.askyesno("File Override Confirmation", override_msg)
if not override_resp:
if CLI_mode:
print(f"Export for {filename} cancelled.")
return
# Plot
try:
plot_svg(grid, config.get("svg_style", {}), config.get("file_name"))
except Exception as e:
if CLI_mode:
print(f"There is an error with the style configuration:\n{e}")
else:
messagebox.showinfo("Error","There is an error with the style configuration:\n"+str(e))
else:
if CLI_mode:
print(f"Headsign exported as {filename}!")
else:
messagebox.showinfo("Exported", f"Headsign exported as {filename}!")
# -------------------------------
# GUI Setup
# -------------------------------
def create_gui(GUI_w = 1400, GUI_h = 900, initial_files=None):
"""Create and start the GUI"""
root = tk.Tk()
root.geometry(f"{GUI_w}x{GUI_h}")
root.title("LED Destination Sign Generator")
global empty_state_frame
menubar = tk.Menu(root)
file_menu = tk.Menu(menubar, tearoff=0)
notebook = ttk.Notebook(root)
empty_state_frame = ttk.Frame(root)
empty_state_inner = ttk.Frame(empty_state_frame)
empty_state_inner.pack(expand=True)
style = ttk.Style()
style.configure("Big.TButton", font=("Arial", 15), padding=10)
# Big Header
ttk.Label(
empty_state_inner, text="No configuration file is open yet.", font=("Arial", 30, "bold")
).pack(pady=(0, 10))
# Big Subtitle
ttk.Label(
empty_state_inner,
text="Open an existing config to start editing or create a new tab.",
font=("Arial", 18)
).pack(pady=(0, 25))
# Button Container
button_frame = ttk.Frame(empty_state_inner)
button_frame.pack(pady=15)
# Big Buttons via Style
ttk.Button(
button_frame, text="Open Config", style="Big.TButton", command=lambda: open_files(notebook)
).pack(side="left", padx=15)
ttk.Button(
button_frame, text="New Config", style="Big.TButton", command=lambda: create_tab(notebook)
).pack(side="left", padx=15)
file_menu.add_command(label="New Tab", command=lambda: create_tab(notebook), accelerator="Ctrl+N")
file_menu.add_command(label="Open...", command=lambda: open_files(notebook), accelerator="Ctrl+O")
file_menu.add_separator()
file_menu.add_command(label="Save", command=lambda: save_current_tab(notebook), accelerator="Ctrl+S")
file_menu.add_command(label="Save As...", command=lambda: save_current_tab_as(notebook), accelerator="Ctrl+Shift+S")
file_menu.add_command(label="Export", command=lambda: export_current_tab(notebook), accelerator="Ctrl+E")
file_menu.add_separator()
file_menu.add_command(label="Close Tab", command=lambda: close_current_tab(notebook), accelerator="Ctrl+W")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit, accelerator="Ctrl+Q")
root.bind_all("<Control-n>", lambda event: create_tab(notebook))
root.bind_all("<Control-o>", lambda event: open_files(notebook))
root.bind_all("<Control-s>", lambda event: save_current_tab(notebook))
root.bind_all("<Control-Shift-S>", lambda event: save_current_tab_as(notebook))
root.bind_all("<Control-e>", lambda event: export_current_tab(notebook))
root.bind_all("<Control-w>", lambda event: close_current_tab(notebook))
root.bind_all("<Control-q>", lambda event: root.quit())
menubar.add_cascade(label="File", menu=file_menu)
root.config(menu=menubar)
notebook.pack(fill="both", expand=True)
notebook.bind("<<NotebookTabChanged>>", on_tab_changed)
update_empty_state(notebook)
if initial_files:
open_paths(notebook, initial_files)
root.mainloop()