1use crate::bake::{
13 BakeLayerReport, ByteEdit, PcbCleanOptions, PcbCleanReport, UserLayerCollision,
14 VIRTUAL_GROUP_PREFIX, VdocLayerPreset, apply_byte_edits, arc_midpoint,
15 collect_footprint_clean_edits, default_kicad_layer_for_virtual_preset, deterministic_uuid,
16 nm_to_kicad_mm,
17};
18use crate::geom::{
19 AreaShape, CoordNm, FabLayerItems, FabStroke, LayerSide, Placement2D, StrokeKind, StrokePath,
20};
21use crate::gerber::shape_to_board_polygon;
22use crate::virtual_layers::{build_virtual_layer, resolve_virtual_layer_key};
23use crate::{FabError, FabViewData};
24use kicad_monkey_core::pcb::{PcbFootprint, PcbLimits, PcbView};
25use kicad_monkey_core::sexpr::{Sexp, build_with_limit};
26use kicad_monkey_core::{FootprintLimits, FootprintView};
27use serde::{Deserialize, Serialize};
28use std::collections::{BTreeMap, HashSet};
29use std::fmt::Write as _;
30
31pub const DEFAULT_FOOTPRINT_VIRTUAL_LAYERS: [&str; 6] = [
33 "ASSEMBLY_OUTLINES_TOP",
34 "PIN1_TOP",
35 "DIODES_TOP",
36 "CAPACITORS_TOP",
37 "INDUCTORS_TOP",
38 "RESISTORS_TOP",
39];
40
41pub const FOOTPRINT_SUPPORTED_VIRTUAL_LAYERS: [&str; 7] = [
43 "ASSEMBLY_OUTLINES_TOP",
44 "PIN1_TOP",
45 "DIODES_TOP",
46 "CAPACITORS_TOP",
47 "INDUCTORS_TOP",
48 "RESISTORS_TOP",
49 "PAD_LABELS_TOP",
50];
51
52const TRANSIENT_PCB_PREFIX: &str = "\
55(kicad_pcb\n\
56\t(version 20241229)\n\
57\t(generator \"kicad_monkey\")\n\
58\t(general (thickness 1.6))\n\
59\t(layers\n\
60\t\t(0 \"F.Cu\" signal)\n\
61\t\t(31 \"B.Cu\" signal)\n\
62\t\t(32 \"B.Adhes\" user)\n\
63\t\t(33 \"F.Adhes\" user)\n\
64\t\t(34 \"B.Paste\" user)\n\
65\t\t(35 \"F.Paste\" user)\n\
66\t\t(36 \"B.SilkS\" user)\n\
67\t\t(37 \"F.SilkS\" user)\n\
68\t\t(38 \"B.Mask\" user)\n\
69\t\t(39 \"F.Mask\" user)\n\
70\t\t(44 \"Edge.Cuts\" user)\n\
71\t\t(46 \"B.CrtYd\" user)\n\
72\t\t(47 \"F.CrtYd\" user)\n\
73\t\t(48 \"B.Fab\" user)\n\
74\t\t(49 \"F.Fab\" user)\n\
75\t)\n";
76
77#[must_use]
81pub fn resolve_footprint_virtual_layer_key(raw: &str) -> Option<&'static str> {
82 let norm = raw.trim().to_ascii_uppercase().replace(['-', ' '], "_");
83 match norm.as_str() {
84 "ASSEMBLY_OUTLINES" | "OUTLINES" | "FAB" => return Some("ASSEMBLY_OUTLINES_TOP"),
85 "PIN1" | "PIN_1" | "POLARITY" => return Some("PIN1_TOP"),
86 "DIODES" | "DIODE" => return Some("DIODES_TOP"),
87 "CAPACITORS" | "CAPACITOR" | "CAPS" => return Some("CAPACITORS_TOP"),
88 "INDUCTORS" | "INDUCTOR" => return Some("INDUCTORS_TOP"),
89 "RESISTORS" | "RESISTOR" => return Some("RESISTORS_TOP"),
90 "PAD_LABELS" => return Some("PAD_LABELS_TOP"),
91 _ => {}
92 }
93 let canon = resolve_virtual_layer_key(&norm)?;
94 FOOTPRINT_SUPPORTED_VIRTUAL_LAYERS
95 .contains(&canon)
96 .then_some(canon)
97}
98
99#[derive(Clone, Debug)]
101pub struct BakeFootprintVirtualLayersOptions {
102 pub layer_map: Vec<(String, String)>,
104 pub force: bool,
105}
106
107impl Default for BakeFootprintVirtualLayersOptions {
108 fn default() -> Self {
109 Self {
110 layer_map: DEFAULT_FOOTPRINT_VIRTUAL_LAYERS
111 .iter()
112 .filter_map(|&k| {
113 default_kicad_layer_for_virtual_preset(k, VdocLayerPreset::Fab)
114 .map(|l| (k.to_owned(), l.to_owned()))
115 })
116 .collect(),
117 force: false,
118 }
119 }
120}
121
122#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
124pub struct BakeFootprintVirtualLayersReport {
125 pub footprint_name: String,
126 pub synthetic_designator: String,
127 pub layers: Vec<BakeLayerReport>,
128 pub collisions: Vec<UserLayerCollision>,
129}
130
131impl BakeFootprintVirtualLayersReport {
132 #[must_use]
134 pub fn total_items_written(&self) -> usize {
135 self.layers.iter().map(|l| l.items_written).sum()
136 }
137}
138
139fn wrap_footprint_as_transient_pcb(fp_source: &str) -> Result<String, FabError> {
140 FootprintView::parse(fp_source, FootprintLimits::default())
142 .map_err(|e| FabError::Parse(e.to_string()))?;
143 let mut wrapped = String::with_capacity(TRANSIENT_PCB_PREFIX.len() + fp_source.len() + 4);
144 wrapped.push_str(TRANSIENT_PCB_PREFIX);
145 wrapped.push_str(fp_source);
146 if !fp_source.ends_with('\n') {
147 wrapped.push('\n');
148 }
149 wrapped.push_str(")\n");
150 Ok(wrapped)
151}
152
153pub fn clean_footprint_doc_layers_source(
156 source: &str,
157 opts: &PcbCleanOptions,
158) -> Result<(String, PcbCleanReport), FabError> {
159 let wrapped = wrap_footprint_as_transient_pcb(source)?;
160 let view = PcbView::parse(&wrapped, PcbLimits::default())
161 .map_err(|e| FabError::Parse(e.to_string()))?;
162 let mut report = PcbCleanReport::default();
163 let mut wrapped_edits: Vec<ByteEdit> = Vec::new();
164 collect_footprint_clean_edits(&wrapped, &view, opts, &mut wrapped_edits, &mut report)?;
165
166 let prefix_len = TRANSIENT_PCB_PREFIX.len();
167 let source_len = source.len();
168 let mut edits = Vec::with_capacity(wrapped_edits.len());
169 for mut edit in wrapped_edits {
170 if edit.start >= prefix_len && edit.end <= prefix_len + source_len {
171 edit.start -= prefix_len;
172 edit.end -= prefix_len;
173 edits.push(edit);
174 }
175 }
176 Ok((apply_byte_edits(source, edits), report))
177}
178
179pub fn detect_footprint_layer_collisions(
181 source: &str,
182 layer_map: &[(String, String)],
183) -> Result<Vec<UserLayerCollision>, FabError> {
184 let wrapped = wrap_footprint_as_transient_pcb(source)?;
185 let view = PcbView::parse(&wrapped, PcbLimits::default())
186 .map_err(|e| FabError::Parse(e.to_string()))?;
187 let mut counts: BTreeMap<String, usize> = BTreeMap::new();
188
189 for fg in view.footprint_graphics() {
190 let fg = fg.map_err(|e| FabError::Parse(e.to_string()))?;
191 if let Some(layer) = fg.graphic.layer.as_deref() {
192 *counts.entry(layer.to_owned()).or_insert(0) += 1;
193 }
194 if let Some(layers) = fg.graphic.layers.as_ref() {
195 for layer in layers {
196 *counts.entry(layer.clone()).or_insert(0) += 1;
197 }
198 }
199 }
200 for tb in view.footprint_text_boxes() {
201 let tb = tb.map_err(|e| FabError::Parse(e.to_string()))?;
202 if !tb.layer.is_empty() {
203 *counts.entry(tb.layer).or_insert(0) += 1;
204 }
205 }
206 for ft in view.footprint_texts() {
207 let ft = ft.map_err(|e| FabError::Parse(e.to_string()))?;
208 if !matches!(ft.kind.as_str(), "reference" | "value") && !ft.layer.is_empty() {
209 *counts.entry(ft.layer).or_insert(0) += 1;
210 }
211 }
212
213 let mut collisions = Vec::new();
214 for (vkey, klayer) in layer_map {
215 if let Some(&count) = counts.get(klayer)
216 && count > 0
217 {
218 collisions.push(UserLayerCollision {
219 virtual_key: vkey.clone(),
220 kicad_layer: klayer.clone(),
221 existing_count: count,
222 });
223 }
224 }
225 Ok(collisions)
226}
227
228pub fn build_footprint_fab_view(
231 source: &str,
232 library_name: Option<&str>,
233 synthetic_designator_override: Option<&str>,
234 extra_parameters: &BTreeMap<String, String>,
235) -> Result<(FabViewData, String, String), FabError> {
236 let wrapped = wrap_footprint_as_transient_pcb(source)?;
237 let pcb_view = PcbView::parse(&wrapped, PcbLimits::default())
238 .map_err(|e| FabError::Parse(e.to_string()))?;
239 let fp_meta = pcb_view
240 .footprints()
241 .next()
242 .transpose()
243 .map_err(|e| FabError::Parse(e.to_string()))?
244 .ok_or_else(|| FabError::Parse("missing footprint in standalone file".to_owned()))?;
245 let fp_name = fp_meta.library_link.clone();
246 let (legacy_ref, legacy_val) = extract_legacy_primary_texts(&pcb_view)?;
247 let mut fab_view = FabViewData::from_pcb_view(&pcb_view, &fp_name)?;
248
249 let unique_pad_count = fab_view.components.first().map_or(0, |c| c.pins.len());
250 let effective_ref = fp_meta
251 .reference
252 .as_deref()
253 .filter(|s| !s.trim().is_empty())
254 .or(legacy_ref.as_deref());
255 let synthetic_designator = infer_synthetic_designator(
256 &fp_meta,
257 effective_ref,
258 unique_pad_count,
259 library_name,
260 synthetic_designator_override,
261 );
262
263 if let Some(comp) = fab_view.components.first_mut() {
264 comp.designator = synthetic_designator.clone();
265 comp.fitted = true;
268 comp.side = LayerSide::Top;
269 if comp.value.trim().is_empty()
270 && let Some(val) = legacy_val
271 {
272 comp.value = val;
273 }
274 normalize_component_metadata(comp, &fp_meta, library_name, extra_parameters);
275 }
276 let top_has_lands = fab_view
279 .layers_items
280 .get("TOP")
281 .is_some_and(|i| !i.lands.is_empty());
282 if !top_has_lands
283 && let Some(bot_lands) = fab_view
284 .layers_items
285 .get("BOTTOM")
286 .filter(|i| !i.lands.is_empty())
287 .map(|i| i.lands.clone())
288 {
289 fab_view
290 .layers_items
291 .entry("TOP".to_owned())
292 .or_default()
293 .lands
294 .extend(bot_lands);
295 }
296 Ok((fab_view, fp_name, synthetic_designator))
297}
298
299fn extract_legacy_primary_texts(
300 view: &PcbView<'_>,
301) -> Result<(Option<String>, Option<String>), FabError> {
302 let mut ref_text = None;
303 let mut val_text = None;
304 for ft in view.footprint_texts() {
305 let ft = ft.map_err(|e| FabError::Parse(e.to_string()))?;
306 let text = ft.text.trim();
307 if text.is_empty() {
308 continue;
309 }
310 if ft.kind == "reference" && ref_text.is_none() {
311 ref_text = Some(text.to_owned());
312 } else if ft.kind == "value" && val_text.is_none() {
313 val_text = Some(text.to_owned());
314 }
315 }
316 Ok((ref_text, val_text))
317}
318
319fn has_param_ci(params: &BTreeMap<String, String>, key: &str) -> bool {
320 params
321 .iter()
322 .any(|(k, v)| k.eq_ignore_ascii_case(key) && !v.trim().is_empty())
323}
324
325fn set_param_ci(params: &mut BTreeMap<String, String>, key: &str, value: String) {
326 let existing: Vec<String> = params
327 .keys()
328 .filter(|k| k.eq_ignore_ascii_case(key))
329 .cloned()
330 .collect();
331 for old in existing {
332 params.remove(&old);
333 }
334 params.insert(key.to_owned(), value);
335}
336
337fn normalize_component_metadata(
338 comp: &mut crate::geom::FabComponent,
339 fp_meta: &PcbFootprint,
340 library_name: Option<&str>,
341 extra_parameters: &BTreeMap<String, String>,
342) {
343 if let Some(lib) = library_name.filter(|s| !s.trim().is_empty())
344 && !comp.footprint.contains(':')
345 {
346 comp.footprint = format!("{}:{}", lib.trim(), fp_meta.library_link);
347 }
348 if let Some(ki_desc) = comp
349 .parameters
350 .iter()
351 .find(|(k, v)| k.eq_ignore_ascii_case("ki_description") && !v.trim().is_empty())
352 .map(|(_, v)| v.trim().to_owned())
353 {
354 if comp.description.trim().is_empty() {
355 comp.description = ki_desc.clone();
356 }
357 if !has_param_ci(&comp.parameters, "Description") {
358 comp.parameters.insert("Description".to_owned(), ki_desc);
359 }
360 }
361 if !fp_meta.description.trim().is_empty() {
362 let descr = fp_meta.description.trim().to_owned();
363 if comp.description.trim().is_empty() {
364 comp.description = descr.clone();
365 }
366 if !has_param_ci(&comp.parameters, "Description") {
367 comp.parameters.insert("Description".to_owned(), descr);
368 }
369 }
370 if !fp_meta.tags.trim().is_empty() && !has_param_ci(&comp.parameters, "Keywords") {
371 comp.parameters
372 .insert("Keywords".to_owned(), fp_meta.tags.trim().to_owned());
373 }
374 for (k, v) in extra_parameters {
375 if !k.trim().is_empty() && !v.trim().is_empty() {
376 set_param_ci(&mut comp.parameters, k.trim(), v.trim().to_owned());
377 }
378 }
379}
380
381#[must_use]
385pub fn infer_synthetic_designator(
386 fp: &PcbFootprint,
387 raw_reference: Option<&str>,
388 unique_electrical_pads: usize,
389 library_name: Option<&str>,
390 override_ref: Option<&str>,
391) -> String {
392 if let Some(ov) = override_ref.map(str::trim).filter(|s| !s.is_empty()) {
393 return ov.to_owned();
394 }
395 if let Some(ref_val) = raw_reference.map(str::trim).filter(|s| !s.is_empty()) {
396 if let Some(prefix) = parse_placeholder_prefix(ref_val) {
397 if !matches!(prefix.as_str(), "REF" | "VAL" | "FP" | "PART") {
398 return format!("{prefix}1");
399 }
400 } else if !ref_val.contains('*')
401 && !ref_val.contains('?')
402 && !ref_val.to_ascii_uppercase().starts_with("REF")
403 {
404 return ref_val.to_owned();
405 }
406 }
407
408 let name = fp.library_link.trim();
409 let name_up = name.to_ascii_uppercase();
410 let lib_up = library_name.unwrap_or("").trim().to_ascii_uppercase();
411 let descr_up = fp.description.to_ascii_uppercase();
412 let tags_up = fp.tags.to_ascii_uppercase();
413 let blob_up = format!("{name_up} {lib_up} {descr_up} {tags_up}");
414
415 if name_up.starts_with("FIDUCIAL") || name_up.starts_with("FID_") || name_up.starts_with("FID-")
416 {
417 return "FID1".to_owned();
418 }
419 if name_up.starts_with("MOUNTINGHOLE")
420 || name_up.starts_with("MH_")
421 || name_up.starts_with("MH-")
422 {
423 return "MH1".to_owned();
424 }
425 if is_testpoint_hint(&name_up, &lib_up, &descr_up, unique_electrical_pads) {
426 return "TP1".to_owned();
427 }
428 if is_connector_name_or_lib(&name_up, &lib_up) {
429 return "J1".to_owned();
430 }
431 if unique_electrical_pads == 2
432 && let Some(two_pad) = classify_two_pad_footprint(&name_up, &lib_up, &blob_up)
433 {
434 return two_pad.to_owned();
435 }
436 if name_up.starts_with("Q_") || name_up.starts_with("Q-") || lib_up.contains("TRANSISTOR") {
437 return "Q1".to_owned();
438 }
439 if unique_electrical_pads == 1 {
440 return "TP1".to_owned();
441 }
442 "U1".to_owned()
443}
444
445fn parse_placeholder_prefix(raw: &str) -> Option<String> {
446 let trimmed = raw.trim();
447 let prefix_len = trimmed
448 .bytes()
449 .take_while(|b| b.is_ascii_alphabetic())
450 .count();
451 if prefix_len == 0 || prefix_len == trimmed.len() {
452 return None;
453 }
454 let suffix = &trimmed[prefix_len..];
455 if suffix.bytes().all(|b| b == b'*' || b == b'?') {
456 Some(trimmed[..prefix_len].to_ascii_uppercase())
457 } else {
458 None
459 }
460}
461
462fn has_ascii_word(haystack_up: &str, words: &[&str]) -> bool {
463 haystack_up
464 .split(|c: char| !c.is_ascii_alphanumeric())
465 .any(|tok| words.contains(&tok))
466}
467
468fn is_testpoint_hint(name_up: &str, lib_up: &str, descr_up: &str, pads: usize) -> bool {
469 name_up.starts_with("TP_")
470 || name_up.starts_with("TP-")
471 || name_up.starts_with("TESTPOINT")
472 || lib_up.contains("TESTPOINT")
473 || (pads == 1 && (descr_up.contains("TEST POINT") || descr_up.contains("TESTPOINT")))
474}
475
476fn is_connector_name_or_lib(name_up: &str, lib_up: &str) -> bool {
477 const NAME_PREFIXES: &[&str] = &[
478 "J_",
479 "J-",
480 "CONN_",
481 "CONN-",
482 "PINHEADER",
483 "PINSOCKET",
484 "TERMINALBLOCK",
485 "USB_",
486 "USB-",
487 "D-SUB",
488 "D_SUB",
489 "DSUB",
490 "JST_",
491 "MOLEX_",
492 "HEADER_",
493 ];
494 name_up == "CONN"
495 || NAME_PREFIXES.iter().any(|p| name_up.starts_with(p))
496 || lib_up.contains("CONNECTOR")
497 || lib_up.contains("HEADER")
498}
499
500fn is_connector_word_blob(blob_up: &str) -> bool {
501 has_ascii_word(
502 blob_up,
503 &[
504 "CONNECTOR",
505 "HEADER",
506 "SOCKET",
507 "RECEPTACLE",
508 "TERMINAL",
509 "PLUG",
510 "JACK",
511 "USB",
512 "DSUB",
513 ],
514 )
515}
516
517fn classify_two_pad_footprint(name_up: &str, lib_up: &str, blob_up: &str) -> Option<&'static str> {
518 if name_up.starts_with("LED_") || name_up.starts_with("LED-") || lib_up.starts_with("LED") {
519 return Some("LED1");
520 }
521 if name_up.starts_with("D_")
522 || name_up.starts_with("D-")
523 || name_up.starts_with("DIODE_")
524 || lib_up.starts_with("DIODE")
525 {
526 return Some("D1");
527 }
528 if name_up.starts_with("CP_")
529 || name_up.starts_with("CP-")
530 || name_up.starts_with("C_")
531 || name_up.starts_with("C-")
532 || name_up.starts_with("CAP_")
533 || lib_up.starts_with("CAPACITOR")
534 {
535 return Some("C1");
536 }
537 if name_up.starts_with("FB_")
538 || name_up.starts_with("FB-")
539 || name_up.starts_with("L_")
540 || name_up.starts_with("L-")
541 || name_up.starts_with("IND_")
542 || lib_up.starts_with("INDUCTOR")
543 || lib_up.contains("FERRITE")
544 {
545 return Some("L1");
546 }
547 if name_up.starts_with("R_")
548 || name_up.starts_with("R-")
549 || name_up.starts_with("RES_")
550 || lib_up.starts_with("RESISTOR")
551 {
552 return Some("R1");
553 }
554 if has_ascii_word(blob_up, &["LED"]) && !is_connector_word_blob(blob_up) {
555 return Some("LED1");
556 }
557 if has_ascii_word(blob_up, &["DIODE", "SCHOTTKY", "ZENER", "TVS"])
558 && !is_connector_word_blob(blob_up)
559 {
560 return Some("D1");
561 }
562 if has_ascii_word(blob_up, &["CAPACITOR", "TANTALUM", "ELECTROLYTIC"]) {
563 return Some("C1");
564 }
565 if has_ascii_word(blob_up, &["INDUCTOR", "CHOKE"]) {
566 return Some("L1");
567 }
568 if has_ascii_word(blob_up, &["RESISTOR"]) {
569 return Some("R1");
570 }
571 if is_connector_word_blob(blob_up) {
572 return Some("J1");
573 }
574 None
575}
576
577#[must_use]
580pub fn build_footprint_pad_outline(view: &FabViewData) -> FabLayerItems {
581 let mut out = FabLayerItems::default();
582 let Some(comp) = view.components.first() else {
583 return out;
584 };
585 let mut min_x = i64::MAX;
586 let mut min_y = i64::MAX;
587 let mut max_x = i64::MIN;
588 let mut max_y = i64::MIN;
589 let mut single_disk: Option<(CoordNm, i64)> = None;
590 let mut land_count = 0usize;
591
592 for key in ["TOP", "BOTTOM"] {
593 let Some(items) = view.layers_items.get(key) else {
594 continue;
595 };
596 for land in &items.lands {
597 if land.component.as_deref() != Some(comp.id.as_str()) {
598 continue;
599 }
600 land_count += 1;
601 if let AreaShape::Disk { radius } = land.shape {
602 single_disk = Some((CoordNm::new(land.placement.tx, land.placement.ty), radius));
603 }
604 for pt in shape_to_board_polygon(&land.shape, land.placement) {
605 min_x = min_x.min(pt.x);
606 min_y = min_y.min(pt.y);
607 max_x = max_x.max(pt.x);
608 max_y = max_y.max(pt.y);
609 }
610 }
611 }
612 for hole in &view.holes {
613 if hole.component.as_deref() != Some(comp.id.as_str()) {
614 continue;
615 }
616 let r = hole.diameter / 2;
617 min_x = min_x.min(hole.center.x - r);
618 min_y = min_y.min(hole.center.y - r);
619 max_x = max_x.max(hole.center.x + r);
620 max_y = max_y.max(hole.center.y + r);
621 }
622
623 if land_count == 1
624 && let Some((center, radius)) = single_disk
625 && radius > 1
626 {
627 out.strokes.push(FabStroke {
628 kind: StrokeKind::Virtual,
629 path: StrokePath::FullCircle { center, radius },
630 width: 100_000,
631 net: None,
632 component: Some(comp.id.clone()),
633 source: None,
634 });
635 return out;
636 }
637
638 if min_x < max_x && min_y < max_y {
639 let corners = [
640 CoordNm::new(min_x, min_y),
641 CoordNm::new(max_x, min_y),
642 CoordNm::new(max_x, max_y),
643 CoordNm::new(min_x, max_y),
644 ];
645 for i in 0..4 {
646 out.strokes.push(FabStroke {
647 kind: StrokeKind::Virtual,
648 path: StrokePath::Line {
649 start: corners[i],
650 end: corners[(i + 1) % 4],
651 },
652 width: 100_000,
653 net: None,
654 component: Some(comp.id.clone()),
655 source: None,
656 });
657 }
658 }
659 out
660}
661
662fn format_kicad_layer_quoted(klayer: &str) -> Result<String, FabError> {
663 let trimmed = klayer.trim();
664 if trimmed.is_empty() || trimmed.chars().any(|c| c.is_control()) {
665 return Err(FabError::Parse(format!(
666 "invalid KiCad layer name: {klayer:?}"
667 )));
668 }
669 build_with_limit(&Sexp::Quoted(trimmed.to_owned()), 1024)
670 .map_err(|e| FabError::Parse(e.to_string()))
671}
672
673fn splice_before_footprint_root_close(source: &str, insertion: &str) -> Result<String, FabError> {
674 if insertion.is_empty() {
675 return Ok(source.to_owned());
676 }
677 let view = FootprintView::parse(source, FootprintLimits::default())
678 .map_err(|e| FabError::Parse(e.to_string()))?;
679 let meta = view
680 .metadata()
681 .map_err(|e| FabError::Parse(e.to_string()))?;
682 let root_slice = source
683 .get(meta.source_range.clone())
684 .ok_or_else(|| FabError::Parse("footprint root span out of bounds".to_owned()))?;
685 let rel_close = root_slice
686 .rfind(')')
687 .ok_or_else(|| FabError::Parse("missing closing ')' on footprint root".to_owned()))?;
688 let close_idx = meta.source_range.start + rel_close;
689 let mut out = String::with_capacity(source.len() + insertion.len() + 4);
690 out.push_str(&source[..close_idx]);
691 out.push_str(insertion);
692 if !insertion.ends_with('\n') {
693 out.push('\n');
694 }
695 out.push_str(&source[close_idx..]);
696 Ok(out)
697}
698
699pub fn bake_virtual_layers_to_footprint_source(
702 source: &str,
703 fab_view: &FabViewData,
704 footprint_name: &str,
705 synthetic_designator: &str,
706 opts: &BakeFootprintVirtualLayersOptions,
707 outline_override: Option<&FabLayerItems>,
708) -> Result<(String, BakeFootprintVirtualLayersReport), FabError> {
709 let mut normalized_map: Vec<(String, String)> = Vec::with_capacity(opts.layer_map.len());
710 let mut seen_keys = HashSet::new();
711 for (raw_key, klayer) in &opts.layer_map {
712 let canon = resolve_footprint_virtual_layer_key(raw_key)
713 .ok_or_else(|| FabError::UnknownVirtualLayer(raw_key.clone()))?;
714 let trimmed_layer = klayer.trim();
715 let _ = format_kicad_layer_quoted(trimmed_layer)?;
716 if seen_keys.insert(canon) {
717 normalized_map.push((canon.to_owned(), trimmed_layer.to_owned()));
718 }
719 }
720
721 let collisions = detect_footprint_layer_collisions(source, &normalized_map)?;
722 if !collisions.is_empty() && !opts.force {
723 return Ok((
724 source.to_owned(),
725 BakeFootprintVirtualLayersReport {
726 footprint_name: footprint_name.to_owned(),
727 synthetic_designator: synthetic_designator.to_owned(),
728 layers: Vec::new(),
729 collisions,
730 },
731 ));
732 }
733
734 let mut insert_buf = String::with_capacity(2048);
735 let mut layer_reports = Vec::with_capacity(normalized_map.len());
736 for (vkey, klayer) in &normalized_map {
737 let quoted_layer = format_kicad_layer_quoted(klayer)?;
738 let items = if vkey == "ASSEMBLY_OUTLINES_TOP" {
739 match outline_override {
740 Some(ov) if !ov.is_empty() => ov.clone(),
741 _ => build_footprint_pad_outline(fab_view),
742 }
743 } else {
744 build_virtual_layer(fab_view, vkey)
745 };
746 let written = append_fp_layer_items_sexpr(
747 &mut insert_buf,
748 footprint_name,
749 vkey,
750 "ed_layer,
751 &items,
752 );
753 layer_reports.push(BakeLayerReport {
754 virtual_key: vkey.clone(),
755 kicad_layer: klayer.clone(),
756 group_name: format!("{VIRTUAL_GROUP_PREFIX}{vkey}"),
757 items_written: written,
758 removed_previous: 0,
759 });
760 }
761
762 let out = splice_before_footprint_root_close(source, &insert_buf)?;
763 Ok((
764 out,
765 BakeFootprintVirtualLayersReport {
766 footprint_name: footprint_name.to_owned(),
767 synthetic_designator: synthetic_designator.to_owned(),
768 layers: layer_reports,
769 collisions,
770 },
771 ))
772}
773
774fn append_fp_layer_items_sexpr(
775 out: &mut String,
776 fp_name: &str,
777 vkey: &str,
778 quoted_layer: &str,
779 items: &FabLayerItems,
780) -> usize {
781 let tag = format!("fp:{fp_name}:{vkey}");
782 let mut seq = 1usize;
783 let mut written = 0usize;
784
785 for stroke in &items.strokes {
786 let w_mm = (stroke.width.max(50_000) as f64) / 1e6;
787 match stroke.path {
788 StrokePath::Line { start, end } => {
789 if start == end {
790 continue;
791 }
792 let uid = deterministic_uuid(&tag, seq);
793 seq += 1;
794 let (x0, y0) = nm_to_kicad_mm(start);
795 let (x1, y1) = nm_to_kicad_mm(end);
796 let _ = write!(
797 out,
798 "\n\t(fp_line\n\t\t(start {x0:.6} {y0:.6})\n\t\t(end {x1:.6} {y1:.6})\n\t\t(stroke\n\t\t\t(width {w_mm:.4})\n\t\t\t(type solid)\n\t\t)\n\t\t(layer {quoted_layer})\n\t\t(uuid \"{uid}\")\n\t)"
799 );
800 written += 1;
801 }
802 StrokePath::Arc {
803 start,
804 end,
805 center,
806 ccw,
807 major,
808 } => {
809 let r = ((start.x - center.x) as f64).hypot((start.y - center.y) as f64);
810 if r <= 1.0 {
811 continue;
812 }
813 if start == end {
814 if major {
815 let uid = deterministic_uuid(&tag, seq);
816 seq += 1;
817 let (cx, cy) = nm_to_kicad_mm(center);
818 let ex = cx + (r / 1e6);
819 let _ = write!(
820 out,
821 "\n\t(fp_circle\n\t\t(center {cx:.6} {cy:.6})\n\t\t(end {ex:.6} {cy:.6})\n\t\t(stroke\n\t\t\t(width {w_mm:.4})\n\t\t\t(type solid)\n\t\t)\n\t\t(fill none)\n\t\t(layer {quoted_layer})\n\t\t(uuid \"{uid}\")\n\t)"
822 );
823 written += 1;
824 }
825 continue;
826 }
827 let uid = deterministic_uuid(&tag, seq);
828 seq += 1;
829 let mid = arc_midpoint(start, end, center, ccw);
830 let (x0, y0) = nm_to_kicad_mm(start);
831 let (xm, ym) = nm_to_kicad_mm(mid);
832 let (x1, y1) = nm_to_kicad_mm(end);
833 let _ = write!(
834 out,
835 "\n\t(fp_arc\n\t\t(start {x0:.6} {y0:.6})\n\t\t(mid {xm:.6} {ym:.6})\n\t\t(end {x1:.6} {y1:.6})\n\t\t(stroke\n\t\t\t(width {w_mm:.4})\n\t\t\t(type solid)\n\t\t)\n\t\t(layer {quoted_layer})\n\t\t(uuid \"{uid}\")\n\t)"
836 );
837 written += 1;
838 }
839 StrokePath::FullCircle { center, radius } => {
840 if radius <= 1 {
841 continue;
842 }
843 let uid = deterministic_uuid(&tag, seq);
844 seq += 1;
845 let (cx, cy) = nm_to_kicad_mm(center);
846 let ex = cx + (radius as f64 / 1e6);
847 let _ = write!(
848 out,
849 "\n\t(fp_circle\n\t\t(center {cx:.6} {cy:.6})\n\t\t(end {ex:.6} {cy:.6})\n\t\t(stroke\n\t\t\t(width {w_mm:.4})\n\t\t\t(type solid)\n\t\t)\n\t\t(fill none)\n\t\t(layer {quoted_layer})\n\t\t(uuid \"{uid}\")\n\t)"
850 );
851 written += 1;
852 }
853 }
854 }
855
856 for area in &items.areas {
857 written += append_fp_area_sexpr(
858 out,
859 &tag,
860 quoted_layer,
861 &area.shape,
862 area.placement,
863 &mut seq,
864 );
865 }
866 for land in &items.lands {
867 written += append_fp_area_sexpr(
868 out,
869 &tag,
870 quoted_layer,
871 &land.shape,
872 land.placement,
873 &mut seq,
874 );
875 }
876 written
877}
878
879fn append_fp_area_sexpr(
880 out: &mut String,
881 tag: &str,
882 quoted_layer: &str,
883 shape: &AreaShape,
884 placement: Placement2D,
885 seq: &mut usize,
886) -> usize {
887 if let AreaShape::Disk { radius } = shape {
888 if *radius <= 1 {
889 return 0;
890 }
891 let uid = deterministic_uuid(tag, *seq);
892 *seq += 1;
893 let (cx, cy) = nm_to_kicad_mm(CoordNm::new(placement.tx, placement.ty));
894 let ex = cx + (*radius as f64 / 1e6);
895 let _ = write!(
896 out,
897 "\n\t(fp_circle\n\t\t(center {cx:.6} {cy:.6})\n\t\t(end {ex:.6} {cy:.6})\n\t\t(stroke\n\t\t\t(width 0.05)\n\t\t\t(type solid)\n\t\t)\n\t\t(fill solid)\n\t\t(layer {quoted_layer})\n\t\t(uuid \"{uid}\")\n\t)"
898 );
899 return 1;
900 }
901 let pts = shape_to_board_polygon(shape, placement);
902 if pts.len() < 3 {
903 return 0;
904 }
905 let uid = deterministic_uuid(tag, *seq);
906 *seq += 1;
907 out.push_str("\n\t(fp_poly\n\t\t(pts");
908 for pt in pts {
909 let (x, y) = nm_to_kicad_mm(pt);
910 let _ = write!(out, "\n\t\t\t(xy {x:.6} {y:.6})");
911 }
912 let _ = write!(
913 out,
914 "\n\t\t)\n\t\t(stroke\n\t\t\t(width 0.05)\n\t\t\t(type solid)\n\t\t)\n\t\t(fill solid)\n\t\t(layer {quoted_layer})\n\t\t(uuid \"{uid}\")\n\t)"
915 );
916 1
917}
918
919#[must_use]
921pub fn footprint_glob_match(text: &str, pattern: &str) -> bool {
922 crate::bake::glob_match(text, pattern)
923}
924
925#[cfg(test)]
926mod tests {
927 use super::*;
928
929 fn sample_diode_mod() -> &'static str {
930 r#"(footprint "D_SOD-123"
931 (version 20241229)
932 (generator "pcbnew")
933 (layer "F.Cu")
934 (descr "Schottky Diode SOD-123")
935 (tags "diode schottky")
936 (property "Reference" "REF**" (at 0 -1.8) (layer "F.SilkS")
937 (effects (font (size 1 1) (thickness 0.15)))
938 )
939 (property "Value" "D_SOD-123" (at 0 1.8) (layer "F.Fab")
940 (effects (font (size 1 1) (thickness 0.15)))
941 )
942 (attr smd)
943 (fp_line (start -1.6 -0.9) (end 1.6 -0.9) (stroke (width 0.12) (type solid)) (layer "F.SilkS"))
944 (fp_line (start -1.5 -0.8) (end 1.5 -0.8) (stroke (width 0.1) (type solid)) (layer "F.Fab"))
945 (fp_text user "${REFERENCE}" (at 0 0) (layer "F.Fab") (effects (font (size 0.5 0.5) (thickness 0.08))))
946 (pad "1" smd rect (at -1.2 0) (size 0.9 1.0) (layers "F.Cu" "F.Mask" "F.Paste"))
947 (pad "2" smd rect (at 1.2 0) (size 0.9 1.0) (layers "F.Cu" "F.Mask" "F.Paste"))
948)
949"#
950 }
951
952 #[test]
953 fn clean_and_bake_diode_footprint_roundtrips_cleanly() {
954 let src = sample_diode_mod();
955 let (view, fp_name, synth) =
956 build_footprint_fab_view(src, Some("Diode_SMD"), None, &BTreeMap::new()).unwrap();
957 assert_eq!(fp_name, "D_SOD-123");
958 assert_eq!(synth, "D1");
959
960 let clean_opts = PcbCleanOptions::default();
961 let (cleaned, clean_rep) = clean_footprint_doc_layers_source(src, &clean_opts).unwrap();
962 assert_eq!(clean_rep.footprint_graphics_removed, 2); assert_eq!(clean_rep.value_fields_hidden, 1);
964 assert!(cleaned.contains("F.SilkS"));
965 assert!(!cleaned.contains("${REFERENCE}"));
966
967 let opts = BakeFootprintVirtualLayersOptions::default();
968 let (baked, bake_rep) =
969 bake_virtual_layers_to_footprint_source(&cleaned, &view, &fp_name, &synth, &opts, None)
970 .unwrap();
971 assert!(bake_rep.collisions.is_empty());
972 assert!(bake_rep.total_items_written() > 0);
973 let parsed = FootprintView::parse(&baked, FootprintLimits::default()).unwrap();
975 assert_eq!(parsed.name().unwrap(), "D_SOD-123");
976 let by_key: BTreeMap<_, _> = bake_rep
977 .layers
978 .iter()
979 .map(|l| (l.virtual_key.as_str(), l.items_written))
980 .collect();
981 assert!(*by_key.get("ASSEMBLY_OUTLINES_TOP").unwrap_or(&0) > 0);
982 assert!(*by_key.get("PIN1_TOP").unwrap_or(&0) > 0);
983 assert!(*by_key.get("DIODES_TOP").unwrap_or(&0) > 0);
984 }
985
986 #[test]
987 fn infer_designator_guards_multipin_and_connectors() {
988 let dsub = r#"(footprint "D-Sub_DB9"
989 (version 20241229) (layer "F.Cu") (descr "9-pin D-Sub")
990 (property "Reference" "REF**" (at 0 -2) (layer "F.SilkS") (effects (font (size 1 1) (thickness 0.15))))
991 (pad "1" smd rect (at 0 0) (size 0.5 0.5) (layers "F.Cu"))
992 (pad "2" smd rect (at 1 0) (size 0.5 0.5) (layers "F.Cu"))
993 (pad "3" smd rect (at 2 0) (size 0.5 0.5) (layers "F.Cu"))
994)"#;
995 let (_, _, ref_dsub) =
996 build_footprint_fab_view(dsub, None, None, &BTreeMap::new()).unwrap();
997 assert_eq!(ref_dsub, "J1");
998
999 let r_arr = r#"(footprint "R_Array_4x0603"
1000 (version 20241229) (layer "F.Cu") (descr "4x resistor array")
1001 (property "Reference" "REF**" (at 0 -2) (layer "F.SilkS") (effects (font (size 1 1) (thickness 0.15))))
1002 (pad "1" smd rect (at 0 0) (size 0.5 0.5) (layers "F.Cu"))
1003 (pad "2" smd rect (at 1 0) (size 0.5 0.5) (layers "F.Cu"))
1004 (pad "3" smd rect (at 2 0) (size 0.5 0.5) (layers "F.Cu"))
1005 (pad "4" smd rect (at 3 0) (size 0.5 0.5) (layers "F.Cu"))
1006)"#;
1007 let (_, _, ref_arr) =
1008 build_footprint_fab_view(r_arr, None, None, &BTreeMap::new()).unwrap();
1009 assert_eq!(ref_arr, "U1");
1010
1011 let conn_tvs = r#"(footprint "Conn_01x02_Pin"
1012 (version 20241229) (layer "F.Cu") (descr "2-pin connector for TVS test")
1013 (property "Reference" "REF**" (at 0 -2) (layer "F.SilkS") (effects (font (size 1 1) (thickness 0.15))))
1014 (pad "1" smd rect (at 0 0) (size 0.5 0.5) (layers "F.Cu"))
1015 (pad "2" smd rect (at 2 0) (size 0.5 0.5) (layers "F.Cu"))
1016)"#;
1017 let (_, _, ref_conn) =
1018 build_footprint_fab_view(conn_tvs, None, None, &BTreeMap::new()).unwrap();
1019 assert_eq!(ref_conn, "J1");
1020 }
1021}