-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunified_gui.py
More file actions
executable file
·1627 lines (1378 loc) · 65.4 KB
/
Copy pathunified_gui.py
File metadata and controls
executable file
·1627 lines (1378 loc) · 65.4 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
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Unified GDS to KiCad Workflow GUI
Single application with 5 tabs:
1. Extract Pins - load GDS/LYP, prepare stripped GDS, extract pin list
2. Pin List Editor - review/edit pin names, types, sides
3. Symbol Designer - generate .kicad_sym from pin list
4. Footprint Generator - generate .kicad_mod from extraction data
5. History - conversion registry
"""
import sys
import json
import uuid
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, List
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QTextEdit, QFileDialog,
QGroupBox, QMessageBox, QTabWidget, QTableWidget, QTableWidgetItem,
QHeaderView, QAbstractItemView, QComboBox, QSplitter, QSlider, QCheckBox,
)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QColor, QAction
from theme import COLORS, STYLESHEET, FilterableComboBox
from lyp_parser import LYPParser
from pin_extractor import PinExtractor
from pin_list import PinList, PinEntry, VALID_PIN_TYPES, VALID_PIN_SIDES
from pad_review import PadReview
from kicad_sym_writer import (
KiCadSymWriter, SymbolDefinition, SymbolPin, PinSide, PinType,
)
from symbol_layout import (
create_layout_from_pin_list,
calculate_body_size,
)
from preview_widgets import SymbolPreviewWidget, LayoutPreviewWidget
from _paths import resolve_data_dir, atomic_write
# Style override for QComboBox embedded in QTableWidget cells
TABLE_COMBO_STYLE = "QComboBox { min-width: 0px; padding: 2px 4px; }"
# =============================================================================
# Conversion Registry
# =============================================================================
class ConversionRegistry:
"""Manages JSON database of conversion records."""
def __init__(self, registry_path: str):
self.registry_path = Path(registry_path)
# NOTE: do not create the parent folder here. Merely launching the GUI
# instantiates this registry, and creating the folder eagerly would
# litter the working directory with generated_kicad_symbol_files/ even
# when the user never saves anything. The folder is created lazily in
# save(), i.e. only when there is actually something to persist.
self.data: Dict = {"conversions": []}
self.load()
def load(self):
data = None
if self.registry_path.exists():
try:
with open(self.registry_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except (json.JSONDecodeError, IOError):
data = None
# Accept only the expected shape; any valid-JSON-but-wrong-schema file
# (e.g. '{}', a bare list, a half-written file) would otherwise KeyError
# later in get_entries/add_entry and brick the GUI on startup.
if isinstance(data, dict) and isinstance(data.get("conversions"), list):
self.data = data
else:
self.data = {"conversions": []}
def save(self):
# Create the output folder on demand -- only now that there is content
# to persist -- so launching the GUI never creates it by itself.
self.registry_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.registry_path, 'w', encoding='utf-8') as f:
json.dump(self.data, f, indent=2)
def add_entry(self, entry_type: str, **kwargs) -> str:
entry_id = str(uuid.uuid4())[:8]
entry = {
"id": entry_id,
"timestamp": datetime.now().isoformat(),
"type": entry_type,
**kwargs,
}
self.data["conversions"].append(entry)
self.save()
return entry_id
def get_entries(self) -> List[Dict]:
return self.data["conversions"]
def delete_entry(self, entry_id: str) -> bool:
for i, entry in enumerate(self.data["conversions"]):
if entry.get("id") == entry_id:
del self.data["conversions"][i]
self.save()
return True
return False
# =============================================================================
# Main Window
# =============================================================================
class UnifiedMainWindow(QMainWindow):
# Writable base (CWD or $GDS_TO_KICAD_DATA_DIR), never the read-only
# install dir. See _paths.resolve_data_dir().
DATA_DIR = resolve_data_dir()
DEFAULT_OUTPUT_DIR = DATA_DIR / "generated_kicad_symbol_files"
REGISTRY_PATH = DEFAULT_OUTPUT_DIR / "unified_registry.json"
# Folder the terminal was in when the tool was launched (captured at import).
# Used as the default suggestion for the export dialogs (pin list, .kicad_sym,
# .kicad_mod), so exports land where the user invoked the tool rather than in
# an internal output dir.
INVOCATION_DIR = Path.cwd()
# Project file: stores the input GDS/LYP/stripped-GDS *paths* (the files
# are expected to stay in place), the layer selections, the extraction
# source and the edited pin list, so a session can be reopened later.
PROJECT_FORMAT = "gds-to-kicad-project"
PROJECT_VERSION = 1
def __init__(self):
super().__init__()
self.setWindowTitle("GDS to KiCad -- Unified Workflow")
self.setMinimumSize(1200, 850)
self.registry = ConversionRegistry(str(self.REGISTRY_PATH))
self.lyp_parser: Optional[LYPParser] = None
self.current_pin_list: Optional[PinList] = None
self.current_symbol: Optional[SymbolDefinition] = None
self.stripped_gds_path: Optional[str] = None
self.pad_dicts: List[dict] = []
self._setup_ui()
self.setStyleSheet(STYLESHEET)
def _setup_ui(self):
self._build_menu_bar()
central = QWidget()
self.setCentralWidget(central)
main_layout = QVBoxLayout(central)
main_layout.setSpacing(10)
main_layout.setContentsMargins(15, 15, 15, 15)
title = QLabel("GDS to KiCad -- Unified Workflow")
title.setFont(QFont("Monospace", 14, QFont.Weight.Bold))
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
main_layout.addWidget(title)
self.tabs = QTabWidget()
self._build_extract_tab()
self._build_pin_editor_tab()
self._build_symbol_tab()
self._build_footprint_tab()
self._build_history_tab()
# Vertical splitter: tabs (top) + log (bottom) -- user can drag to resize
self.main_splitter = QSplitter(Qt.Orientation.Vertical)
self.main_splitter.addWidget(self.tabs)
log_widget = QWidget()
log_widget.setMinimumHeight(30) # keep header visible when splitter dragged small
log_inner = QVBoxLayout(log_widget)
log_inner.setContentsMargins(0, 0, 0, 0)
log_inner.setSpacing(2)
log_header = QHBoxLayout()
log_label = QLabel("Log")
log_label.setFont(QFont("Monospace", 10, QFont.Weight.Bold))
log_header.addWidget(log_label)
log_header.addStretch()
self.log_toggle_btn = QPushButton("Hide")
self.log_toggle_btn.setFixedWidth(60)
self.log_toggle_btn.clicked.connect(self._toggle_log)
log_header.addWidget(self.log_toggle_btn)
log_inner.addLayout(log_header)
self.log_text = QTextEdit()
self.log_text.setReadOnly(True)
log_inner.addWidget(self.log_text)
self.main_splitter.addWidget(log_widget)
self.main_splitter.setCollapsible(1, False) # prevent collapsing past min height
self.main_splitter.setSizes([700, 100])
main_layout.addWidget(self.main_splitter)
self.statusBar().showMessage("Ready")
self.statusBar().setStyleSheet(f"color: {COLORS['text_secondary']};")
self._log("Application started. Begin by extracting pins from a GDS file.")
self._refresh_history()
# =========================================================================
# Logging
# =========================================================================
def _log(self, message: str, is_error: bool = False):
timestamp = datetime.now().strftime("%H:%M:%S")
color = COLORS['error'] if is_error else COLORS['text_primary']
self.log_text.append(
f'<span style="color: {COLORS["text_secondary"]}">[{timestamp}]</span> '
f'<span style="color: {color}">{message}</span>'
)
def _toggle_log(self):
if self.log_text.isVisible():
self.log_text.hide()
self.log_toggle_btn.setText("Show")
else:
self.log_text.show()
self.log_toggle_btn.setText("Hide")
# Restore log panel if splitter was dragged too small
sizes = self.main_splitter.sizes()
if sizes[1] < 100:
self.main_splitter.setSizes([sizes[0], 100])
# =========================================================================
# Tab 1: Extract Pins
# =========================================================================
def _build_extract_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Input group
input_group = QGroupBox("Input Configuration")
ig_layout = QVBoxLayout(input_group)
# GDS File
gds_row = QHBoxLayout()
gds_label = QLabel("GDS File:")
gds_label.setFixedWidth(110)
self.gds_path_edit = QLineEdit()
self.gds_path_edit.setPlaceholderText("Select a GDSII file...")
gds_btn = QPushButton("Browse...")
gds_btn.clicked.connect(self._select_gds_file)
gds_row.addWidget(gds_label)
gds_row.addWidget(self.gds_path_edit)
gds_row.addWidget(gds_btn)
ig_layout.addLayout(gds_row)
# LYP File
lyp_row = QHBoxLayout()
lyp_label = QLabel("LYP File:")
lyp_label.setFixedWidth(110)
self.lyp_path_edit = QLineEdit()
self.lyp_path_edit.setPlaceholderText("Select a KLayout .lyp file...")
lyp_btn = QPushButton("Browse...")
lyp_btn.clicked.connect(self._select_lyp_file)
lyp_row.addWidget(lyp_label)
lyp_row.addWidget(self.lyp_path_edit)
lyp_row.addWidget(lyp_btn)
ig_layout.addLayout(lyp_row)
# Pad Layer
pad_row = QHBoxLayout()
pad_label = QLabel("Pad Layer:")
pad_label.setFixedWidth(110)
self.pad_layer_combo = FilterableComboBox()
self.pad_layer_combo.setPlaceholderText("Select LYP file first...")
self.pad_layer_combo.setEnabled(False)
self.scan_btn = QPushButton("Scan GDS")
self.scan_btn.setEnabled(False)
self.scan_btn.clicked.connect(self._scan_gds_layers)
pad_row.addWidget(pad_label)
pad_row.addWidget(self.pad_layer_combo)
pad_row.addWidget(self.scan_btn)
ig_layout.addLayout(pad_row)
# Text Layer
text_row = QHBoxLayout()
text_label = QLabel("Text Layer:")
text_label.setFixedWidth(110)
self.text_layer_combo = FilterableComboBox()
self.text_layer_combo.setPlaceholderText("Auto-detect (or select)")
self.text_layer_combo.setEnabled(False)
text_row.addWidget(text_label)
text_row.addWidget(self.text_layer_combo)
text_row.addStretch()
ig_layout.addLayout(text_row)
layout.addWidget(input_group)
# GDS Preparation
prep_group = QGroupBox("Prepare GDS for Extraction")
prep_layout = QVBoxLayout(prep_group)
prep_btn_row = QHBoxLayout()
gen_stripped_btn = QPushButton("Generate Stripped GDS")
gen_stripped_btn.clicked.connect(self._generate_stripped_gds)
open_stripped_btn = QPushButton("Open Stripped GDS in KLayout")
open_stripped_btn.clicked.connect(self._open_stripped_in_klayout)
open_full_btn = QPushButton("Open Full GDS in KLayout")
open_full_btn.clicked.connect(self._open_full_in_klayout)
prep_btn_row.addWidget(gen_stripped_btn)
prep_btn_row.addWidget(open_stripped_btn)
prep_btn_row.addWidget(open_full_btn)
prep_layout.addLayout(prep_btn_row)
self.stripped_gds_status = QLabel("No stripped GDS generated yet")
self.stripped_gds_status.setFont(QFont("Monospace", 9))
prep_layout.addWidget(self.stripped_gds_status)
layout.addWidget(prep_group)
# Extraction source selector + action
action_row = QHBoxLayout()
src_label = QLabel("Extract from:")
src_label.setFixedWidth(110)
self.extraction_source_combo = QComboBox()
self.extraction_source_combo.addItems(["Full GDS", "Stripped GDS"])
self.extraction_source_combo.setCurrentIndex(0)
self.extraction_source_combo.model().item(1).setEnabled(False)
action_row.addWidget(src_label)
action_row.addWidget(self.extraction_source_combo)
self.extract_btn = QPushButton("Extract Pin List")
self.extract_btn.setMinimumHeight(40)
self.extract_btn.clicked.connect(self._extract_pin_list)
action_row.addWidget(self.extract_btn)
layout.addLayout(action_row)
layout.addStretch()
self.tabs.addTab(tab, "1. Extract Pins")
# =========================================================================
# Tab 2: Pin List Editor
# =========================================================================
def _build_pin_editor_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Toolbar
toolbar = QHBoxLayout()
load_btn = QPushButton("Load JSON")
load_btn.clicked.connect(self._load_pin_list_file)
save_btn = QPushButton("Save JSON")
save_btn.clicked.connect(self._save_pin_list_file)
add_btn = QPushButton("Add Row")
add_btn.clicked.connect(self._add_pin_row)
del_btn = QPushButton("Delete Row")
del_btn.clicked.connect(self._delete_pin_row)
toolbar.addWidget(load_btn)
toolbar.addWidget(save_btn)
toolbar.addWidget(add_btn)
toolbar.addWidget(del_btn)
toolbar.addStretch()
layout.addLayout(toolbar)
# Pin count and validation summary
self.pin_editor_summary = QLabel("No pin list loaded")
self.pin_editor_summary.setFont(QFont("Monospace", 10))
layout.addWidget(self.pin_editor_summary)
# Table
self.pin_editor_table = QTableWidget()
self.pin_editor_table.setColumnCount(7)
self.pin_editor_table.setHorizontalHeaderLabels([
"Name", "Type", "Side", "Pad Index", "Center X", "Center Y", "Size"
])
self.pin_editor_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.pin_editor_table.horizontalHeader().setStretchLastSection(True)
self.pin_editor_table.horizontalHeader().setSectionResizeMode(
QHeaderView.ResizeMode.ResizeToContents
)
self.pin_editor_table.itemChanged.connect(
lambda _item: self._update_pin_editor_summary()
)
layout.addWidget(self.pin_editor_table)
self.tabs.addTab(tab, "2. Pin List Editor")
# =========================================================================
# Tab 3: Symbol Designer
# =========================================================================
def _build_symbol_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Action buttons at top (always visible)
action_row = QHBoxLayout()
gen_sym_btn = QPushButton("Generate from Pin List")
gen_sym_btn.setMinimumHeight(36)
gen_sym_btn.clicked.connect(self._generate_symbol_from_pin_list)
self.export_sym_btn = QPushButton("Export .kicad_sym")
self.export_sym_btn.setMinimumHeight(36)
self.export_sym_btn.setEnabled(False)
self.export_sym_btn.clicked.connect(self._export_symbol)
action_row.addWidget(gen_sym_btn)
action_row.addWidget(self.export_sym_btn)
layout.addLayout(action_row)
splitter = QSplitter(Qt.Orientation.Horizontal)
# Left: pin table
left = QWidget()
left_layout = QVBoxLayout(left)
left_layout.setContentsMargins(0, 0, 0, 0)
tbl_label = QLabel("Pin Configuration")
tbl_label.setFont(QFont("Monospace", 11, QFont.Weight.Bold))
left_layout.addWidget(tbl_label)
self.sym_pin_table = QTableWidget()
self.sym_pin_table.setColumnCount(4)
self.sym_pin_table.setHorizontalHeaderLabels(["Name", "Number", "Side", "Type"])
self.sym_pin_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.sym_pin_table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
self.sym_pin_table.horizontalHeader().setStretchLastSection(True)
self.sym_pin_table.horizontalHeader().setSectionResizeMode(
QHeaderView.ResizeMode.ResizeToContents
)
left_layout.addWidget(self.sym_pin_table)
# Side buttons
btn_row = QHBoxLayout()
for label, side in [("Left", PinSide.LEFT), ("Right", PinSide.RIGHT),
("Top", PinSide.TOP), ("Bottom", PinSide.BOTTOM)]:
btn = QPushButton(label)
btn.clicked.connect(lambda checked, s=side: self._move_sym_pin_side(s))
btn_row.addWidget(btn)
left_layout.addLayout(btn_row)
splitter.addWidget(left)
# Right: symbol preview
right = QWidget()
right_layout = QVBoxLayout(right)
right_layout.setContentsMargins(0, 0, 0, 0)
prev_label = QLabel("Symbol Preview")
prev_label.setFont(QFont("Monospace", 11, QFont.Weight.Bold))
right_layout.addWidget(prev_label)
self.preview_widget = SymbolPreviewWidget()
right_layout.addWidget(self.preview_widget, stretch=1)
zoom_row = QHBoxLayout()
zoom_row.addWidget(QLabel("Zoom:"))
self.zoom_slider = QSlider(Qt.Orientation.Horizontal)
self.zoom_slider.setRange(20, 500)
self.zoom_slider.setValue(100)
self.zoom_slider.valueChanged.connect(
lambda v: self.preview_widget.set_zoom(v / 100.0)
)
zoom_row.addWidget(self.zoom_slider)
self.zoom_label = QLabel("100%")
self.zoom_slider.valueChanged.connect(
lambda v: self.zoom_label.setText(f"{v}%")
)
zoom_row.addWidget(self.zoom_label)
right_layout.addLayout(zoom_row)
# Sync wheel zoom back to slider
self.preview_widget.zoomChanged.connect(self._on_symbol_zoom_changed)
splitter.addWidget(right)
splitter.setSizes([400, 600])
layout.addWidget(splitter)
self.tabs.addTab(tab, "3. Symbol Designer")
# =========================================================================
# Tab 4: Footprint Generator
# =========================================================================
def _build_footprint_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
# Action row at top (always visible)
action_row = QHBoxLayout()
self.flip_chip_checkbox = QCheckBox("Flip-chip (mirror-X)")
self.flip_chip_checkbox.setFont(QFont("Monospace", 10))
self.flip_chip_checkbox.setToolTip(
"Mirror pad X coordinates for face-down die orientation.\n"
"Enable for dies mounted via Cu-pillar on interposer.\n"
"The footprint will show pads as seen from the interposer side."
)
self.flip_chip_checkbox.stateChanged.connect(self._on_flip_chip_toggled)
action_row.addWidget(self.flip_chip_checkbox)
action_row.addStretch()
export_fp_btn = QPushButton("Export .kicad_mod")
export_fp_btn.setMinimumHeight(36)
export_fp_btn.clicked.connect(self._export_footprint)
action_row.addWidget(export_fp_btn)
layout.addLayout(action_row)
splitter = QSplitter(Qt.Orientation.Horizontal)
# Left: layout preview
left = QWidget()
left_layout = QVBoxLayout(left)
left_layout.setContentsMargins(0, 0, 0, 0)
self.fp_view_label = QLabel("Pad Layout Preview -- Die View (original)")
self.fp_view_label.setFont(QFont("Monospace", 11, QFont.Weight.Bold))
left_layout.addWidget(self.fp_view_label)
self.layout_preview = LayoutPreviewWidget()
left_layout.addWidget(self.layout_preview, stretch=1)
fp_zoom_row = QHBoxLayout()
fp_zoom_row.addWidget(QLabel("Zoom:"))
self.fp_zoom_slider = QSlider(Qt.Orientation.Horizontal)
self.fp_zoom_slider.setRange(10, 1000)
self.fp_zoom_slider.setValue(100)
self.fp_zoom_slider.valueChanged.connect(
lambda v: self.layout_preview.set_zoom(v / 100.0)
)
fp_zoom_row.addWidget(self.fp_zoom_slider)
left_layout.addLayout(fp_zoom_row)
# Sync wheel zoom back to slider
self.layout_preview.zoomChanged.connect(self._on_fp_zoom_changed)
splitter.addWidget(left)
# Right: controls
right = QWidget()
right_layout = QVBoxLayout(right)
right_layout.setContentsMargins(0, 0, 0, 0)
ctrl_label = QLabel("Footprint Controls")
ctrl_label.setFont(QFont("Monospace", 11, QFont.Weight.Bold))
right_layout.addWidget(ctrl_label)
# Pad count
self.fp_pad_count_label = QLabel("Pads: --")
self.fp_pad_count_label.setFont(QFont("Monospace", 10))
right_layout.addWidget(self.fp_pad_count_label)
# Cross-reference: symbol thumbnail
xref_label = QLabel("Symbol (ref.)")
xref_label.setFont(QFont("Monospace", 10, QFont.Weight.Bold))
right_layout.addWidget(xref_label)
self.fp_xref_symbol_preview = SymbolPreviewWidget()
right_layout.addWidget(self.fp_xref_symbol_preview, stretch=1)
self.fp_xref_pin_count = QLabel("Pins: --")
self.fp_xref_pin_count.setFont(QFont("Monospace", 9))
right_layout.addWidget(self.fp_xref_pin_count)
self.fp_xref_mismatch = QLabel("")
self.fp_xref_mismatch.setFont(QFont("Monospace", 9))
self.fp_xref_mismatch.setStyleSheet(f"color: {COLORS['warning']};")
right_layout.addWidget(self.fp_xref_mismatch)
splitter.addWidget(right)
splitter.setSizes([600, 400])
layout.addWidget(splitter)
self.tabs.addTab(tab, "4. Footprint Generator")
# =========================================================================
# Tab 5: History
# =========================================================================
def _build_history_tab(self):
tab = QWidget()
layout = QVBoxLayout(tab)
self.history_table = QTableWidget()
self.history_table.setColumnCount(5)
self.history_table.setHorizontalHeaderLabels([
"Date", "Type", "Source", "Pins", "Output"
])
self.history_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.history_table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.history_table.horizontalHeader().setStretchLastSection(True)
self.history_table.horizontalHeader().setSectionResizeMode(
QHeaderView.ResizeMode.ResizeToContents
)
layout.addWidget(self.history_table)
btn_row = QHBoxLayout()
refresh_btn = QPushButton("Refresh")
refresh_btn.clicked.connect(self._refresh_history)
delete_btn = QPushButton("Delete Selected")
delete_btn.clicked.connect(self._delete_history_entry)
btn_row.addWidget(refresh_btn)
btn_row.addWidget(delete_btn)
btn_row.addStretch()
layout.addLayout(btn_row)
self.tabs.addTab(tab, "5. History")
# =========================================================================
# Menu bar + Project save/load
# =========================================================================
def _build_menu_bar(self):
file_menu = self.menuBar().addMenu("&File")
open_action = QAction("&Open Project...", self)
open_action.setShortcut("Ctrl+O")
open_action.triggered.connect(self._open_project)
file_menu.addAction(open_action)
save_action = QAction("&Save Project As...", self)
save_action.setShortcut("Ctrl+S")
save_action.triggered.connect(self._save_project)
file_menu.addAction(save_action)
def _select_combo_text(self, combo, text: str):
"""Select the item whose text matches `text`, if present."""
if not text:
return
idx = combo.findText(text)
if idx >= 0:
combo.setCurrentIndex(idx)
def _save_project(self):
"""Save the current session to a .g2kproj file.
Stores the GDS / LYP / stripped-GDS *paths* (the files are expected to
stay where they are), the layer selections and extraction source, and
embeds the edited pin list so the work survives across sessions.
"""
self._sync_editor_to_pin_list()
gds_path = self.gds_path_edit.text().strip()
if not gds_path:
self._log("Nothing to save yet -- select a GDS first", is_error=True)
return
project = {
"format": self.PROJECT_FORMAT,
"version": self.PROJECT_VERSION,
"gds_path": gds_path,
"lyp_path": self.lyp_path_edit.text().strip(),
"stripped_gds_path": self.stripped_gds_path or "",
"pad_layer": self.pad_layer_combo.currentText(),
"text_layer": self.text_layer_combo.currentText(),
"extraction_source": self.extraction_source_combo.currentIndex(),
"pin_list": None,
}
if self.current_pin_list is not None and self.current_pin_list.pins:
pl = self.current_pin_list
project["pin_list"] = {**pl.metadata,
"pins": [p.to_dict() for p in pl.pins]}
stem = ""
if self.current_pin_list is not None:
stem = self.current_pin_list.metadata.get("chiplet_name", "")
default_name = f"{stem or Path(gds_path).stem}.g2kproj"
path, _ = QFileDialog.getSaveFileName(
self, "Save Project",
str(self.DEFAULT_OUTPUT_DIR / default_name),
"GDS-to-KiCad Project (*.g2kproj);;JSON Files (*.json);;All Files (*)"
)
if not path:
self._log("Project save cancelled")
return
if not Path(path).suffix:
path = path.rstrip(".") + ".g2kproj"
try:
Path(path).parent.mkdir(parents=True, exist_ok=True)
with atomic_write(path) as f:
json.dump(project, f, indent=2)
self._log(f"Saved project: {path}")
except Exception as e:
self._log(f"Error saving project: {e}", is_error=True)
def _open_project(self):
path, _ = QFileDialog.getOpenFileName(
self, "Open Project",
str(self.DEFAULT_OUTPUT_DIR),
"GDS-to-KiCad Project (*.g2kproj);;JSON Files (*.json);;All Files (*)"
)
if not path:
return
try:
with open(path, 'r', encoding='utf-8') as f:
project = json.load(f)
except Exception as e:
self._log(f"Error reading project: {e}", is_error=True)
return
if not isinstance(project, dict) or project.get("format") != self.PROJECT_FORMAT:
self._log("Not a valid gds-to-kicad project file", is_error=True)
return
self._load_project(project, source=path)
def _load_project(self, project: dict, source: str = ""):
# Reset per-session state (mirrors _select_gds_file's resets).
self.current_pin_list = None
self.current_symbol = None
self.stripped_gds_path = None
self.pad_dicts = []
self.layout_preview.set_pads([])
self.fp_pad_count_label.setText("Pads: --")
self.fp_xref_pin_count.setText("Pins: --")
self.fp_xref_mismatch.setText("")
# Clear the pin editor so no rows from a previously open project linger
# when the incoming project has no embedded pin list.
self.pin_editor_table.setRowCount(0)
self.pin_editor_summary.setText("No pin list loaded")
self.stripped_gds_status.setText("No stripped GDS generated yet")
self.stripped_gds_status.setToolTip("")
self.extraction_source_combo.setCurrentIndex(0)
self.extraction_source_combo.model().item(1).setEnabled(False)
gds_path = project.get("gds_path", "") or ""
lyp_path = project.get("lyp_path", "") or ""
stripped = project.get("stripped_gds_path", "") or ""
self.gds_path_edit.setText(gds_path)
if gds_path and not Path(gds_path).exists():
self._log(f"Warning: GDS not found at {gds_path}", is_error=True)
# Load the LYP first so the layer combos are populated before we
# restore the saved selections.
self.lyp_path_edit.setText(lyp_path)
self.lyp_parser = None
if lyp_path and Path(lyp_path).exists():
self._load_layers_from_lyp(lyp_path)
elif lyp_path:
self._log(f"Warning: LYP not found at {lyp_path}", is_error=True)
if self.lyp_parser is not None:
self._select_combo_text(self.pad_layer_combo, project.get("pad_layer", ""))
self._select_combo_text(self.text_layer_combo, project.get("text_layer", ""))
# Restore stripped GDS (path only; the file is expected to still exist).
if stripped:
self.stripped_gds_path = stripped
if Path(stripped).exists():
self.stripped_gds_status.setText(f"Stripped GDS: {Path(stripped).name}")
self.stripped_gds_status.setToolTip(stripped)
self.extraction_source_combo.model().item(1).setEnabled(True)
else:
self._log(f"Warning: stripped GDS not found at {stripped}", is_error=True)
# Restore extraction source only if the stripped option is valid now.
if (project.get("extraction_source", 0) == 1
and self.extraction_source_combo.model().item(1).isEnabled()):
self.extraction_source_combo.setCurrentIndex(1)
else:
self.extraction_source_combo.setCurrentIndex(0)
# Restore the embedded pin list (this repopulates the previews and
# cross-references via _build_pad_dicts_from_pin_list).
pl_data = project.get("pin_list")
if isinstance(pl_data, dict):
metadata = {k: v for k, v in pl_data.items() if k != "pins"}
pins = [PinEntry.from_dict(p) for p in pl_data.get("pins", [])]
self.current_pin_list = PinList(pins=pins, metadata=metadata)
self._load_pin_list_into_editor()
self._build_pad_dicts_from_pin_list()
self.scan_btn.setEnabled(
bool(self.lyp_parser and gds_path and Path(gds_path).exists())
)
n = len(self.current_pin_list) if self.current_pin_list else 0
name = Path(source).name if source else "project"
self._log(f"Opened project: {name} ({n} pins)")
self.tabs.setCurrentIndex(0)
# =========================================================================
# File Selectors (Tab 1)
# =========================================================================
def _select_gds_file(self):
path, _ = QFileDialog.getOpenFileName(
self, "Select GDSII File",
str(Path.cwd()),
"GDSII Files (*.gds *.GDS);;All Files (*)"
)
if path:
self.gds_path_edit.setText(path)
self._log(f"Selected GDS: {Path(path).name}")
self.scan_btn.setEnabled(bool(self.lyp_parser))
# Reset state from previous GDS
self.current_pin_list = None
self.current_symbol = None
self.stripped_gds_path = None
self.pad_dicts = []
# Clear stale preview / footprint labels from the previous GDS
self.layout_preview.set_pads([])
self.fp_pad_count_label.setText("Pads: --")
self.fp_xref_pin_count.setText("Pins: --")
self.fp_xref_mismatch.setText("")
# Reset extraction source to Full GDS and re-disable Stripped GDS
self.extraction_source_combo.setCurrentIndex(0)
self.extraction_source_combo.model().item(1).setEnabled(False)
def _select_lyp_file(self):
path, _ = QFileDialog.getOpenFileName(
self, "Select Layer Properties File",
str(Path(__file__).parent / "pdks"),
"LYP Files (*.lyp);;All Files (*)"
)
if path:
self.lyp_path_edit.setText(path)
self._load_layers_from_lyp(path)
def _load_layers_from_lyp(self, lyp_path: str):
try:
self.lyp_parser = LYPParser(lyp_path)
display_names = self.lyp_parser.get_layer_display_names()
self.pad_layer_combo.setEnabled(True)
self.pad_layer_combo.setItems(display_names)
self.text_layer_combo.setEnabled(True)
text_items = ["(Auto-detect)"] + display_names
self.text_layer_combo.setItems(text_items)
self.text_layer_combo.setCurrentIndex(0)
self._log(f"Loaded {len(display_names)} layers from {Path(lyp_path).name}")
gds_path = self.gds_path_edit.text().strip()
self.scan_btn.setEnabled(bool(gds_path and Path(gds_path).exists()))
for i, name in enumerate(display_names):
if 'TopMetal2.drawing' in name:
self.pad_layer_combo.setCurrentIndex(i)
break
except Exception as e:
self._log(f"Error loading LYP: {e}", is_error=True)
self.lyp_parser = None
# =========================================================================
# Scan GDS (Tab 1)
# =========================================================================
def _scan_gds_layers(self):
gds_path = self.gds_path_edit.text().strip()
if not gds_path or not Path(gds_path).exists():
self._log("Select a valid GDS file first", is_error=True)
return
self._log(f"Scanning {Path(gds_path).name}...")
QApplication.processEvents()
try:
result = PinExtractor.scan_gds_layers(gds_path, self.lyp_parser)
for c in result['pad_candidates'][:5]:
name = c['name'] or f"{c['layer_num']}/{c['datatype']}"
total = c['boxes'] + c['polygons']
self._log(f" Pad: {name} ({total} shapes)")
for c in result['text_candidates'][:5]:
name = c['name'] or f"{c['layer_num']}/{c['datatype']}"
self._log(f" Text: {name} ({c['texts']} texts)")
# Auto-select
suggested_pad = result['suggested_pad_layer']
if suggested_pad:
display_names = [self.pad_layer_combo.itemText(i)
for i in range(self.pad_layer_combo.count())]
for i, d in enumerate(display_names):
if d.startswith(suggested_pad + ' (') or d == suggested_pad:
self.pad_layer_combo.setCurrentIndex(i)
break
self._log(f"Suggested pad layer: {suggested_pad}")
suggested_text = result['suggested_text_layers']
if suggested_text:
text_items = [self.text_layer_combo.itemText(i)
for i in range(self.text_layer_combo.count())]
for i, d in enumerate(text_items):
if d.startswith(suggested_text[0] + ' (') or d == suggested_text[0]:
self.text_layer_combo.setCurrentIndex(i)
break
except Exception as e:
self._log(f"Scan error: {e}", is_error=True)
# =========================================================================
# Extract Pin List (Tab 1 -> Tab 2)
# =========================================================================
def _extract_pin_list(self):
gds_path = self.gds_path_edit.text().strip()
lyp_path = self.lyp_path_edit.text().strip()
if not gds_path or not Path(gds_path).exists():
self._log("Invalid GDS path", is_error=True)
return
if not self.lyp_parser:
self._log("Load a LYP file first", is_error=True)
return
pad_display = self.pad_layer_combo.getSelectedItem()
pad_layer_name = pad_display.split(' (')[0] if ' (' in pad_display else pad_display
if not pad_layer_name:
self._log("Select a pad layer", is_error=True)
return
text_display = self.text_layer_combo.getSelectedItem()
text_layer_names = None
if text_display and text_display != "(Auto-detect)":
text_name = text_display.split(' (')[0] if ' (' in text_display else text_display
text_layer_names = [text_name]
# Determine extraction source from user selection
use_stripped = self.extraction_source_combo.currentIndex() == 1
if use_stripped and self.stripped_gds_path and Path(self.stripped_gds_path).exists():
source_gds = self.stripped_gds_path
else:
source_gds = gds_path
if use_stripped:
self._log("Stripped GDS not found, falling back to full GDS", is_error=True)
self._log(f"Extracting pins from: {Path(source_gds).name}")
QApplication.processEvents()
try:
import io, contextlib
extractor = PinExtractor(self.lyp_parser)
f = io.StringIO()
with contextlib.redirect_stdout(f):
pads, cell_name = extractor.extract_named_pads(
source_gds, pad_layer_name,
text_layer_names=text_layer_names,
)
for line in f.getvalue().strip().split('\n'):
if line.strip():
self._log(f" {line.strip()}")
pin_list = PinList.from_extracted_pads(
pads,
chiplet_name=cell_name,
gds_source=Path(source_gds).name,
lyp_file=Path(lyp_path).name,
pad_layer=pad_layer_name,
text_layers=text_layer_names,
)
self.current_pin_list = pin_list
self._load_pin_list_into_editor()
self._build_pad_dicts_from_pin_list()
self._log(f"Extracted {len(pin_list)} pins.")
except Exception as e:
self._log(f"Extraction error: {e}", is_error=True)
return
# Extraction succeeded: offer to save the pin list now, letting the user
# pick the destination folder and file name. Done outside the try above
# so a save error is not misreported as an extraction error.
if self._write_pin_list_dialog("Save Extracted Pin List") is None:
self._log("Pin list not saved -- use 'Save JSON' in the editor when ready")
self._log("Switch to Pin List Editor to review.")
self.tabs.setCurrentIndex(1)
# =========================================================================
# Pin List Editor Operations (Tab 2)
# =========================================================================
def _load_pin_list_into_editor(self):
if not self.current_pin_list:
return
pl = self.current_pin_list
self.pin_editor_table.blockSignals(True)
self.pin_editor_table.setRowCount(len(pl.pins))
for row, pin in enumerate(pl.pins):
# Name (editable)
name_item = QTableWidgetItem(pin.name)
self.pin_editor_table.setItem(row, 0, name_item)
# Type combo
type_combo = QComboBox()
type_combo.setStyleSheet(TABLE_COMBO_STYLE)
type_combo.addItems(VALID_PIN_TYPES)
type_combo.setCurrentText(pin.type)
self.pin_editor_table.setCellWidget(row, 1, type_combo)
# Side combo
side_combo = QComboBox()
side_combo.setStyleSheet(TABLE_COMBO_STYLE)
side_combo.addItems(VALID_PIN_SIDES)
side_combo.setCurrentText(pin.side)
self.pin_editor_table.setCellWidget(row, 2, side_combo)
# Pad index (read-only)
idx_item = QTableWidgetItem(str(pin.pad_index))
idx_item.setFlags(idx_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
self.pin_editor_table.setItem(row, 3, idx_item)
# Center X (read-only)
cx_item = QTableWidgetItem(f"{pin.center_x_dbu:.0f}")