Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/library_edits/
footprints.rs

1use super::{
2    Error, LibraryEdit, children, children_mut, finish, head, invalid, named_child, replacement,
3    root_and_spans, scalar,
4};
5use crate::sexpr::{Patch, Sexp, parse};
6use crate::sexpr_projection::FormSpan;
7
8/// Direct standalone-footprint edits. Every choice is supplied by the caller.
9#[derive(Clone, Debug, Default)]
10pub struct FootprintEdits<'a> {
11    pub retain_properties: Option<&'a [&'a str]>,
12    pub remove_attribute_tokens: &'a [&'a str],
13    /// Remove only recognized fp_* graphic/text forms on these exact layers;
14    /// pads, models, properties and unknown extension forms are not artwork.
15    pub remove_graphic_layers: &'a [&'a str],
16    pub text_face: Option<&'a str>,
17}
18
19/// Edit only the explicitly requested direct footprint fields.
20pub fn edit_footprint(
21    source: &str,
22    edits: &FootprintEdits<'_>,
23    max_output_bytes: usize,
24) -> Result<LibraryEdit, Error> {
25    if edits.text_face.is_some_and(|face| face.contains('\0')) {
26        return Err(invalid("Text font face contains NUL"));
27    }
28    let (_, spans) = root_and_spans(source, &["footprint", "module"])?;
29    if !has_edits(edits) {
30        return finish(source, &[], max_output_bytes);
31    }
32    let mut patches = Vec::new();
33    for span in spans.iter().filter(|span| editable_form(span)) {
34        let tag = span.head.as_deref().unwrap_or("");
35        let mut value = parse(span.text(source)?)?;
36        if remove_form(tag, children(&value)?, edits) {
37            patches.push(Patch::new(span.range.start, span.range.end, ""));
38            continue;
39        }
40        if tag == "attr" && remove_attributes(&mut value, edits.remove_attribute_tokens)? {
41            patches.push(Patch::new(span.range.start, span.range.end, ""));
42            continue;
43        }
44        if matches!(tag, "fp_text" | "property")
45            && let Some(face) = edits.text_face
46        {
47            ensure_face(&mut value, face)?;
48        }
49        if let Some(patch) = replacement(source, span, &value, max_output_bytes)? {
50            patches.push(patch);
51        }
52    }
53    finish(source, &patches, max_output_bytes)
54}
55
56fn editable_form(span: &FormSpan) -> bool {
57    let tag = span.head.as_deref().unwrap_or("");
58    span.depth == 1 && (matches!(tag, "property" | "attr" | "fp_text") || is_graphic(tag))
59}
60
61fn remove_form(tag: &str, values: &[Sexp], edits: &FootprintEdits<'_>) -> bool {
62    if tag == "property" {
63        return edits.retain_properties.is_some_and(|names| {
64            values
65                .get(1)
66                .and_then(scalar)
67                .is_some_and(|name| !names.contains(&name))
68        });
69    }
70    is_graphic(tag)
71        && named_child(values, "layer")
72            .and_then(|layer| children(layer).ok())
73            .and_then(|layer| layer.get(1))
74            .and_then(scalar)
75            .is_some_and(|layer| edits.remove_graphic_layers.contains(&layer))
76}
77
78fn has_edits(edits: &FootprintEdits<'_>) -> bool {
79    edits.retain_properties.is_some()
80        || !edits.remove_attribute_tokens.is_empty()
81        || !edits.remove_graphic_layers.is_empty()
82        || edits.text_face.is_some()
83}
84
85/// Remove any direct footprint form having a direct layer child matching an
86/// exact layer or literal prefix supplied by the caller. This deliberately
87/// includes properties and extension forms on those selected layers. Every
88/// other byte, including unknown forms and embedded payloads, stays unchanged.
89/// Empty layer/prefix sets are a no-op; no layer patterns are implicit.
90pub fn remove_footprint_layer_forms(
91    source: &str,
92    exact_layers: &[&str],
93    layer_prefixes: &[&str],
94    max_output_bytes: usize,
95) -> Result<LibraryEdit, Error> {
96    let (_, spans) = root_and_spans(source, &["footprint", "module"])?;
97    let mut direct = None;
98    let mut last_removed = None;
99    let mut patches = Vec::new();
100    for span in &spans {
101        if span.depth == 1 {
102            direct = Some(span);
103            continue;
104        }
105        if span.depth != 2 || span.head.as_deref() != Some("layer") {
106            continue;
107        }
108        let value = parse(span.text(source)?)?;
109        let selected = children(&value)?
110            .get(1)
111            .and_then(scalar)
112            .is_some_and(|layer| layer_matches(layer, exact_layers, layer_prefixes));
113        if let Some(parent) =
114            direct.filter(|parent| selected && last_removed != Some(parent.range.start))
115        {
116            patches.push(Patch::new(parent.range.start, parent.range.end, ""));
117            last_removed = Some(parent.range.start);
118        }
119    }
120    finish(source, &patches, max_output_bytes)
121}
122
123fn layer_matches(layer: &str, exact: &[&str], prefixes: &[&str]) -> bool {
124    exact.contains(&layer) || prefixes.iter().any(|prefix| layer.starts_with(*prefix))
125}
126
127fn remove_attributes(value: &mut Sexp, tokens: &[&str]) -> Result<bool, Error> {
128    let values = children_mut(value)?;
129    let previous = values.len();
130    let mut index = 0;
131    values.retain(|value| {
132        let retain = index == 0 || !scalar(value).is_some_and(|value| tokens.contains(&value));
133        index += 1;
134        retain
135    });
136    Ok(previous != values.len() && values.len() == 1)
137}
138
139/// Repair only direct `(pad ... (size x y))` fields. If either axis is
140/// nonpositive, both axes become the explicitly supplied positive dimensions.
141/// Missing size fields and nested padstack sizes are left unchanged.
142pub fn normalize_nonpositive_direct_pad_sizes(
143    source: &str,
144    replacement_mm: [f64; 2],
145    max_output_bytes: usize,
146) -> Result<LibraryEdit, Error> {
147    if replacement_mm
148        .iter()
149        .any(|axis| !axis.is_finite() || *axis <= 0.0)
150    {
151        return Err(invalid(
152            "Replacement pad dimensions must be positive finite numbers",
153        ));
154    }
155    let (_, spans) = root_and_spans(source, &["footprint", "module"])?;
156    let mut patches = Vec::new();
157    for span in first_direct_sizes(&spans) {
158        let mut size = parse(span.text(source)?)?;
159        let values = children_mut(&mut size)?;
160        let x = values
161            .get(1)
162            .and_then(number)
163            .ok_or_else(|| invalid("Direct pad size has no finite x axis"))?;
164        let y = values
165            .get(2)
166            .and_then(number)
167            .ok_or_else(|| invalid("Direct pad size has no finite y axis"))?;
168        if x <= 0.0 || y <= 0.0 {
169            values[1] = Sexp::Float(replacement_mm[0]);
170            values[2] = Sexp::Float(replacement_mm[1]);
171            if let Some(patch) = replacement(source, span, &size, max_output_bytes)? {
172                patches.push(patch);
173            }
174        }
175    }
176    finish(source, &patches, max_output_bytes)
177}
178
179fn first_direct_sizes(spans: &[FormSpan]) -> Vec<&FormSpan> {
180    let mut selected = Vec::new();
181    let mut saw_size = false;
182    for span in spans {
183        if span.depth == 1 && span.head.as_deref() == Some("pad") {
184            saw_size = false;
185        }
186        if !saw_size
187            && span.depth == 2
188            && span.path.get(1).is_some_and(|head| head == "pad")
189            && span.head.as_deref() == Some("size")
190        {
191            selected.push(span);
192            saw_size = true;
193        }
194    }
195    selected
196}
197
198fn number(value: &Sexp) -> Option<f64> {
199    match value {
200        Sexp::Integer(value) => Some(*value as f64),
201        Sexp::Float(value) if value.is_finite() => Some(*value),
202        _ => None,
203    }
204}
205
206fn is_graphic(tag: &str) -> bool {
207    matches!(
208        tag,
209        "fp_line"
210            | "fp_arc"
211            | "fp_circle"
212            | "fp_rect"
213            | "fp_poly"
214            | "fp_curve"
215            | "fp_text"
216            | "fp_text_box"
217    )
218}
219
220fn ensure_face(value: &mut Sexp, face: &str) -> Result<(), Error> {
221    let values = children_mut(value)?;
222    let index = match values
223        .iter()
224        .position(|value| head(value) == Some("effects"))
225    {
226        Some(index) => index,
227        None => {
228            values.push(Sexp::List(vec![Sexp::Atom("effects".into())]));
229            values.len() - 1
230        }
231    };
232    let effects = children_mut(&mut values[index])?;
233    let index = match effects.iter().position(|value| head(value) == Some("font")) {
234        Some(index) => index,
235        None => {
236            effects.push(Sexp::List(vec![Sexp::Atom("font".into())]));
237            effects.len() - 1
238        }
239    };
240    let font = &mut effects[index];
241    let next = Sexp::List(vec![Sexp::Atom("face".into()), Sexp::Quoted(face.into())]);
242    if !crate::sexpr_mutation::replace_element(font, "face", next.clone()) {
243        children_mut(font)?.push(next);
244    }
245    Ok(())
246}