-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtabs.py
More file actions
983 lines (784 loc) · 37 KB
/
tabs.py
File metadata and controls
983 lines (784 loc) · 37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
"""
Tabs - Tab creation and template management functions for KiRender
This module re-exports all tab creation functions from their separate modules
and contains the unified template system helper functions.
"""
import os
import wx
import wx.lib.scrolledpanel as scrolled
# Re-export tab creation functions from their modules
from .spinrender_tab import create_spinrender_tab
from .static_tab import create_static_tab
from .svg_tab import create_svg_tab
from .pinout_tab import create_pinout_tab
from .export_tabs import create_export3d_tab, create_bom_tab, create_settings_tab
# Re-export TemplateEditorDialog
from .template_ui import TemplateEditorDialog
# Import CLI validator functions (validation logic lives in cli_validator.py)
from .cli_validator import (
CLIValidator,
ValidationLevel,
validate_cli_params,
normalize_params,
validate_and_normalize
)
# Import UI validation functions (wxPython integration)
from .validation_ui import (
validate_and_log,
validate_before_render,
update_validation_status
)
# Aliases for internal use (underscore prefix convention)
_validate_and_log = validate_and_log
_validate_before_render = validate_before_render
_validate_params_background = update_validation_status
# ============== UNIFIED TEMPLATE SYSTEM ==============
# Single code path for all template types: spinrender, static, pinout
def _get_template_type_for_mode(mode: str) -> str:
"""Map UI mode to template_type."""
mode_map = {
"animation": "spinrender",
"spinrender": "spinrender",
"static": "static",
"pinout": "pinout"
}
return mode_map.get(mode, mode)
def _get_choice_ctrl(dialog, template_type: str):
"""Get the choice control for a template type."""
ctrl_map = {
"spinrender": "anim_template_choice",
"static": "static_template_choice",
"pinout": "pinout_template_choice"
}
return getattr(dialog, ctrl_map.get(template_type, "anim_template_choice"), None)
def _refresh_template_dropdown(dialog, template_type: str, force_reload: bool = False):
"""Refresh the template dropdown for any tab type.
Args:
dialog: The main dialog
template_type: Type of template (spinrender, static, pinout)
force_reload: If True, bypass cache and reload from disk
"""
from .template_manager import load_all_templates
# Cache templates per type to avoid repeated disk reads
cache_attr = f'_templates_cache_{template_type}'
if hasattr(dialog, cache_attr) and not force_reload:
templates = getattr(dialog, cache_attr)
else:
templates = load_all_templates(template_type)
setattr(dialog, cache_attr, templates)
# Store templates for later use
setattr(dialog, f'_{template_type}_templates', templates)
choice_ctrl = _get_choice_ctrl(dialog, template_type)
if not choice_ctrl:
return
choice_ctrl.Clear()
# NO "None (Custom)" - template is always required as base
# First template in list becomes default
sorted_names = sorted(templates.keys())
for name in sorted_names:
prefix = "🔒 " if templates[name].get("_is_builtin") else "🔓 "
choice_ctrl.Append(f"{prefix}{name}")
# Only auto-select first template on initial load (not force_reload)
# When force_reload=True, caller will select the appropriate template
if sorted_names and not force_reload:
choice_ctrl.SetSelection(0)
# Apply the first template
first_template = templates[sorted_names[0]]
setattr(dialog, f'_{template_type}_current_template', first_template)
_apply_template(dialog, first_template, template_type)
is_builtin = first_template.get("_is_builtin", False)
_set_controls_enabled(dialog, template_type, not is_builtin)
_update_template_status(dialog, template_type, first_template)
_update_cli_preview(dialog, template_type)
def _on_template_selected(dialog, template_type: str):
"""Handle template selection from any tab dropdown."""
choice_ctrl = _get_choice_ctrl(dialog, template_type)
if not choice_ctrl:
return
selection = choice_ctrl.GetStringSelection()
# Remove emoji prefix if present
clean_name = selection.replace("🔒 ", "").replace("🔓 ", "")
templates = getattr(dialog, f'_{template_type}_templates', {})
if clean_name in templates:
template = templates[clean_name]
setattr(dialog, f'_{template_type}_current_template', template)
setattr(dialog, f'_current_{template_type.replace("spinrender", "anim")}_template', template) # For estimate
_apply_template(dialog, template, template_type)
# Update JSON preview
_update_json_preview(dialog, template_type, template)
# Built-in templates are locked
is_builtin = template.get("_is_builtin", False)
_update_template_status(dialog, template_type, template)
_update_cli_preview(dialog, template_type)
if is_builtin:
dialog.log(f"{template_type.title()}: Applied built-in template '{clean_name}'")
else:
dialog.log(f"{template_type.title()}: Applied user template '{clean_name}'")
def _update_json_preview(dialog, template_type: str, template):
"""Update the JSON preview panel for a tab."""
if template_type == "spinrender":
from .spinrender_tab import update_anim_json_preview
update_anim_json_preview(dialog, template)
elif template_type == "static":
from .static_tab import update_static_json_preview
update_static_json_preview(dialog, template)
elif template_type == "pinout":
from .pinout_tab import update_pinout_json_preview
update_pinout_json_preview(dialog, template)
def _apply_template(dialog, template, template_type: str):
"""Apply template settings to dialog controls for any tab type."""
params = template.get("cli_params", {})
# For new architecture, template params are shown in JSON preview
# No need to apply to UI controls that have been removed
if template_type == "spinrender":
# Store template for rendering (no UI controls to update)
pass
elif template_type == "static":
# Store template for rendering (no UI controls to update)
pass
elif template_type == "pinout":
# Pinout still has side control (render-time setting)
if hasattr(dialog, 'pinout_side'):
side = params.get("side", "top")
idx = dialog.pinout_side.FindString(side)
if idx != wx.NOT_FOUND:
dialog.pinout_side.SetSelection(idx)
# Other settings are now template-only, shown in JSON preview
def _set_controls_enabled(dialog, template_type: str, enabled: bool):
"""Enable or disable controls for a template type."""
# Most controls have been moved to template editor
# Only render-time controls remain
controls_map = {
"spinrender": [], # All moved to template
"static": [], # All moved to template
"pinout": ['pinout_side'], # Only side is render-time
}
controls = controls_map.get(template_type, [])
for ctrl_name in controls:
ctrl = getattr(dialog, ctrl_name, None)
if ctrl:
ctrl.Enable(enabled)
def _update_template_status(dialog, template_type: str, template):
"""Update the template status indicator."""
status_ctrl_map = {
"spinrender": "anim_template_status",
"static": "static_template_status",
"pinout": "pinout_template_status"
}
status_ctrl = getattr(dialog, status_ctrl_map.get(template_type, ""), None)
if not status_ctrl:
return
if template is None:
status_ctrl.SetLabel("Mode: Custom (manual settings)")
status_ctrl.SetForegroundColour(wx.Colour(100, 100, 100))
else:
name = template.get("name", "Unknown")
is_builtin = template.get("_is_builtin", False)
locked = "🔒 Built-in" if is_builtin else "User"
status_ctrl.SetLabel(f"✓ Using template: {name} [{locked}]")
status_ctrl.SetForegroundColour(wx.Colour(0, 100, 0))
status_ctrl.GetParent().Layout()
def log_cli_command(dialog, template_type: str, pcb_path: str, output_path: str):
"""Log the CLI command to the output log."""
from .cli_builder import get_cli_string
params = getattr(dialog, f'_{template_type}_cli_params', None)
if not params:
params = _get_ui_params(dialog, template_type)
kicad_cli = getattr(dialog, 'cli_path', None)
if kicad_cli:
kicad_cli = kicad_cli.GetValue()
else:
kicad_cli = "kicad-cli"
cli_string = get_cli_string(params, kicad_cli, pcb_path, output_path)
dialog.log(f"CLI: {cli_string}")
def _show_preview(dialog, template_type: str):
"""Generate and show a quick preview render."""
import subprocess
import tempfile
from .cli_builder import build_cli_command
# Get current template
template = getattr(dialog, f'_{template_type}_current_template', None)
if not template:
dialog.log(f"No template selected for {template_type}")
wx.MessageBox("Please select a template first.", "Preview", wx.OK | wx.ICON_WARNING)
return
cli_params = template.get("cli_params", {})
# Get actual configured dimensions from template to maintain aspect ratio
actual_w = cli_params.get("width", 1920)
actual_h = cli_params.get("height", 1080)
# Ensure we don't divide by zero
if actual_h <= 0:
actual_h = 1080
if actual_w <= 0:
actual_w = 1920
# Scale down while maintaining aspect ratio (max 640 on longest edge)
MAX_PREVIEW = 640
aspect = actual_w / actual_h
if actual_w >= actual_h:
preview_w = MAX_PREVIEW
preview_h = int(MAX_PREVIEW / aspect)
else:
preview_h = MAX_PREVIEW
preview_w = int(MAX_PREVIEW * aspect)
# Build preview params from template
preview_params = {
"width": preview_w,
"height": preview_h,
"quality": "basic", # Fast preview
"zoom": cli_params.get("zoom", 1.0),
"background": cli_params.get("background", "transparent"),
"perspective": cli_params.get("perspective", False),
}
# Get side for all template types
if template_type == "spinrender":
# SpinRender always needs a side - default to "top"
preview_params["side"] = cli_params.get("side", "top")
# Build rotate string from tilt values for safe zoom calculation
# This is critical for corner clipping prevention
tilt_x = dialog.tilt_x.GetValue() if hasattr(dialog, 'tilt_x') else 0
tilt_y = dialog.tilt_y.GetValue() if hasattr(dialog, 'tilt_y') else 0
tilt_z = dialog.tilt_z.GetValue() if hasattr(dialog, 'tilt_z') else 0
preview_params["rotate"] = f"{tilt_x},{tilt_y},{tilt_z}"
elif template_type == "static":
# Use first checked view or default to top
side = "top"
for view, cb_name in [("top", "view_top"), ("bottom", "view_bottom"),
("front", "view_front"), ("back", "view_back")]:
cb = getattr(dialog, cb_name, None)
if cb and cb.GetValue():
side = view
break
preview_params["side"] = side
elif template_type == "pinout":
if hasattr(dialog, 'pinout_side'):
preview_params["side"] = dialog.pinout_side.GetStringSelection()
# ====== ADD BOARD DIMENSIONS FOR ROTATION-ZOOM CLIPPING PREVENTION ======
# Get board dimensions for safe zoom calculation
if hasattr(dialog, '_get_board_dimensions'):
board_w, board_h = dialog._get_board_dimensions()
if board_w and board_h:
preview_params["board_width"] = board_w
preview_params["board_height"] = board_h
# Enable auto-safe-zoom to prevent corner clipping during rotation
preview_params["auto_safe_zoom"] = True
# ====== NORMALIZE AND VALIDATE CLI PARAMETERS ======
dialog.log("-" * 40)
dialog.log(f"Processing CLI parameters for {template_type} preview...")
dialog.log(f"[DEBUG] Before normalize: zoom={preview_params.get('zoom')}, rotate={preview_params.get('rotate')}")
dialog.log(f"[DEBUG] Board dims: {preview_params.get('board_width')}x{preview_params.get('board_height')}mm")
# Normalize params first (fixes negative rotation, clamps values, auto-adjusts zoom for rotation)
preview_params, norm_logs = normalize_params(preview_params)
# Log all normalization messages (including debug)
if norm_logs:
for log_msg in norm_logs:
if log_msg.startswith("[DEBUG]"):
dialog.log(log_msg)
else:
dialog.log_warning(f"⚠️ {log_msg}")
dialog.log(f"[DEBUG] After normalize: zoom={preview_params.get('zoom')}")
# Validate the normalized params
if not _validate_and_log(dialog, preview_params, f"{template_type} preview"):
if hasattr(dialog, 'log_error'):
dialog.log_error("Preview aborted due to validation errors.")
else:
dialog.log("Preview aborted due to validation errors.")
return
# Create temp file for preview
temp_dir = tempfile.gettempdir()
preview_file = os.path.join(temp_dir, f"kirender_preview_{template_type}.png")
# Build CLI args using the unified builder
kicad_cli = dialog.cli_path.GetValue() if hasattr(dialog, 'cli_path') else "kicad-cli"
pcb_path = dialog.pcb_path
args = build_cli_command(preview_params, kicad_cli, pcb_path, preview_file)
dialog.log(f"Generating preview ({preview_w}x{preview_h}, aspect {actual_w}x{actual_h})...")
dialog.log(f"CLI: {' '.join(args)}")
try:
# Run render synchronously (quick at this size)
result = subprocess.run(args, capture_output=True, text=True, timeout=30)
if result.returncode == 0 and os.path.exists(preview_file):
if hasattr(dialog, 'log_success'):
dialog.log_success("Preview ready!")
else:
dialog.log("Preview ready!")
# Show preview in a dialog
_show_preview_dialog(dialog, preview_file, template_type, preview_w, preview_h, actual_w, actual_h)
else:
if hasattr(dialog, 'log_error'):
dialog.log_error(f"Preview failed: {result.stderr}")
else:
dialog.log(f"Preview failed: {result.stderr}")
wx.MessageBox(f"Preview render failed:\n{result.stderr}", "Preview Error", wx.OK | wx.ICON_ERROR)
except subprocess.TimeoutExpired:
dialog.log("Preview timed out (>30s)")
wx.MessageBox("Preview render timed out.", "Preview Error", wx.OK | wx.ICON_ERROR)
except Exception as e:
dialog.log(f"Preview error: {e}")
wx.MessageBox(f"Preview error: {e}", "Preview Error", wx.OK | wx.ICON_ERROR)
def _show_preview_dialog(parent, image_path: str, template_type: str,
preview_w: int = 640, preview_h: int = 480,
actual_w: int = 1600, actual_h: int = 900):
"""Show preview image in a dialog."""
if not os.path.exists(image_path):
return
# Adjust dialog size based on preview aspect ratio
dlg_w = min(preview_w + 40, 720)
dlg_h = min(preview_h + 120, 620)
dlg = wx.Dialog(parent, title=f"Preview - {template_type.title()}",
size=(dlg_w, dlg_h), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
sizer = wx.BoxSizer(wx.VERTICAL)
# Load and display image at actual size (no scaling needed, already correct size)
img = wx.Image(image_path, wx.BITMAP_TYPE_PNG)
if img.IsOk():
bmp = wx.StaticBitmap(dlg, bitmap=wx.Bitmap(img))
sizer.Add(bmp, 1, wx.ALL | wx.ALIGN_CENTER, 10)
# Info label
info = wx.StaticText(dlg, label=f"Preview: {preview_w}x{preview_h} (basic quality)\nActual render: {actual_w}x{actual_h}")
info.SetForegroundColour(wx.Colour(100, 100, 100))
sizer.Add(info, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, 10)
# Close button
close_btn = wx.Button(dlg, wx.ID_OK, "Close")
sizer.Add(close_btn, 0, wx.ALIGN_CENTER | wx.BOTTOM, 10)
dlg.SetSizer(sizer)
dlg.ShowModal()
dlg.Destroy()
def _update_cli_preview(dialog, template_type: str):
"""Store the CLI preview for logging when render starts and validate in background."""
from .template_manager import get_cli_string
# Get current template or build params from UI
current_template = getattr(dialog, f'_{template_type}_current_template', None)
if current_template:
params = current_template.get("cli_params", {})
else:
# Build params from current UI values
params = _get_ui_params(dialog, template_type)
# Store params for CLI logging when render starts
setattr(dialog, f'_{template_type}_cli_params', params)
# Run background validation (non-blocking, just log results)
_validate_params_background(dialog, params, template_type)
def _get_ui_params(dialog, template_type: str) -> dict:
"""Get current parameter values from template for CLI preview."""
# Get current template
template = getattr(dialog, f'_{template_type}_current_template', None)
if not template:
return {}
cli_params = template.get("cli_params", {})
params = {
"width": cli_params.get("width", 1920),
"height": cli_params.get("height", 1080),
"zoom": cli_params.get("zoom", 1.0),
"background": cli_params.get("background", "transparent"),
"quality": cli_params.get("quality", "high"),
"perspective": cli_params.get("perspective", False),
}
if template_type == "spinrender":
# Tilt/rotation from UI (render-time)
if hasattr(dialog, 'tilt_x'):
tilt_x = dialog.tilt_x.GetValue()
tilt_y = dialog.tilt_y.GetValue() if hasattr(dialog, 'tilt_y') else 0
tilt_z = dialog.tilt_z.GetValue() if hasattr(dialog, 'tilt_z') else 0
if tilt_x or tilt_y or tilt_z:
params["rotate"] = f"{tilt_x},{tilt_y},{tilt_z}"
# Animation-specific info for display
if hasattr(dialog, 'anim_frames'):
params["_frames"] = dialog.anim_frames.GetValue()
if hasattr(dialog, 'anim_fps'):
params["_fps"] = dialog.anim_fps.GetValue()
if hasattr(dialog, 'anim_revs'):
params["_revolutions"] = dialog.anim_revs.GetValue()
# Safe zoom params
params["safety_margin"] = cli_params.get("safety_margin", 5)
params["component_height"] = cli_params.get("component_height", 10)
elif template_type == "static":
# Views from UI (render-time)
pass
elif template_type == "pinout":
# Side from UI (render-time)
if hasattr(dialog, 'pinout_side'):
params["side"] = dialog.pinout_side.GetStringSelection()
# Camera settings from template
params["pan"] = cli_params.get("pan", "")
params["pivot"] = cli_params.get("pivot", "")
params["rotate"] = cli_params.get("rotate", "")
return params
def _open_template_folder():
"""Open the templates folder in the system file explorer."""
import subprocess
import sys
from .template_manager import TEMPLATES_DIR
if sys.platform == 'win32':
os.startfile(TEMPLATES_DIR)
elif sys.platform == 'darwin':
subprocess.run(['open', TEMPLATES_DIR])
else:
subprocess.run(['xdg-open', TEMPLATES_DIR])
def _show_manage_menu(dialog, btn, template_type: str):
"""Show unified manage dropdown menu for any template type."""
from .template_manager import load_all_templates, delete_template, save_template
menu = wx.Menu()
templates = load_all_templates(template_type)
choice_ctrl = _get_choice_ctrl(dialog, template_type)
if not choice_ctrl:
return
current = choice_ctrl.GetStringSelection().replace("🔒 ", "").replace("🔓 ", "")
is_builtin = templates.get(current, {}).get("_is_builtin", False)
# New Template
id_new = wx.NewId()
menu.Append(id_new, "New Template...")
dialog.Bind(wx.EVT_MENU, lambda e: _create_new_template(dialog, template_type), id=id_new)
# Save Current As...
id_save = wx.NewId()
menu.Append(id_save, "Save Current Settings As...")
dialog.Bind(wx.EVT_MENU, lambda e: _save_as_template(dialog, template_type), id=id_save)
menu.AppendSeparator()
# Edit selected (opens editor, only for user templates)
id_edit = wx.NewId()
edit_label = f'Edit "{current}"...'
item_edit = menu.Append(id_edit, edit_label)
item_edit.Enable(not is_builtin)
dialog.Bind(wx.EVT_MENU, lambda e: _edit_template(dialog, template_type, current), id=id_edit)
# Duplicate selected
id_dup = wx.NewId()
dup_label = f'Duplicate "{current}"...'
item_dup = menu.Append(id_dup, dup_label)
dialog.Bind(wx.EVT_MENU, lambda e: _duplicate_template(dialog, template_type, current), id=id_dup)
# Delete (disabled if builtin)
id_del = wx.NewId()
del_label = f'Delete "{current}"'
item_del = menu.Append(id_del, del_label)
item_del.Enable(not is_builtin)
dialog.Bind(wx.EVT_MENU, lambda e: _delete_template_action(dialog, template_type, current), id=id_del)
menu.AppendSeparator()
# View All Templates
id_view = wx.NewId()
menu.Append(id_view, "View All Templates...")
dialog.Bind(wx.EVT_MENU, lambda e: _show_template_manager(dialog, template_type), id=id_view)
btn.PopupMenu(menu, 0, btn.GetSize().height)
menu.Destroy()
def _select_and_apply_template(dialog, template_type: str, name: str):
"""Select a template in dropdown and apply it."""
choice = _get_choice_ctrl(dialog, template_type)
if not choice:
return
# Templates in dropdown have emoji prefix, try to find with prefix
templates = getattr(dialog, f'_{template_type}_templates', {})
is_builtin = templates.get(name, {}).get("_is_builtin", False)
prefix = "🔒 " if is_builtin else "🔓 "
# Try with prefix first
idx = choice.FindString(f"{prefix}{name}")
if idx == wx.NOT_FOUND:
# Try without prefix (in case format changed)
idx = choice.FindString(name)
if idx != wx.NOT_FOUND:
choice.SetSelection(idx)
_on_template_selected(dialog, template_type)
def _create_new_template(dialog, template_type: str):
"""Open template editor to create a new template."""
from .template_manager import get_empty_template
template = get_empty_template(template_type)
dlg = TemplateEditorDialog(dialog, template, template_type, is_new=True)
if dlg.ShowModal() == wx.ID_OK:
name = dlg.result.get('name', '')
dialog.log(f"Created template: {name}")
_refresh_template_dropdown(dialog, template_type, force_reload=True)
# Select and apply the new template
_select_and_apply_template(dialog, template_type, name)
dlg.Destroy()
def _save_as_template(dialog, template_type: str):
"""Save current UI settings as a new template via editor."""
from .template_manager import get_empty_template
# Build template from current UI values
template = get_empty_template(template_type)
template["name"] = "My Template"
template["description"] = "Custom template"
# Gather CLI params from current UI
params = _get_ui_params(dialog, template_type)
template["cli_params"].update(params)
# Open editor with prefilled values
dlg = TemplateEditorDialog(dialog, template, template_type, is_new=True)
if dlg.ShowModal() == wx.ID_OK:
name = dlg.result.get('name', '')
dialog.log(f"Created template: {name}")
_refresh_template_dropdown(dialog, template_type, force_reload=True)
# Select and apply the new template
_select_and_apply_template(dialog, template_type, name)
dlg.Destroy()
def _edit_template(dialog, template_type: str, name: str):
"""Edit an existing user template via editor dialog."""
from .template_manager import load_all_templates
templates = load_all_templates(template_type)
if name not in templates:
return
template = templates[name]
if template.get("_is_builtin"):
wx.MessageBox(f'Cannot edit built-in template "{name}".\n\nUse "Duplicate" to create an editable copy.',
"Edit Template", wx.OK | wx.ICON_WARNING)
return
dlg = TemplateEditorDialog(dialog, template.copy(), template_type, is_new=False)
if dlg.ShowModal() == wx.ID_OK:
new_name = dlg.result.get('name', name)
dialog.log(f"Updated template: {new_name}")
# Force reload to get freshly saved template from disk
_refresh_template_dropdown(dialog, template_type, force_reload=True)
# Re-select the edited template and apply
_select_and_apply_template(dialog, template_type, new_name)
dlg.Destroy()
def _duplicate_template(dialog, template_type: str, name: str):
"""Duplicate an existing template via editor."""
from .template_manager import load_all_templates
templates = load_all_templates(template_type)
if name not in templates:
return
# Copy template and open editor
template = templates[name].copy()
template["cli_params"] = templates[name].get("cli_params", {}).copy()
template["name"] = f"{name} Copy"
template["locked"] = False
template.pop("_filepath", None)
template.pop("_is_builtin", None)
dlg = TemplateEditorDialog(dialog, template, template_type, is_new=True)
if dlg.ShowModal() == wx.ID_OK:
name = dlg.result.get('name', '')
dialog.log(f"Duplicated template as: {name}")
_refresh_template_dropdown(dialog, template_type, force_reload=True)
# Select and apply the new template
_select_and_apply_template(dialog, template_type, name)
dlg.Destroy()
def _delete_template_action(dialog, template_type: str, name: str):
"""Delete a user template."""
from .template_manager import load_all_templates, delete_template
templates = load_all_templates(template_type)
if name not in templates:
return
template = templates[name]
if template.get("_is_builtin"):
wx.MessageBox(f'Cannot delete built-in template "{name}".', "Delete Template", wx.OK | wx.ICON_WARNING)
return
result = wx.MessageBox(
f'Delete template "{name}"?\n\nThis cannot be undone.',
"Confirm Delete",
wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION
)
if result == wx.YES:
if delete_template(template):
dialog.log(f"Deleted template: {name}")
_refresh_template_dropdown(dialog, template_type, force_reload=True)
def _show_template_manager(dialog, template_type: str):
"""Show unified template management dialog."""
from .template_manager import load_all_templates, delete_template, duplicate_template
templates = load_all_templates(template_type)
# Build list of templates with info
items = []
sorted_names = sorted(templates.keys())
for name in sorted_names:
tmpl = templates[name]
status = "🔒 Built-in" if tmpl.get("_is_builtin") else "🔓 User"
desc = tmpl.get("description", "")[:40]
items.append(f"{name} [{status}] - {desc}")
if not items:
wx.MessageBox(f"No {template_type} templates found.", "Templates", wx.OK | wx.ICON_INFORMATION)
return
dlg = wx.SingleChoiceDialog(
dialog,
f"Select a {template_type} template to manage:",
f"{template_type.title()} Templates",
items
)
if dlg.ShowModal() == wx.ID_OK:
selected_idx = dlg.GetSelection()
selected_name = sorted_names[selected_idx]
template = templates[selected_name]
# Show action menu
is_builtin = template.get("_is_builtin", False)
actions = ["Apply", "Duplicate"]
if not is_builtin:
actions.append("Delete")
action_dlg = wx.SingleChoiceDialog(
dialog,
f"Action for '{selected_name}':",
"Template Action",
actions
)
if action_dlg.ShowModal() == wx.ID_OK:
action = actions[action_dlg.GetSelection()]
if action == "Apply":
# Select this template in dropdown
choice_ctrl = _get_choice_ctrl(dialog, template_type)
if choice_ctrl:
prefix = "🔒 " if is_builtin else "🔓 "
idx = choice_ctrl.FindString(f"{prefix}{selected_name}")
if idx != wx.NOT_FOUND:
choice_ctrl.SetSelection(idx)
_on_template_selected(dialog, template_type)
elif action == "Delete":
if delete_template(template):
dialog.log(f"Deleted template: {selected_name}")
_refresh_template_dropdown(dialog, template_type, force_reload=True)
elif action == "Duplicate":
name_dlg = wx.TextEntryDialog(
dialog,
"New template name:",
"Duplicate Template",
f"{selected_name} Copy"
)
if name_dlg.ShowModal() == wx.ID_OK:
new_name = name_dlg.GetValue().strip()
if new_name:
duplicate_template(template, new_name)
dialog.log(f"Duplicated template as: {new_name}")
_refresh_template_dropdown(dialog, template_type, force_reload=True)
name_dlg.Destroy()
action_dlg.Destroy()
dlg.Destroy()
# ============== SVG Template Functions ==============
# SVG templates use separate system (different schema from CLI-based templates)
# SVG export doesn't use kicad-cli pcb render, so has its own template format
def _refresh_svg_template_dropdown(dialog):
"""Refresh the SVG template dropdown choices."""
from .svg_templates import load_svg_templates
templates = load_svg_templates()
dialog.svg_template_choice.Clear()
# SVG still has "None" option as it's a layer selection, not CLI params
dialog.svg_template_choice.Append("None (Custom)")
for name in sorted(templates.keys()):
dialog.svg_template_choice.Append(name)
dialog.svg_template_choice.SetSelection(0)
def _on_svg_template_selected(dialog):
"""Handle SVG template selection from dropdown."""
from .svg_templates import load_svg_templates
from .svg import PCB_LAYERS, PAGE_SIZE_OPTIONS, DRILL_SHAPE_OPTIONS
selection = dialog.svg_template_choice.GetStringSelection()
if selection == "None (Custom)":
dialog.svg_template = None
dialog.log("SVG Template: None (Custom)")
return
templates = load_svg_templates()
if selection in templates:
template = templates[selection]
dialog.svg_template = template.copy()
dialog.svg_template["name"] = selection
# Apply template to controls
layers = template.get("layers", [])
for layer_id, cb in dialog.svg_layer_checks.items():
cb.SetValue(layer_id in layers)
dialog.svg_bw.SetValue(template.get("bw", False))
dialog.svg_negative.SetValue(template.get("negative", False))
dialog.svg_mirror.SetValue(template.get("mirror", False))
dialog.svg_exclude_sheet.SetValue(template.get("exclude_sheet", False))
dialog.svg_merge_all.SetValue(template.get("merge_all", False))
dialog.svg_page_size.SetSelection(template.get("page_size", 2))
dialog.svg_drill_shape.SetSelection(template.get("drill_shape", 2))
dialog.log(f"Applied SVG template: {selection}")
def _show_svg_manage_menu(dialog, btn):
"""Show the Manage dropdown menu for SVG templates."""
from .svg_templates import DEFAULT_SVG_TEMPLATES, SVGTemplateManagerDialog, load_svg_templates
from .svg import PCB_LAYERS
menu = wx.Menu()
templates = load_svg_templates()
current = dialog.svg_template_choice.GetStringSelection()
is_custom = (current == "None (Custom)")
is_builtin = current in DEFAULT_SVG_TEMPLATES
# Add New
id_add = wx.NewId()
menu.Append(id_add, "Add New")
dialog.Bind(wx.EVT_MENU, lambda e: _add_new_svg_template(dialog), id=id_add)
# Edit (disabled if None)
id_edit = wx.NewId()
edit_label = f'Edit "{current}"' if not is_custom else "Edit"
item_edit = menu.Append(id_edit, edit_label)
item_edit.Enable(not is_custom)
dialog.Bind(wx.EVT_MENU, lambda e: _edit_svg_template(dialog, current), id=id_edit)
# Delete (disabled if builtin or None)
id_del = wx.NewId()
del_label = f'Delete "{current}"' if not is_custom else "Delete"
item_del = menu.Append(id_del, del_label)
item_del.Enable(not is_custom and not is_builtin)
dialog.Bind(wx.EVT_MENU, lambda e: _delete_svg_template(dialog, current), id=id_del)
menu.AppendSeparator()
# View All Templates
id_view = wx.NewId()
menu.Append(id_view, "View All Templates...")
dialog.Bind(wx.EVT_MENU, lambda e: _view_all_svg_templates(dialog), id=id_view)
btn.PopupMenu(menu, 0, btn.GetSize().height)
menu.Destroy()
def _add_new_svg_template(dialog):
"""Open SVG template editor to create a new template."""
from .svg_templates import SVGTemplateEditorDialog, save_svg_templates, load_svg_templates
from .svg import PCB_LAYERS
dlg = SVGTemplateEditorDialog(dialog, "", None, False, PCB_LAYERS)
if dlg.ShowModal() == wx.ID_OK and dlg.result:
templates = load_svg_templates()
templates[dlg.result["name"]] = dlg.result["data"]
save_svg_templates(templates)
_refresh_svg_template_dropdown(dialog)
idx = dialog.svg_template_choice.FindString(dlg.result["name"])
if idx != wx.NOT_FOUND:
dialog.svg_template_choice.SetSelection(idx)
_on_svg_template_selected(dialog)
dialog.log(f"Created SVG template: {dlg.result['name']}")
dlg.Destroy()
def _edit_svg_template(dialog, name):
"""Open SVG template editor to edit an existing template."""
from .svg_templates import SVGTemplateEditorDialog, save_svg_templates, load_svg_templates, DEFAULT_SVG_TEMPLATES
from .svg import PCB_LAYERS
import copy
templates = load_svg_templates()
if name not in templates:
return
data = copy.deepcopy(templates[name])
is_builtin = name in DEFAULT_SVG_TEMPLATES
dlg = SVGTemplateEditorDialog(dialog, name, data, is_builtin, PCB_LAYERS)
if dlg.ShowModal() == wx.ID_OK and dlg.result:
new_name = dlg.result["name"]
new_data = dlg.result["data"]
if new_name != name and not is_builtin:
del templates[name]
templates[new_name] = new_data
save_svg_templates(templates)
_refresh_svg_template_dropdown(dialog)
idx = dialog.svg_template_choice.FindString(new_name)
if idx != wx.NOT_FOUND:
dialog.svg_template_choice.SetSelection(idx)
_on_svg_template_selected(dialog)
dialog.log(f"Updated SVG template: {new_name}")
dlg.Destroy()
def _delete_svg_template(dialog, name):
"""Delete a user SVG template (not built-in)."""
from .svg_templates import save_svg_templates, load_svg_templates, DEFAULT_SVG_TEMPLATES
if name in DEFAULT_SVG_TEMPLATES:
wx.MessageBox(f'Cannot delete built-in template "{name}".', "Delete Template", wx.OK | wx.ICON_WARNING)
return
result = wx.MessageBox(
f'Delete template "{name}"?\n\nThis cannot be undone.',
"Confirm Delete",
wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION
)
if result == wx.YES:
templates = load_svg_templates()
if name in templates:
del templates[name]
save_svg_templates(templates)
_refresh_svg_template_dropdown(dialog)
dialog.log(f"Deleted SVG template: {name}")
def _view_all_svg_templates(dialog):
"""Open the SVG template manager dialog."""
from .svg_templates import SVGTemplateManagerDialog
from .svg import PCB_LAYERS
dlg = SVGTemplateManagerDialog(dialog, PCB_LAYERS)
dlg.ShowModal()
dlg.Destroy()
_refresh_svg_template_dropdown(dialog)
def _on_pinout_format_change(dialog):
"""Handle pinout output format change (PNG vs SVG)."""
is_svg = dialog.pinout_format.GetSelection() == 1
# Hide SVG layer box - no longer needed since we use 3D render
dialog.pinout_svg_box.Show(False)
# Update file extension
current_path = dialog.pinout_output.GetValue()
if is_svg:
new_path = current_path.rsplit('.', 1)[0] + '.svg'
else:
new_path = current_path.rsplit('.', 1)[0] + '.png'
dialog.pinout_output.SetValue(new_path)
# Refresh layout
dialog.pinout_svg_box.GetParent().Layout()
dialog.pinout_svg_box.GetParent().GetParent().FitInside()