-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpinout.py
More file actions
895 lines (705 loc) · 35.7 KB
/
pinout.py
File metadata and controls
895 lines (705 loc) · 35.7 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
"""
KiRender Pinout/2D Documentation Module - v3
Generates annotated 2D documentation images with component labels,
pin callouts, and highlight groups using KiCad's 3D renderer or SVG export.
Uses cli_builder for all CLI generation (single source of truth).
"""
# Force module reload - change this to bust cache
_MODULE_VERSION = "3.1"
print(f"[KiRender] pinout.py loaded, version {_MODULE_VERSION}")
import os
import sys
import csv
import subprocess
import threading
import tempfile
import wx
try:
from PIL import Image, ImageDraw, ImageFont
HAS_PIL = True
except ImportError:
HAS_PIL = False
# Import CLI builder - the single source of truth for CLI construction
from .cli_builder import build_cli_command
class PinoutRenderThread(threading.Thread):
"""Thread for generating annotated 2D documentation renders or SVG exports."""
def __init__(self, parent, params):
super().__init__()
self.parent = parent
self.params = params
self.daemon = True
self._cancelled = False
def cancel(self):
self._cancelled = True
def run(self):
try:
self._do_render()
except Exception as e:
wx.CallAfter(self.parent.on_render_error, str(e))
def _do_render(self):
p = self.params
startupinfo = None
creationflags = 0
if sys.platform == "win32":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
creationflags = subprocess.CREATE_NO_WINDOW
# Debug log the output format
wx.CallAfter(self.parent.log, f"Output format received: {p.get('output_format', 'NOT SET')}")
# Check if SVG output format is selected
if p.get('output_format') == 'svg':
wx.CallAfter(self.parent.log, "Routing to SVG export...")
self._do_svg_export(p, startupinfo, creationflags)
return
wx.CallAfter(self.parent.log, "Routing to PNG export...")
# Step 1: Export position file
wx.CallAfter(self.parent.log, "Extracting component positions...")
wx.CallAfter(self.parent.update_progress, 10, "Getting positions")
pos_file = os.path.join(tempfile.gettempdir(), "kirender_positions.csv")
pos_cmd = [
p['kicad_cli'], "pcb", "export", "pos",
"--format", "csv",
"--units", "mm",
"--side", "both",
"-o", pos_file,
p['pcb_path']
]
result = subprocess.run(pos_cmd, startupinfo=startupinfo,
creationflags=creationflags, capture_output=True, text=True)
if result.returncode != 0:
wx.CallAfter(self.parent.log, f"Position export error: {result.stderr}")
# Parse positions
components = self._parse_positions(pos_file, p['side'])
wx.CallAfter(self.parent.log, f"Found {len(components)} components on {p['side']} side")
if self._cancelled:
return
# Step 2: Render orthographic view
wx.CallAfter(self.parent.log, "Rendering orthographic view...")
wx.CallAfter(self.parent.update_progress, 30, "Rendering")
render_file = os.path.join(tempfile.gettempdir(), "kirender_ortho.png")
# Build CLI params for orthographic render
cli_params = {
'side': p['side'],
'width': p['width'],
'height': p['height'],
'background': p.get('background', 'opaque'),
'quality': p.get('quality', 'high'),
}
# Use unified CLI builder
render_cmd = build_cli_command(cli_params, p['kicad_cli'], p['pcb_path'], render_file)
result = subprocess.run(render_cmd, startupinfo=startupinfo,
creationflags=creationflags, capture_output=True, text=True)
if result.returncode != 0:
wx.CallAfter(self.parent.log, f"Render error: {result.stderr}")
wx.CallAfter(self.parent.on_render_error, f"Render failed: {result.stderr}")
return
wx.CallAfter(self.parent.log, "✓ Base render complete")
if self._cancelled:
return
# Step 3: Add labels if PIL available and labels enabled
if HAS_PIL and p.get('show_labels', True):
wx.CallAfter(self.parent.log, "Adding component labels...")
wx.CallAfter(self.parent.update_progress, 60, "Adding labels")
output_file = self._add_labels(render_file, components, p)
else:
output_file = render_file
if not HAS_PIL and p.get('show_labels', True):
wx.CallAfter(self.parent.log, "⚠ PIL not installed, skipping labels")
if self._cancelled:
return
# Step 4: Copy to output location
wx.CallAfter(self.parent.update_progress, 90, "Saving")
import shutil
final_output = p['output_file']
# Ensure output directory exists
os.makedirs(os.path.dirname(final_output), exist_ok=True)
if output_file != final_output:
shutil.copy2(output_file, final_output)
wx.CallAfter(self.parent.log, f"✓ Saved: {os.path.basename(final_output)}")
wx.CallAfter(self.parent.on_render_complete, final_output)
def _parse_positions(self, pos_file, side):
"""Parse component positions from CSV file."""
components = []
side_filter = "top" if side == "top" else "bottom"
try:
with open(pos_file, 'r', newline='') as f:
# Skip header comment lines
lines = f.readlines()
data_lines = [l for l in lines if not l.startswith('#')]
reader = csv.DictReader(data_lines)
for row in reader:
# Handle different CSV column names
ref = row.get('Ref', row.get('Reference', row.get('ref', '')))
val = row.get('Val', row.get('Value', row.get('val', '')))
pkg = row.get('Package', row.get('Footprint', row.get('package', '')))
pos_x = float(row.get('PosX', row.get('X', row.get('posx', 0))))
pos_y = float(row.get('PosY', row.get('Y', row.get('posy', 0))))
rot = float(row.get('Rot', row.get('Rotation', row.get('rot', 0))))
comp_side = row.get('Side', row.get('side', 'top')).lower()
if comp_side == side_filter:
components.append({
'ref': ref,
'value': val,
'footprint': pkg,
'x': pos_x,
'y': pos_y,
'rotation': rot,
'side': comp_side
})
except Exception as e:
wx.CallAfter(self.parent.log, f"Position parse error: {e}")
return components
def _add_labels(self, render_file, components, params):
"""Add component labels to the render using PIL."""
img = Image.open(render_file)
draw = ImageDraw.Draw(img)
# Get image dimensions for coordinate mapping
img_w, img_h = img.size
# Try to load a font
font_size = params.get('label_size', 12)
try:
# Try common fonts
for font_name in ['arial.ttf', 'Arial.ttf', 'DejaVuSans.ttf', 'FreeSans.ttf']:
try:
font = ImageFont.truetype(font_name, font_size)
break
except:
continue
else:
font = ImageFont.load_default()
except:
font = ImageFont.load_default()
# Label settings
label_color = params.get('label_color', (255, 255, 255))
bg_color = params.get('label_bg', (0, 0, 0, 180))
show_refs = params.get('show_refs', True)
show_values = params.get('show_values', False)
highlight_pattern = params.get('highlight_pattern', '')
highlight_color = params.get('highlight_color', (255, 255, 0))
# Filter by pattern if specified
filter_pattern = params.get('filter_pattern', '')
# Board bounds estimation (we'd need to get this from KiCad ideally)
# For now, use center-based scaling
if components:
xs = [c['x'] for c in components]
ys = [c['y'] for c in components]
min_x, max_x = min(xs), max(xs)
min_y, max_y = min(ys), max(ys)
# Add padding
pad_x = (max_x - min_x) * 0.1 or 10
pad_y = (max_y - min_y) * 0.1 or 10
min_x -= pad_x
max_x += pad_x
min_y -= pad_y
max_y += pad_y
board_w = max_x - min_x
board_h = max_y - min_y
else:
return render_file
# Draw labels for each component
for comp in components:
ref = comp['ref']
# Apply filter if specified
if filter_pattern:
import fnmatch
if not fnmatch.fnmatch(ref, filter_pattern):
continue
# Calculate pixel position
norm_x = (comp['x'] - min_x) / board_w
norm_y = (comp['y'] - min_y) / board_h
# Flip Y for image coordinates and account for render margins
# The render has some margin, estimate at ~10%
margin = 0.1
px = int(img_w * (margin + norm_x * (1 - 2*margin)))
py = int(img_h * (margin + (1 - norm_y) * (1 - 2*margin)))
# Build label text
label_parts = []
if show_refs:
label_parts.append(ref)
if show_values and comp['value']:
label_parts.append(comp['value'])
if not label_parts:
continue
label_text = " ".join(label_parts)
# Check if this component should be highlighted
is_highlighted = False
if highlight_pattern:
import fnmatch
if fnmatch.fnmatch(ref, highlight_pattern):
is_highlighted = True
# Get text size
bbox = draw.textbbox((0, 0), label_text, font=font)
text_w = bbox[2] - bbox[0]
text_h = bbox[3] - bbox[1]
# Draw background rectangle
rect_pad = 2
rect = [
px - text_w//2 - rect_pad,
py - text_h//2 - rect_pad,
px + text_w//2 + rect_pad,
py + text_h//2 + rect_pad
]
if is_highlighted:
draw.rectangle(rect, fill=(*highlight_color, 200))
draw.text((px - text_w//2, py - text_h//2), label_text, fill=(0, 0, 0), font=font)
else:
draw.rectangle(rect, fill=bg_color)
draw.text((px - text_w//2, py - text_h//2), label_text, fill=label_color, font=font)
# Save labeled image
output_file = render_file.replace('.png', '_labeled.png')
img.save(output_file)
return output_file
def _do_svg_export(self, params, startupinfo, creationflags):
"""Export PCB as hybrid SVG with embedded 3D render + vector labels."""
p = params
wx.CallAfter(self.parent.log, "Creating hybrid SVG (3D render + vector labels)...")
wx.CallAfter(self.parent.update_progress, 10, "Starting SVG export")
if self._cancelled:
return
# Ensure output directory exists
output_dir = os.path.dirname(p['output_file'])
if output_dir:
os.makedirs(output_dir, exist_ok=True)
# Step 1: Render 3D orthographic view as PNG (with 3D models)
wx.CallAfter(self.parent.log, "Rendering 3D view...")
wx.CallAfter(self.parent.update_progress, 20, "Rendering 3D")
temp_png = os.path.join(tempfile.gettempdir(), "kirender_3d_for_svg.png")
# Build CLI params from render parameters
cli_params = {
'width': p.get('width', 2400),
'height': p.get('height', 1600),
'side': p.get('side', 'top'),
'background': 'transparent',
'quality': p.get('quality', 'basic'),
'perspective': p.get('perspective', False),
'zoom': p.get('zoom', 1.0),
'pan': p.get('pan', ''),
'pivot': p.get('pivot', ''),
'rotate': p.get('rotate', ''),
}
wx.CallAfter(self.parent.log, f"Quality: {cli_params['quality']}")
# Build render command using unified CLI builder
render_cmd = build_cli_command(cli_params, p['kicad_cli'], p['pcb_path'], temp_png)
# Log exact CLI command for debugging
cmd_display = ' '.join(render_cmd)
wx.CallAfter(self.parent.log, f"CLI: {cmd_display}")
result = subprocess.run(render_cmd, startupinfo=startupinfo,
creationflags=creationflags, capture_output=True, text=True)
if result.returncode != 0:
wx.CallAfter(self.parent.log, f"3D render error: {result.stderr}")
wx.CallAfter(self.parent.on_render_error, f"3D render failed: {result.stderr}")
return
if not os.path.exists(temp_png):
wx.CallAfter(self.parent.on_render_error, "3D render produced no output")
return
wx.CallAfter(self.parent.log, "✓ 3D render complete")
if self._cancelled:
return
# Step 2: Get component positions
wx.CallAfter(self.parent.log, "Getting component positions...")
wx.CallAfter(self.parent.update_progress, 50, "Getting positions")
pos_file = os.path.join(tempfile.gettempdir(), "kirender_positions.csv")
pos_cmd = [
p['kicad_cli'], "pcb", "export", "pos",
"--format", "csv",
"--units", "mm",
"--side", "both",
"-o", pos_file,
p['pcb_path']
]
result = subprocess.run(pos_cmd, startupinfo=startupinfo,
creationflags=creationflags, capture_output=True, text=True)
components = []
if result.returncode == 0:
components = self._parse_positions(pos_file, p['side'])
wx.CallAfter(self.parent.log, f"Found {len(components)} components")
if self._cancelled:
return
# Step 3: Create SVG with embedded 3D render + vector labels
wx.CallAfter(self.parent.log, "Creating SVG with 3D render + vector labels...")
wx.CallAfter(self.parent.update_progress, 70, "Creating SVG")
self._create_hybrid_svg(temp_png, components, p)
wx.CallAfter(self.parent.update_progress, 100, "Done")
wx.CallAfter(self.parent.log, f"✓ Saved: {os.path.basename(p['output_file'])}")
wx.CallAfter(self.parent.on_render_complete, p['output_file'])
def _get_board_bounds(self, pcb_path):
"""Extract board bounds from KiCad PCB file (Edge.Cuts layer) - fast line-by-line parsing."""
import re
min_x, min_y = float('inf'), float('inf')
max_x, max_y = float('-inf'), float('-inf')
try:
# Line-by-line parsing is much faster than regex on whole file
coord_pattern = re.compile(r'\((?:start|end|at)\s+([\d.-]+)\s+([\d.-]+)\)')
with open(pcb_path, 'r', encoding='utf-8') as f:
in_edge_cuts = False
for line in f:
# Check if this line mentions Edge.Cuts
if 'Edge.Cuts' in line:
in_edge_cuts = True
# Extract coordinates from this line
for match in coord_pattern.finditer(line):
x, y = float(match.group(1)), float(match.group(2))
min_x, min_y = min(min_x, x), min(min_y, y)
max_x, max_y = max(max_x, x), max(max_y, y)
elif in_edge_cuts and line.strip().startswith('('):
# Still in a multi-line Edge.Cuts element
for match in coord_pattern.finditer(line):
x, y = float(match.group(1)), float(match.group(2))
min_x, min_y = min(min_x, x), min(min_y, y)
max_x, max_y = max(max_x, x), max(max_y, y)
if ')' in line and '(' not in line[line.index(')'):]:
in_edge_cuts = False
else:
in_edge_cuts = False
except Exception as e:
return None
if min_x == float('inf'):
return None
return (min_x, min_y, max_x, max_y)
def _create_hybrid_svg(self, png_file, components, params):
"""Create SVG with embedded 3D render PNG and vector text labels."""
import base64
try:
# Check PNG file exists and size
if not os.path.exists(png_file):
wx.CallAfter(self.parent.log, f"Error: PNG file not found: {png_file}")
wx.CallAfter(self.parent.on_render_error, "3D render PNG not found")
return
file_size = os.path.getsize(png_file)
wx.CallAfter(self.parent.log, f"PNG file size: {file_size / 1024 / 1024:.1f} MB")
# Read PNG and get dimensions
with open(png_file, 'rb') as f:
png_data = f.read()
wx.CallAfter(self.parent.log, "Encoding PNG to base64...")
png_base64 = base64.b64encode(png_data).decode('utf-8')
wx.CallAfter(self.parent.log, "Getting PNG dimensions...")
# Get PNG dimensions
if HAS_PIL:
img = Image.open(png_file)
img_w, img_h = img.size
img.close()
else:
# Default dimensions if PIL not available
img_w, img_h = params.get('width', 2400), params.get('height', 1600)
wx.CallAfter(self.parent.log, f"PNG dimensions: {img_w}x{img_h}")
# Try to get actual board bounds from PCB file
wx.CallAfter(self.parent.log, "Parsing board bounds...")
board_bounds = self._get_board_bounds(params['pcb_path'])
wx.CallAfter(self.parent.log, f"Board bounds result: {board_bounds}")
if board_bounds:
min_x, min_y, max_x, max_y = board_bounds
wx.CallAfter(self.parent.log, f"Board bounds: ({min_x:.1f}, {min_y:.1f}) to ({max_x:.1f}, {max_y:.1f}) mm")
elif components:
# Fallback: estimate from component positions
xs = [c['x'] for c in components]
ys = [c['y'] for c in components]
min_x, max_x = min(xs), max(xs)
min_y, max_y = min(ys), max(ys)
wx.CallAfter(self.parent.log, f"Estimated bounds from components: ({min_x:.1f}, {min_y:.1f}) to ({max_x:.1f}, {max_y:.1f}) mm")
else:
min_x, min_y, max_x, max_y = 0, 0, 100, 100
# Calculate board dimensions
board_w = max_x - min_x
board_h = max_y - min_y
# kicad-cli render adds margin around the board
# The render viewport is approximately: board + 5% margin on each side
# So total viewport = board * 1.1
render_margin = 0.05 # 5% margin on each side
viewport_w = board_w * (1 + 2 * render_margin)
viewport_h = board_h * (1 + 2 * render_margin)
# Board starts at margin offset within viewport
board_offset_x = board_w * render_margin
board_offset_y = board_h * render_margin
# Calculate scale: pixels per mm
# The render fits the board (with margin) into the image
scale_x = img_w / viewport_w if viewport_w else 1
scale_y = img_h / viewport_h if viewport_h else 1
# Use uniform scale (aspect ratio preserved, centered)
scale = min(scale_x, scale_y)
# Center offset if aspect ratios don't match
used_w = viewport_w * scale
used_h = viewport_h * scale
offset_x = (img_w - used_w) / 2
offset_y = (img_h - used_h) / 2
wx.CallAfter(self.parent.log, f"Coordinate mapping: scale={scale:.2f} px/mm, offset=({offset_x:.1f}, {offset_y:.1f})")
# Label settings
font_size = params.get('label_size', 14)
show_refs = params.get('show_refs', True)
show_values = params.get('show_values', False)
filter_pattern = params.get('filter_pattern', '')
highlight_pattern = params.get('highlight_pattern', '')
show_labels = params.get('show_labels', True)
# Background color mapping
bg_choice = params.get('background', 'white')
bg_colors = {
'transparent': None,
'white': '#ffffff',
'light gray': '#f0f0f0',
'black': '#1a1a1a',
'opaque': '#ffffff', # Legacy support
}
bg_color = bg_colors.get(bg_choice, '#ffffff')
# Build SVG
svg_lines = []
svg_lines.append('<?xml version="1.0" encoding="UTF-8"?>')
svg_lines.append(f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ')
svg_lines.append(f' width="{img_w}" height="{img_h}" viewBox="0 0 {img_w} {img_h}">')
svg_lines.append(f' <title>PCB Pinout - {os.path.basename(params["pcb_path"])}</title>')
svg_lines.append(f' <desc>Generated by KiRender - 3D render with vector labels</desc>')
# Add background rectangle if not transparent
if bg_color:
svg_lines.append(f' <rect x="0" y="0" width="{img_w}" height="{img_h}" fill="{bg_color}"/>')
# Embed the 3D render as background image
svg_lines.append(f' <image x="0" y="0" width="{img_w}" height="{img_h}" ')
svg_lines.append(f' xlink:href="data:image/png;base64,{png_base64}"/>')
# Add vector labels on top
if show_labels and components:
svg_lines.append(' <g id="component-labels" style="font-family: Arial, Helvetica, sans-serif;">')
for comp in components:
ref = comp['ref']
# Apply filter
if filter_pattern:
import fnmatch
if not fnmatch.fnmatch(ref, filter_pattern):
continue
# Build label text
label_parts = []
if show_refs:
label_parts.append(ref)
if show_values and comp['value']:
label_parts.append(comp['value'])
if not label_parts:
continue
label_text = " ".join(label_parts)
# Map component position (mm) to image pixels
# Component position is relative to board origin (0,0)
# Board spans from (min_x, min_y) to (max_x, max_y) in mm
# Render has margin around board
# Position within board (0 to board_w/h)
pos_in_board_x = comp['x'] - min_x
pos_in_board_y = comp['y'] - min_y
# Position within viewport (including margin)
pos_in_viewport_x = board_offset_x + pos_in_board_x
pos_in_viewport_y = board_offset_y + pos_in_board_y
# Convert to pixels
px = offset_x + pos_in_viewport_x * scale
# Y is flipped: KiCad Y increases downward, image Y increases downward too
# But render shows top view, so Y should be flipped
py = offset_y + (viewport_h - pos_in_viewport_y) * scale
# Check if highlighted
is_highlighted = False
if highlight_pattern:
import fnmatch
if fnmatch.fnmatch(ref, highlight_pattern):
is_highlighted = True
# Label styling
rect_w = len(label_text) * font_size * 0.6
rect_h = font_size * 1.5
if is_highlighted:
label_bg = "#ffff00"
label_opacity = "0.9"
text_color = "#000000"
else:
label_bg = "#000000"
label_opacity = "0.75"
text_color = "#ffffff"
# Create label group
svg_lines.append(f' <g transform="translate({px:.1f},{py:.1f})">')
svg_lines.append(f' <rect x="{-rect_w/2:.1f}" y="{-rect_h/2:.1f}" width="{rect_w:.1f}" height="{rect_h:.1f}" ')
svg_lines.append(f' fill="{label_bg}" fill-opacity="{label_opacity}" rx="3"/>')
svg_lines.append(f' <text x="0" y="{font_size*0.35:.1f}" text-anchor="middle" ')
svg_lines.append(f' font-size="{font_size}" fill="{text_color}" font-weight="bold">{label_text}</text>')
svg_lines.append(' </g>')
svg_lines.append(' </g>')
svg_lines.append('</svg>')
# Write SVG file
wx.CallAfter(self.parent.log, "Writing SVG file...")
svg_content = '\n'.join(svg_lines)
with open(params['output_file'], 'w', encoding='utf-8') as f:
f.write(svg_content)
wx.CallAfter(self.parent.log, f"SVG file written successfully")
except Exception as e:
import traceback
error_msg = f"SVG creation error: {e}\n{traceback.format_exc()}"
wx.CallAfter(self.parent.log, error_msg)
wx.CallAfter(self.parent.on_render_error, f"SVG creation failed: {e}")
def _add_svg_labels(self, svg_file, components, params):
"""Add component labels as SVG text elements."""
import re
# Read the SVG file
with open(svg_file, 'r', encoding='utf-8') as f:
svg_content = f.read()
# Extract viewBox dimensions to understand coordinate system
# KiCad SVG viewBox is in mm and matches board coordinates
viewbox_match = re.search(r'viewBox="([^"]+)"', svg_content)
if not viewbox_match:
wx.CallAfter(self.parent.log, "Warning: No viewBox found in SVG")
return
vb = viewbox_match.group(1).split()
vb_x, vb_y, vb_w, vb_h = float(vb[0]), float(vb[1]), float(vb[2]), float(vb[3])
wx.CallAfter(self.parent.log, f"SVG viewBox: x={vb_x:.1f} y={vb_y:.1f} w={vb_w:.1f} h={vb_h:.1f}")
if not components:
return
# Label settings - scale font size based on board size
base_font_size = params.get('label_size', 12)
# Estimate a reasonable font size based on viewBox (board is typically 50-200mm)
font_size = max(1.0, min(base_font_size, vb_w / 30))
show_refs = params.get('show_refs', True)
show_values = params.get('show_values', False)
filter_pattern = params.get('filter_pattern', '')
highlight_pattern = params.get('highlight_pattern', '')
# Build label SVG elements
labels_svg = []
labels_svg.append('<g id="component-labels" style="font-family: Arial, sans-serif;">')
for comp in components:
ref = comp['ref']
# Apply filter if specified
if filter_pattern:
import fnmatch
if not fnmatch.fnmatch(ref, filter_pattern):
continue
# Build label text
label_parts = []
if show_refs:
label_parts.append(ref)
if show_values and comp['value']:
label_parts.append(comp['value'])
if not label_parts:
continue
label_text = " ".join(label_parts)
# KiCad position file gives coordinates in mm from board origin
# SVG viewBox is also in mm - use coordinates directly
# Y axis: KiCad uses Y-down in position file, SVG also uses Y-down
svg_x = comp['x']
svg_y = comp['y']
# Check if highlighted
is_highlighted = False
if highlight_pattern:
import fnmatch
if fnmatch.fnmatch(ref, highlight_pattern):
is_highlighted = True
# Create label element with background rect
rect_w = len(label_text) * font_size * 0.6
rect_h = font_size * 1.4
if is_highlighted:
bg_color = "#ffff00"
bg_opacity = "1"
text_color = "#000000"
else:
bg_color = "#000000"
bg_opacity = "0.7"
text_color = "#ffffff"
labels_svg.append(f' <g transform="translate({svg_x:.3f},{svg_y:.3f})">')
labels_svg.append(f' <rect x="{-rect_w/2:.3f}" y="{-rect_h/2:.3f}" width="{rect_w:.3f}" height="{rect_h:.3f}" fill="{bg_color}" fill-opacity="{bg_opacity}" rx="0.5"/>')
labels_svg.append(f' <text x="0" y="{font_size*0.35:.3f}" text-anchor="middle" font-size="{font_size:.2f}" fill="{text_color}">{label_text}</text>')
labels_svg.append(' </g>')
labels_svg.append('</g>')
# Insert labels before closing </svg> tag
labels_str = '\n'.join(labels_svg)
svg_content = svg_content.replace('</svg>', f'{labels_str}\n</svg>')
# Write modified SVG
with open(svg_file, 'w', encoding='utf-8') as f:
f.write(svg_content)
class BOMExportThread(threading.Thread):
"""Thread for exporting Bill of Materials."""
def __init__(self, parent, params):
super().__init__()
self.parent = parent
self.params = params
self.daemon = True
def run(self):
try:
self._do_export()
except Exception as e:
wx.CallAfter(self.parent.on_render_error, str(e))
def _do_export(self):
p = self.params
startupinfo = None
creationflags = 0
if sys.platform == "win32":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
creationflags = subprocess.CREATE_NO_WINDOW
wx.CallAfter(self.parent.log, "Exporting position/BOM data...")
wx.CallAfter(self.parent.update_progress, 30, "Exporting")
# Export position file
pos_cmd = [
p['kicad_cli'], "pcb", "export", "pos",
"--format", p.get('format', 'csv'),
"--units", p.get('units', 'mm'),
"--side", p.get('side', 'both'),
"-o", p['output_file'],
p['pcb_path']
]
if p.get('exclude_dnp', False):
pos_cmd.insert(-2, "--exclude-dnp")
if p.get('smd_only', False):
pos_cmd.insert(-2, "--smd-only")
result = subprocess.run(pos_cmd, startupinfo=startupinfo,
creationflags=creationflags, capture_output=True, text=True)
if result.returncode != 0:
wx.CallAfter(self.parent.log, f"Export error: {result.stderr}")
wx.CallAfter(self.parent.on_render_error, f"Export failed: {result.stderr}")
return
wx.CallAfter(self.parent.log, f"✓ Exported: {os.path.basename(p['output_file'])}")
wx.CallAfter(self.parent.on_render_complete, p['output_file'])
class Assembly3DExportThread(threading.Thread):
"""Thread for exporting 3D assembly files (STEP/GLB)."""
def __init__(self, parent, params):
super().__init__()
self.parent = parent
self.params = params
self.daemon = True
def run(self):
try:
self._do_export()
except Exception as e:
wx.CallAfter(self.parent.on_render_error, str(e))
def _do_export(self):
p = self.params
startupinfo = None
creationflags = 0
if sys.platform == "win32":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
creationflags = subprocess.CREATE_NO_WINDOW
export_format = p.get('format', 'step')
wx.CallAfter(self.parent.log, f"Exporting {export_format.upper()} file...")
wx.CallAfter(self.parent.update_progress, 20, f"Exporting {export_format.upper()}")
cmd = [
p['kicad_cli'], "pcb", "export", export_format,
"-o", p['output_file'],
p['pcb_path']
]
# Add optional flags
if p.get('board_only', False):
cmd.insert(4, "--board-only")
if p.get('no_components', False):
cmd.insert(4, "--no-components")
if p.get('component_filter'):
cmd.insert(4, "--component-filter")
cmd.insert(5, p['component_filter'])
if p.get('include_tracks', False):
cmd.insert(4, "--include-tracks")
if p.get('include_pads', False):
cmd.insert(4, "--include-pads")
if p.get('include_zones', False):
cmd.insert(4, "--include-zones")
if p.get('include_silkscreen', False):
cmd.insert(4, "--include-silkscreen")
if p.get('include_soldermask', False):
cmd.insert(4, "--include-soldermask")
if p.get('no_dnp', False):
cmd.insert(4, "--no-dnp")
cmd.insert(4, "-f") # Force overwrite
result = subprocess.run(cmd, startupinfo=startupinfo,
creationflags=creationflags, capture_output=True, text=True)
if result.returncode != 0:
wx.CallAfter(self.parent.log, f"Export error: {result.stderr}")
wx.CallAfter(self.parent.on_render_error, f"Export failed: {result.stderr}")
return
wx.CallAfter(self.parent.log, f"✓ Exported: {os.path.basename(p['output_file'])}")
wx.CallAfter(self.parent.on_render_complete, p['output_file'])
# Check PIL availability
def check_pil():
return HAS_PIL