-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdialog.py
More file actions
1037 lines (874 loc) · 44.2 KB
/
dialog.py
File metadata and controls
1037 lines (874 loc) · 44.2 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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
KiRender - RenderDialog Module
Main dialog window for the plugin.
"""
import os
import sys
import subprocess
import webbrowser
import threading
import wx
import pcbnew
from .config import load_config, save_config, CONFIG_FILE
# Pre-import tabs module to front-load import cost (not the heavy render threads)
from . import tabs as _tabs_module
# Lazy imports - heavy modules loaded on demand
# from .SpinRender import RenderThread
# from .Images import StaticRenderThread
# from .svg import SVGExportThread
__version__ = "1.3.0"
# URLs for Help menu
HELP_URL = "https://pcbtools.xyz/tools/kirender"
GET_INVOLVED_URL = "https://github.com/way2pramil/KiRender"
DONATE_URL = "https://pcbtools.xyz/tools/kirender#sponsor"
REPORT_BUG_URL = "https://github.com/way2pramil/KiRender/issues"
class RenderDialog(wx.Frame):
"""Main dialog for KiRender plugin."""
def __init__(self, parent, schema_lib=None):
import time
self._init_start = time.time()
# Store the pcbschema library reference (may be None if not available)
self.pcbschema = schema_lib
if self.pcbschema:
print(f"[KiRender] Linked to pcbschema version: {getattr(self.pcbschema, '__version__', 'Unknown')}")
self.config = load_config()
super().__init__(parent, title="KiRender - 3D PCB Renderer",
size=(self.config['window_width'], self.config['window_height']),
style=wx.DEFAULT_FRAME_STYLE)
self.board = pcbnew.GetBoard()
self.pcb_path = self.board.GetFileName()
self.project_dir = os.path.dirname(self.pcb_path)
self.project_name = os.path.splitext(os.path.basename(self.pcb_path))[0]
self.render_thread = None
self.kicad_cli = self._find_kicad_cli()
self.ffmpeg_path = self._find_ffmpeg()
# Setup KiRender output folder structure
self.kirender_dir = os.path.join(self.project_dir, "KiRender")
self.output_dirs = {
'SpinRender': os.path.join(self.kirender_dir, "SpinRender"),
'Static': os.path.join(self.kirender_dir, "Static"),
'Pinout': os.path.join(self.kirender_dir, "Pinout"),
'SVG': os.path.join(self.kirender_dir, "SVG"),
'3D': os.path.join(self.kirender_dir, "3D"),
'POS': os.path.join(self.kirender_dir, "POS"),
}
# Create all output directories
for dir_path in self.output_dirs.values():
os.makedirs(dir_path, exist_ok=True)
# Template settings (will be set when user applies a template)
self.anim_template = None
self.static_template = None
self.svg_template = None
# Start board dimension parsing in background (runs during wx event loop delay)
self._board_dimensions = (None, None)
self._board_dimensions_loaded = False
self._board_dimensions_thread = threading.Thread(target=self._parse_board_dimensions_background, daemon=True)
self._board_dimensions_thread.start()
self._create_ui()
self.Centre()
self.Bind(wx.EVT_CLOSE, self.on_close)
self.Bind(wx.EVT_SIZE, self.on_resize)
def _find_kicad_cli(self):
"""Locate kicad-cli executable."""
cli_name = "kicad-cli.exe" if sys.platform == "win32" else "kicad-cli"
kicad_bin = os.path.dirname(sys.executable)
for path in [
os.path.join(kicad_bin, cli_name),
os.path.join(os.path.dirname(kicad_bin), "bin", cli_name),
r"C:\Program Files\KiCad\9.0\bin\kicad-cli.exe",
]:
if os.path.exists(path):
return path
return cli_name
def _find_ffmpeg(self):
"""Locate ffmpeg executable."""
if sys.platform == "win32":
for path in [r"C:\ffmpeg\bin\ffmpeg.exe", r"C:\Program Files\ffmpeg\bin\ffmpeg.exe"]:
if os.path.exists(path):
return path
return "ffmpeg"
def _show_help_menu(self, event):
"""Show Help dropdown menu."""
menu = wx.Menu()
items = [
("Help", lambda e: webbrowser.open(HELP_URL)),
None,
("Get Involved", lambda e: webbrowser.open(GET_INVOLVED_URL)),
("Donate", lambda e: webbrowser.open(DONATE_URL)),
("Report Bug", lambda e: webbrowser.open(REPORT_BUG_URL)),
None,
("Debug Info", lambda e: self._show_debug_dialog()),
None,
("About KiRender", lambda e: self._show_about_dialog()),
]
for item in items:
if item is None:
menu.AppendSeparator()
else:
menu_item = menu.Append(wx.ID_ANY, item[0])
self.Bind(wx.EVT_MENU, item[1], menu_item)
btn = event.GetEventObject()
btn.PopupMenu(menu)
menu.Destroy()
def _show_help_popup(self, event):
"""Show help popup menu."""
menu = wx.Menu()
items = [
("Online Help", lambda e: webbrowser.open(HELP_URL)),
None,
("Get Involved", lambda e: webbrowser.open(GET_INVOLVED_URL)),
("Donate", lambda e: webbrowser.open(DONATE_URL)),
("Report Bug", lambda e: webbrowser.open(REPORT_BUG_URL)),
None,
("Debug Info", lambda e: self._show_debug_dialog()),
None,
("About KiRender", lambda e: self._show_about_dialog()),
]
for item in items:
if item is None:
menu.AppendSeparator()
else:
menu_item = menu.Append(wx.ID_ANY, item[0])
self.Bind(wx.EVT_MENU, item[1], menu_item)
btn = event.GetEventObject()
btn.PopupMenu(menu)
menu.Destroy()
def _create_ui(self):
"""Create main UI."""
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
# Main splitter - notebook on top, log panel on bottom
self.splitter = wx.SplitterWindow(panel, style=wx.SP_LIVE_UPDATE | wx.SP_3DSASH)
self.splitter.SetMinimumPaneSize(60) # Minimum height for log panel
# Top panel - notebook
self._top_panel = wx.Panel(self.splitter)
top_panel = self._top_panel # Local alias for convenience
top_sizer = wx.BoxSizer(wx.VERTICAL)
# Create notebook with placeholder tabs
self.notebook = wx.Notebook(top_panel)
self._tab_names = ["SpinRender", "Static Images", "Pinout/Docs", "SVG Export", "3D Export", "BOM/Position", "Settings"]
self._tab_loaded = {name: False for name in self._tab_names}
# Add placeholder panels for all tabs
for name in self._tab_names:
placeholder = wx.Panel(self.notebook)
# Add "Loading..." text to placeholder
ph_sizer = wx.BoxSizer(wx.VERTICAL)
ph_sizer.AddStretchSpacer()
loading_text = wx.StaticText(placeholder, label="Loading...")
ph_sizer.Add(loading_text, 0, wx.ALIGN_CENTER)
ph_sizer.AddStretchSpacer()
placeholder.SetSizer(ph_sizer)
self.notebook.AddPage(placeholder, name)
# Bind tab change for lazy loading
self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self._on_tab_changed)
top_sizer.Add(self.notebook, 1, wx.EXPAND | wx.ALL, 5)
# Status
self.progress_label = wx.StaticText(top_panel, label="Status: Idle")
self.progress = wx.Gauge(top_panel, range=100)
top_sizer.Add(self.progress_label, 0, wx.LEFT | wx.RIGHT, 10)
top_sizer.Add(self.progress, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 10)
top_panel.SetSizer(top_sizer)
# Bottom panel - log
self._bottom_panel = wx.Panel(self.splitter)
bottom_panel = self._bottom_panel # Local alias for convenience
bottom_sizer = wx.BoxSizer(wx.VERTICAL)
# Log panel state tracking
self._log_expanded = True
self._saved_sash_pos = None
# Separator line at top of log panel for clear visual division
separator = wx.StaticLine(bottom_panel, style=wx.LI_HORIZONTAL)
bottom_sizer.Add(separator, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 5)
# Log header with Show CLI button
log_header = wx.BoxSizer(wx.HORIZONTAL)
log_header.Add(wx.StaticText(bottom_panel, label="Output Log:"), 0, wx.ALIGN_CENTER_VERTICAL)
log_header.AddStretchSpacer()
self.log_timestamp_cb = wx.CheckBox(bottom_panel, label="Timestamps")
self.log_timestamp_cb.SetValue(True) # Enable by default for debugging
self.log_timestamp_cb.SetToolTip("Show timestamps in log messages")
log_header.Add(self.log_timestamp_cb, 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, 10)
clear_btn = wx.Button(bottom_panel, label="Clear")
clear_btn.SetToolTip("Clear the log")
clear_btn.Bind(wx.EVT_BUTTON, lambda e: self.log_text.Clear())
log_header.Add(clear_btn, 0, wx.RIGHT, 5)
show_cli_btn = wx.Button(bottom_panel, label="Show CLI")
show_cli_btn.SetToolTip("Preview the CLI command that will be executed")
show_cli_btn.Bind(wx.EVT_BUTTON, self._on_show_cli)
log_header.Add(show_cli_btn, 0, wx.RIGHT, 5)
# Toggle log button (in log header)
self._toggle_log_btn = wx.Button(bottom_panel, label="Hide Log")
self._toggle_log_btn.SetToolTip("Hide the output log panel")
self._toggle_log_btn.Bind(wx.EVT_BUTTON, self._on_toggle_log)
log_header.Add(self._toggle_log_btn, 0, wx.RIGHT, 5)
bottom_sizer.Add(log_header, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 5)
self.log_text = wx.TextCtrl(bottom_panel, style=wx.TE_MULTILINE | wx.TE_READONLY)
self.log_text.SetFont(wx.Font(9, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
bottom_sizer.Add(self.log_text, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 5)
bottom_panel.SetSizer(bottom_sizer)
# Split horizontally (top/bottom)
self.splitter.SplitHorizontally(top_panel, bottom_panel)
self.splitter.SetSashGravity(0.85) # 85% to top, 15% to bottom by default
# Restore saved log splitter position
saved_log_pos = self.config.get('log_splitter_pos', -150)
if saved_log_pos < 0:
# Negative value = position from bottom
wx.CallAfter(lambda: self.splitter.SetSashPosition(self.GetSize().height + saved_log_pos))
else:
wx.CallAfter(lambda: self.splitter.SetSashPosition(saved_log_pos))
sizer.Add(self.splitter, 1, wx.EXPAND)
# Buttons: Help | Show Log (when hidden) | Close
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
help_btn = wx.Button(panel, label="Help")
help_btn.Bind(wx.EVT_BUTTON, self._show_help_popup)
btn_sizer.Add(help_btn, 0, wx.ALL, 5)
btn_sizer.AddStretchSpacer()
# Show Log button (visible only when log is hidden)
self._show_log_btn = wx.Button(panel, label="Show Log")
self._show_log_btn.SetToolTip("Show the output log panel")
self._show_log_btn.Bind(wx.EVT_BUTTON, self._on_toggle_log)
self._show_log_btn.Hide() # Hidden by default (log is visible)
btn_sizer.Add(self._show_log_btn, 0, wx.ALL, 5)
close_btn = wx.Button(panel, label="Close")
close_btn.Bind(wx.EVT_BUTTON, lambda e: self.Close())
btn_sizer.Add(close_btn, 0, wx.ALL, 5)
sizer.Add(btn_sizer, 0, wx.EXPAND)
panel.SetSizer(sizer)
import time
ui_time = (time.time() - self._init_start) * 1000
self.log(f"[INIT] UI created in {ui_time:.0f}ms")
self.log(f"PCB: {self.pcb_path}")
self.log(f"kicad-cli: {self.kicad_cli}")
# Load first tab after UI is shown - use CallLater(1) for faster callback than CallAfter
self._deferred_scheduled = time.time()
wx.CallLater(1, self._deferred_init)
def _deferred_init(self):
"""Load first tab after window is shown. Board dimensions loaded lazily."""
import time
start = time.time()
# Log how long wx took to call us back
if hasattr(self, '_deferred_scheduled'):
callback_delay = (start - self._deferred_scheduled) * 1000
self.log(f"[INIT] Callback fired after {callback_delay:.0f}ms")
# Load only the first tab immediately (board dimensions parsed inside tab if needed)
self._load_tab(0)
t1 = time.time()
self.log(f"[INIT] First tab loaded in {(t1-start)*1000:.0f}ms")
# Preload remaining tabs in background (non-blocking, one per event loop cycle)
self._preload_index = 1
wx.CallLater(50, self._preload_next_tab)
def _preload_next_tab(self):
"""Preload tabs one at a time to avoid blocking UI."""
if self._preload_index >= len(self._tab_names):
self.log(f"[INIT] All tabs preloaded")
return
tab_name = self._tab_names[self._preload_index]
if not self._tab_loaded[tab_name]:
self._load_tab(self._preload_index, background=True)
self._preload_index += 1
# Schedule next tab with longer delay to reduce jitter
wx.CallLater(100, self._preload_next_tab)
def _parse_board_dimensions_background(self):
"""Parse board dimensions in background thread."""
import time
t1 = time.time()
from .board_utils import get_board_dimensions
self._board_dimensions = get_board_dimensions(self.pcb_path)
self._board_dimensions_loaded = True
self._board_parse_time = (time.time() - t1) * 1000
def _get_board_dimensions(self):
"""Get board dimensions, waiting for background thread if needed."""
# Track if we need to log (first access)
first_access = not getattr(self, '_board_dimensions_logged', False)
if not self._board_dimensions_loaded:
# Wait for background thread to finish
if hasattr(self, '_board_dimensions_thread'):
self._board_dimensions_thread.join(timeout=2.0)
# Log timing and dimensions on first access
if first_access:
self._board_dimensions_logged = True
if hasattr(self, '_board_parse_time'):
self.log(f"[INIT] Board dimensions parsed in {self._board_parse_time:.0f}ms (background)")
width, height = self._board_dimensions
if width and height:
self.log(f"Board size: {width} x {height} mm (aspect ratio: {width/height:.2f}:1)")
else:
self.log("Board size: Unable to detect (no Edge.Cuts found)")
return self._board_dimensions
def _on_tab_changed(self, event):
"""Handle tab change - load tab content if not yet loaded."""
tab_idx = event.GetSelection()
if not self._tab_loaded[self._tab_names[tab_idx]]:
wx.CallAfter(self._load_tab, tab_idx)
event.Skip()
def _load_tab(self, tab_idx, background=False):
"""Load a specific tab's content."""
import time
tab_name = self._tab_names[tab_idx]
if self._tab_loaded[tab_name]:
return
t1 = time.time()
# Remember current selection to restore after
current_selection = self.notebook.GetSelection()
# Freeze entire frame for background loads to prevent any flickering
if background:
self.Freeze()
else:
self.notebook.Freeze()
try:
# Get the placeholder panel
old_panel = self.notebook.GetPage(tab_idx)
# Use pre-imported tabs module
from .tabs import (create_spinrender_tab, create_static_tab, create_svg_tab,
create_settings_tab, create_pinout_tab, create_export3d_tab, create_bom_tab)
tab_creators = {
"SpinRender": create_spinrender_tab,
"Static Images": create_static_tab,
"Pinout/Docs": create_pinout_tab,
"SVG Export": create_svg_tab,
"3D Export": create_export3d_tab,
"BOM/Position": create_bom_tab,
"Settings": create_settings_tab,
}
creator = tab_creators.get(tab_name)
if creator:
# Create the real tab
new_panel = creator(self.notebook, self)
# Replace placeholder with real content (never auto-select)
self.notebook.RemovePage(tab_idx)
old_panel.Destroy()
self.notebook.InsertPage(tab_idx, new_panel, tab_name, select=False)
# Restore the original selection
if self.notebook.GetSelection() != current_selection:
self.notebook.SetSelection(current_selection)
self._tab_loaded[tab_name] = True
t2 = time.time()
if not background:
self.log(f"[TAB] '{tab_name}' loaded in {(t2-t1)*1000:.0f}ms")
finally:
if background:
self.Thaw()
else:
self.notebook.Thaw()
def log(self, msg, color=None):
"""Log a message to the output log.
Args:
msg: Message to log
color: Optional wx.Colour or tuple (r,g,b) for text color
"""
import time
# Build message with optional timestamp
if hasattr(self, 'log_timestamp_cb') and self.log_timestamp_cb.GetValue():
timestamp = time.strftime("%H:%M:%S", time.localtime())
ms = int((time.time() % 1) * 1000)
text = f"[{timestamp}.{ms:03d}] {msg}\n"
else:
text = f"{msg}\n"
# Apply color if specified
if color:
# Save current position
start_pos = self.log_text.GetLastPosition()
self.log_text.AppendText(text)
end_pos = self.log_text.GetLastPosition()
# Apply color to the new text
if isinstance(color, tuple):
color = wx.Colour(*color)
self.log_text.SetStyle(start_pos, end_pos, wx.TextAttr(color))
else:
self.log_text.AppendText(text)
def log_error(self, msg):
"""Log an error message in red."""
self.log(msg, color=(200, 0, 0))
def log_warning(self, msg):
"""Log a warning message in orange."""
self.log(msg, color=(200, 120, 0))
def log_success(self, msg):
"""Log a success message in green."""
self.log(msg, color=(0, 140, 0))
def _on_show_cli(self, event):
"""Show the CLI command for the currently active tab."""
from .tabs import log_cli_command
# Determine which tab is active
current_tab = self.notebook.GetSelection()
tab_types = {0: "spinrender", 1: "static", 2: "pinout"}
template_type = tab_types.get(current_tab, "static")
# Get output path based on tab
if template_type == "spinrender":
output_path = self.anim_output.GetValue() if hasattr(self, 'anim_output') else "output.mp4"
elif template_type == "static":
output_dir = self.static_output_dir.GetValue() if hasattr(self, 'static_output_dir') else ""
prefix = self.static_prefix.GetValue() if hasattr(self, 'static_prefix') else "render"
output_path = f"{output_dir}/{prefix}_<side>.png"
else: # pinout
output_path = self.pinout_output.GetValue() if hasattr(self, 'pinout_output') else "pinout.png"
self.log("-" * 40)
self.log(f"CLI Preview ({template_type}):")
log_cli_command(self, template_type, self.pcb_path, output_path)
def _on_toggle_log(self, event):
"""Toggle the log panel visibility."""
if self._log_expanded:
# Save current position and collapse
self._saved_sash_pos = self.splitter.GetSashPosition()
self.splitter.Unsplit(self._bottom_panel)
self._show_log_btn.Show() # Show "Show Log" button in bottom bar
self._log_expanded = False
# Relayout the parent to show the button
self._show_log_btn.GetParent().Layout()
else:
# Restore log panel
self.splitter.SplitHorizontally(self._top_panel, self._bottom_panel)
if self._saved_sash_pos:
self.splitter.SetSashPosition(self._saved_sash_pos)
else:
# Default: 75% to top
self.splitter.SetSashPosition(int(self.GetSize().height * 0.75))
self._show_log_btn.Hide() # Hide "Show Log" button
self._log_expanded = True
self._show_log_btn.GetParent().Layout()
def update_progress(self, value, label):
self.progress.SetValue(value)
self.progress_label.SetLabel(f"Status: {label}")
def on_resize(self, event):
size = self.GetSize()
self.config['window_width'] = size.GetWidth()
self.config['window_height'] = size.GetHeight()
event.Skip()
def on_close(self, event):
# Clear singleton reference
try:
from . import _dialog_instance
import sys
# Get the parent package module and clear reference
parent_module = sys.modules.get(__package__)
if parent_module:
parent_module._dialog_instance = None
except:
pass
# If KiCad is closing (CanVeto=False), close immediately without prompts
if not event.CanVeto():
if self.render_thread and self.render_thread.is_alive():
self.render_thread.cancel()
self._save_config()
self.Destroy()
return
if self.render_thread and self.render_thread.is_alive():
if wx.MessageBox("Render in progress. Cancel?", "Confirm", wx.YES_NO) == wx.YES:
self.render_thread.cancel()
self._save_config()
self.Destroy()
else:
event.Veto()
else:
self._save_config()
self.Destroy()
def _save_config(self):
# Save window size
w, h = self.GetSize()
self.config['window_width'] = w
self.config['window_height'] = h
# Save main log splitter position
if hasattr(self, 'splitter') and self.splitter.IsSplit():
self.config['log_splitter_pos'] = self.splitter.GetSashPosition()
# Save JSON preview splitter positions
if hasattr(self, 'anim_json_splitter') and self.anim_json_splitter.IsSplit():
self.config['anim_json_splitter_pos'] = self.anim_json_splitter.GetSashPosition()
if hasattr(self, 'static_json_splitter') and self.static_json_splitter.IsSplit():
self.config['static_json_splitter_pos'] = self.static_json_splitter.GetSashPosition()
if hasattr(self, 'pinout_json_splitter') and self.pinout_json_splitter.IsSplit():
self.config['pinout_json_splitter_pos'] = self.pinout_json_splitter.GetSashPosition()
# Only save attributes that exist (lazy loading means some tabs may not be loaded)
if hasattr(self, 'anim_width'):
self.config['anim_width'] = self.anim_width.GetValue()
if hasattr(self, 'anim_height'):
self.config['anim_height'] = self.anim_height.GetValue()
if hasattr(self, 'anim_zoom'):
self.config['anim_zoom'] = self.anim_zoom.GetValue()
if hasattr(self, 'anim_frames'):
self.config['anim_frames'] = self.anim_frames.GetValue()
if hasattr(self, 'anim_fps'):
self.config['anim_fps'] = self.anim_fps.GetValue()
if hasattr(self, 'anim_component_height'):
self.config['anim_component_height'] = self.anim_component_height.GetValue()
if hasattr(self, 'anim_safety_margin'):
self.config['anim_safety_margin'] = self.anim_safety_margin.GetValue()
if hasattr(self, 'anim_workers'):
self.config['parallel_workers'] = self._get_parallel_workers()
if hasattr(self, 'static_width'):
self.config['static_width'] = self.static_width.GetValue()
if hasattr(self, 'static_height'):
self.config['static_height'] = self.static_height.GetValue()
save_config(self.config)
def _get_parallel_workers(self):
"""Get number of parallel workers from UI selection."""
if not hasattr(self, 'anim_workers'):
return 0 # Auto
selection = self.anim_workers.GetSelection()
if selection == 0:
return 0 # Auto
return selection # 1, 2, 3, etc.
# Browse handlers
def on_browse_anim(self, event):
fmt = self.anim_format.GetStringSelection()
wildcards = {"mp4": "MP4|*.mp4", "gif": "GIF|*.gif", "webm": "WebM|*.webm", "png sequence": "PNG|*.png"}
dlg = wx.FileDialog(self, "Save As", self.project_dir, f"{self.project_name}_spin.{fmt.split()[0]}",
wildcards.get(fmt, "MP4|*.mp4"), wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
self.anim_output.SetValue(dlg.GetPath())
dlg.Destroy()
def on_browse_static(self, event):
dlg = wx.DirDialog(self, "Select Output Directory", self.project_dir)
if dlg.ShowModal() == wx.ID_OK:
self.static_output_dir.SetValue(dlg.GetPath())
dlg.Destroy()
def on_browse_svg(self, event):
dlg = wx.DirDialog(self, "Select Output Directory", self.project_dir)
if dlg.ShowModal() == wx.ID_OK:
self.svg_output_dir.SetValue(dlg.GetPath())
dlg.Destroy()
def on_browse_cli(self, event):
wildcard = "Executable|*.exe|All|*.*" if sys.platform == "win32" else "All|*"
dlg = wx.FileDialog(self, "Select kicad-cli", "", "", wildcard, wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.cli_path.SetValue(dlg.GetPath())
self.kicad_cli = dlg.GetPath()
dlg.Destroy()
def on_browse_ffmpeg(self, event):
wildcard = "Executable|*.exe|All|*.*" if sys.platform == "win32" else "All|*"
dlg = wx.FileDialog(self, "Select ffmpeg", "", "", wildcard, wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.ff_path.SetValue(dlg.GetPath())
self.ffmpeg_path = dlg.GetPath()
dlg.Destroy()
# SVG helpers
def on_svg_select_all(self, event):
for cb in self.svg_layer_checks.values():
cb.SetValue(True)
def on_svg_select_none(self, event):
for cb in self.svg_layer_checks.values():
cb.SetValue(False)
# Render handlers
def on_render_animation(self, event):
if self.render_thread and self.render_thread.is_alive():
wx.MessageBox("Render in progress.", "Warning", wx.OK | wx.ICON_WARNING)
return
# Get current template
template = getattr(self, '_spinrender_current_template', None)
if not template:
wx.MessageBox("Please select a template first.", "Warning", wx.OK | wx.ICON_WARNING)
return
cli_params = template.get("cli_params", {})
# Get board dimensions for safe zoom calculation
board_w, board_h = self._get_board_dimensions() if hasattr(self, '_get_board_dimensions') else (150.0, 100.0)
# Get safe zoom parameters from template
component_height = cli_params.get('component_height', 10)
safety_margin = cli_params.get('safety_margin', 5)
params = {
'pcb_path': self.pcb_path, 'kicad_cli': self.cli_path.GetValue(),
'ffmpeg_path': self.ff_path.GetValue(),
'width': cli_params.get('width', 1920),
'height': cli_params.get('height', 1080),
'zoom': cli_params.get('zoom', 0.7),
'background': cli_params.get('background', 'opaque'),
'frames': self.anim_frames.GetValue(),
'fps': self.anim_fps.GetValue(), 'revolutions': self.anim_revs.GetValue(),
'axis': self.axis_rb.GetSelection(), 'tilt_x': self.tilt_x.GetValue(),
'tilt_y': self.tilt_y.GetValue(), 'tilt_z': self.tilt_z.GetValue(),
'output_format': self.anim_format.GetStringSelection().replace(" sequence", ""),
'output_file': self.anim_output.GetValue(),
'quality': cli_params.get('quality', 'high'),
'perspective': 'perspective' if cli_params.get('perspective', False) else 'orthographic',
'ffmpeg_preset': self.ffmpeg_preset.GetStringSelection(),
'crf': self.crf_slider.GetValue(), 'side': 'default',
'board_width': board_w, 'board_height': board_h, # For rotation-zoom clipping prevention
'component_height': component_height, 'safety_margin': safety_margin, # Safe zoom params
'parallel_workers': self._get_parallel_workers() # Parallel rendering
}
self.log("=" * 40)
self.log(f"Starting animation render: {params['output_file']}")
# Log CLI command
from .tabs import log_cli_command
log_cli_command(self, "spinrender", self.pcb_path, params['output_file'])
self.anim_cancel_btn.Enable(True)
from .SpinRender import RenderThread
self.render_thread = RenderThread(self, params)
self.render_thread.start()
def on_render_static(self, event):
if self.render_thread and self.render_thread.is_alive():
wx.MessageBox("Render in progress.", "Warning", wx.OK | wx.ICON_WARNING)
return
# Get current template
template = getattr(self, '_static_current_template', None)
if not template:
wx.MessageBox("Please select a template first.", "Warning", wx.OK | wx.ICON_WARNING)
return
cli_params = template.get("cli_params", {})
views, output_files = [], []
output_dir = self.static_output_dir.GetValue()
prefix = self.static_prefix.GetValue()
for view, cb in [("top", self.view_top), ("bottom", self.view_bottom),
("front", self.view_front), ("back", self.view_back),
("left", self.view_left), ("right", self.view_right)]:
if cb.GetValue():
views.append(view)
output_files.append(os.path.join(output_dir, f"{prefix}_{view}.png"))
if not views:
wx.MessageBox("Select at least one view.", "Warning", wx.OK | wx.ICON_WARNING)
return
params = {
'pcb_path': self.pcb_path, 'kicad_cli': self.cli_path.GetValue(),
'width': cli_params.get('width', 2000),
'height': cli_params.get('height', 2000),
'zoom': cli_params.get('zoom', 1.0),
'background': cli_params.get('background', 'transparent'),
'views': views, 'output_files': output_files,
'quality': cli_params.get('quality', 'high'),
'perspective': 'perspective' if cli_params.get('perspective', False) else 'orthographic'
}
self.log("=" * 40)
self.log(f"Starting static render: {', '.join(views)}")
# Log CLI command
from .tabs import log_cli_command
log_cli_command(self, "static", self.pcb_path, output_files[0] if output_files else "output.png")
self.static_cancel_btn.Enable(True)
from .Images import StaticRenderThread
self.render_thread = StaticRenderThread(self, params)
self.render_thread.start()
def on_export_svg(self, event):
if self.render_thread and self.render_thread.is_alive():
wx.MessageBox("Render in progress.", "Warning", wx.OK | wx.ICON_WARNING)
return
layers, output_files = [], []
output_dir = self.svg_output_dir.GetValue()
merge_all = self.svg_merge_all.GetValue()
for layer_id, cb in self.svg_layer_checks.items():
if cb.GetValue():
layers.append(layer_id)
if not merge_all:
output_files.append(os.path.join(output_dir, f"{self.project_name}_{layer_id.replace('.', '_')}.svg"))
if not layers:
wx.MessageBox("Select at least one layer.", "Warning", wx.OK | wx.ICON_WARNING)
return
# If merge_all, create single output file
if merge_all:
output_files = [os.path.join(output_dir, f"{self.project_name}_merged.svg")]
params = {
'pcb_path': self.pcb_path, 'kicad_cli': self.cli_path.GetValue(),
'layers': layers, 'output_files': output_files, 'output_dir': output_dir,
'black_and_white': self.svg_bw.GetValue(), 'negative': self.svg_negative.GetValue(),
'mirror': self.svg_mirror.GetValue(), 'exclude_drawing_sheet': self.svg_exclude_sheet.GetValue(),
'page_size': self.svg_page_size.GetSelection(), 'drill_shape_opt': self.svg_drill_shape.GetSelection(),
'merge_all': merge_all,
}
self.log("=" * 40)
if merge_all:
self.log(f"Starting SVG export (merged): {', '.join(layers)}")
else:
self.log(f"Starting SVG export: {', '.join(layers)}")
self.svg_cancel_btn.Enable(True)
self.render_thread = SVGExportThread(self, params)
self.render_thread.start()
def on_cancel(self, event):
if self.render_thread and hasattr(self.render_thread, 'cancel'):
self.render_thread.cancel()
self.log("Cancelling...")
def on_render_complete(self, output_path):
self._disable_all_cancel_btns()
self.update_progress(100, "Complete!")
self.log(f"Done: {output_path}")
if wx.MessageBox(f"Complete!\n\n{output_path}\n\nOpen folder?", "Success", wx.YES_NO | wx.ICON_INFORMATION) == wx.YES:
folder = os.path.dirname(output_path) if os.path.isfile(output_path) else output_path
if sys.platform == "win32":
os.startfile(folder)
elif sys.platform == "darwin":
subprocess.run(["open", folder])
else:
subprocess.run(["xdg-open", folder])
def on_render_error(self, error_msg):
self._disable_all_cancel_btns()
self.update_progress(0, "Error")
self.log(f"Error: {error_msg}")
wx.MessageBox(f"Failed:\n\n{error_msg}", "Error", wx.OK | wx.ICON_ERROR)
def _disable_all_cancel_btns(self):
"""Disable all cancel buttons."""
for btn in [self.anim_cancel_btn, self.static_cancel_btn, self.svg_cancel_btn,
self.pinout_cancel_btn, self.export3d_cancel_btn, self.bom_cancel_btn]:
if btn:
btn.Enable(False)
# ==================== PINOUT HANDLERS ====================
def on_browse_pinout(self, event):
is_svg = self.pinout_format.GetSelection() == 1
if is_svg:
ext = "svg"
wildcard = "SVG files (*.svg)|*.svg"
else:
ext = "png"
wildcard = "PNG files (*.png)|*.png|JPEG files (*.jpg)|*.jpg"
with wx.FileDialog(self, "Save Pinout Image", self.project_dir, f"{self.project_name}_pinout.{ext}",
wildcard, wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg:
if dlg.ShowModal() == wx.ID_OK:
self.pinout_output.SetValue(dlg.GetPath())
def on_render_pinout(self, event):
from .pinout import PinoutRenderThread
if self.render_thread and self.render_thread.is_alive():
wx.MessageBox("Render in progress.", "Warning", wx.OK | wx.ICON_WARNING)
return
# Determine output format (PNG or SVG)
format_selection = self.pinout_format.GetSelection()
is_svg = format_selection == 1
self.log(f"Format selection index: {format_selection}, is_svg: {is_svg}")
# Get current template (required now)
current_template = getattr(self, '_pinout_current_template', None)
if not current_template:
wx.MessageBox("Please select a template first.", "Warning", wx.OK | wx.ICON_WARNING)
return
# Use template's cli_params
cli_params = current_template.get('cli_params', {})
self.log(f"Using template: {current_template.get('name', 'Unknown')}")
params = {
'pcb_path': self.pcb_path,
'kicad_cli': self.cli_path.GetValue(),
'side': self.pinout_side.GetStringSelection(), # From UI (render-time setting)
'width': cli_params.get('width', 2400),
'height': cli_params.get('height', 1600),
'background': cli_params.get('background', 'transparent'),
'quality': cli_params.get('quality', 'high'),
'perspective': cli_params.get('perspective', False),
'output_file': self.pinout_output.GetValue(),
'output_format': 'svg' if is_svg else 'png',
# Camera settings from template
'zoom': cli_params.get('zoom', 1.0),
'pan': cli_params.get('pan', ''),
'pivot': cli_params.get('pivot', ''),
'rotate': cli_params.get('rotate', ''),
# Labels still come from UI (render-time settings)
'show_labels': self.pinout_show_labels.GetValue(),
'show_refs': self.pinout_show_refs.GetValue(),
'show_values': self.pinout_show_values.GetValue(),
'label_size': self.pinout_label_size.GetValue(),
'filter_pattern': self.pinout_filter.GetValue(),
'highlight_pattern': self.pinout_highlight.GetValue(),
}
# Add SVG-specific layers if SVG format selected
if is_svg:
selected_layers = []
for layer_id, cb in self.pinout_svg_layers.items():
if cb.GetValue():
selected_layers.append(layer_id)
params['svg_layers'] = selected_layers
self.log(f"SVG layers selected: {selected_layers}")
self.log("=" * 40)
format_str = "SVG" if is_svg else "PNG"
self.log(f"Generating pinout diagram ({params['side']} side, {format_str})...")
self.log(f"Output format param: {params['output_format']}")
# Log CLI command
from .tabs import log_cli_command
log_cli_command(self, "pinout", self.pcb_path, params['output_file'])
self.pinout_cancel_btn.Enable(True)
self.render_thread = PinoutRenderThread(self, params)
self.render_thread.start()
# ==================== 3D EXPORT HANDLERS ====================
def on_browse_export3d(self, event):
fmt = self.export3d_format.GetStringSelection()
wildcard = f"{fmt.upper()} files (*.{fmt})|*.{fmt}"
with wx.FileDialog(self, f"Save {fmt.upper()} File", self.project_dir,
f"{self.project_name}.{fmt}", wildcard,
wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg:
if dlg.ShowModal() == wx.ID_OK:
self.export3d_output.SetValue(dlg.GetPath())
def on_export_3d(self, event):
from .pinout import Assembly3DExportThread
if self.render_thread and self.render_thread.is_alive():
wx.MessageBox("Export in progress.", "Warning", wx.OK | wx.ICON_WARNING)
return
params = {
'pcb_path': self.pcb_path,
'kicad_cli': self.cli_path.GetValue(),
'format': self.export3d_format.GetStringSelection(),
'output_file': self.export3d_output.GetValue(),
'board_only': self.export3d_board_only.GetValue(),
'no_components': self.export3d_no_components.GetValue(),
'no_dnp': self.export3d_no_dnp.GetValue(),
'component_filter': self.export3d_filter.GetValue(),
'include_tracks': self.export3d_tracks.GetValue(),
'include_pads': self.export3d_pads.GetValue(),
'include_zones': self.export3d_zones.GetValue(),
'include_silkscreen': self.export3d_silkscreen.GetValue(),
'include_soldermask': self.export3d_soldermask.GetValue(),
}
self.log("=" * 40)
self.log(f"Exporting {params['format'].upper()}...")
self.export3d_cancel_btn.Enable(True)
self.render_thread = Assembly3DExportThread(self, params)
self.render_thread.start()
# ==================== BOM/POSITION HANDLERS ====================
def on_browse_bom(self, event):
fmt = self.bom_format.GetStringSelection()
ext = "csv" if fmt == "csv" else "txt" if fmt == "ascii" else "gbr"
wildcard = f"{fmt.upper()} files (*.{ext})|*.{ext}|All files (*.*)|*.*"
with wx.FileDialog(self, "Save Position File", self.project_dir,
f"{self.project_name}_pos.{ext}", wildcard,
wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as dlg:
if dlg.ShowModal() == wx.ID_OK:
self.bom_output.SetValue(dlg.GetPath())
def on_export_bom(self, event):
from .pinout import BOMExportThread
if self.render_thread and self.render_thread.is_alive():
wx.MessageBox("Export in progress.", "Warning", wx.OK | wx.ICON_WARNING)
return
params = {
'pcb_path': self.pcb_path,
'kicad_cli': self.cli_path.GetValue(),
'format': self.bom_format.GetStringSelection(),
'units': self.bom_units.GetStringSelection(),
'side': self.bom_side.GetStringSelection(),
'output_file': self.bom_output.GetValue(),
'exclude_dnp': self.bom_exclude_dnp.GetValue(),
'smd_only': self.bom_smd_only.GetValue(),
}
self.log("=" * 40)
self.log(f"Exporting position file ({params['format']})...")
self.bom_cancel_btn.Enable(True)
self.render_thread = BOMExportThread(self, params)
self.render_thread.start()
def _show_debug_dialog(self):
from .help import get_debug_info, copy_to_clipboard
debug_info = get_debug_info(__version__, self.kicad_cli, self.ffmpeg_path,
self.pcb_path, self.project_dir, CONFIG_FILE)
dlg = wx.Dialog(self, title="Debug Info", size=(500, 350), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(wx.StaticText(dlg, label="Copy this when reporting issues:"), 0, wx.ALL, 10)
text = wx.TextCtrl(dlg, value=debug_info, style=wx.TE_MULTILINE | wx.TE_READONLY)
text.SetFont(wx.Font(9, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
sizer.Add(text, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 10)
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
copy_btn = wx.Button(dlg, label="Copy to Clipboard")
copy_btn.Bind(wx.EVT_BUTTON, lambda e: copy_to_clipboard(debug_info))