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

kicad_monkey_core/
footprint_text.rs

1//! Standalone-footprint property and text carrier decoding.
2
3use crate::KiCadTextEffects;
4use crate::footprint::FootprintView;
5use crate::pcb::{
6    standalone_property_from_span, standalone_text_box_from_span, standalone_text_from_span,
7};
8use crate::sexpr::Error;
9use std::ops::Range;
10
11/// Fold locked footprint text's drawing angle into (-90, 90].
12///
13/// This is KiCad's keep-upright presentation rule, not an authored rotation
14/// normalization. Unlocked text must retain its original angle instead.
15pub fn keep_upright_draw_angle(angle: f64) -> f64 {
16    let mut angle = angle.rem_euclid(360.0);
17    while angle > 90.0 {
18        angle -= 180.0;
19    }
20    while angle <= -90.0 {
21        angle += 180.0;
22    }
23    angle
24}
25
26#[cfg(test)]
27mod angle_tests {
28    #[test]
29    fn locked_draw_angle_retains_the_positive_quarter_turn_boundary() {
30        for (source, expected) in [(150., -30.), (90., 90.), (-90., 90.), (450., 90.)] {
31            assert_eq!(super::keep_upright_draw_angle(source), expected);
32        }
33    }
34
35    #[test]
36    fn optional_cache_failures_preserve_text_and_property_acquisition() {
37        for cache in [
38            "(render_cache)",
39            "(render_cache \"X\")",
40            "(render_cache \"X\" bad)",
41            "(render_cache \"X\" nan)",
42            "(render_cache \"X\" 0 (polygon (pts (xy 0 bad))))",
43            "(render_cache \"X\" 0 (polygon (pts (xy 0 0) (xy 1 0) (xy 0 1) (xy 3))))",
44            "(render_cache \"X\" 0 (polygon (pts (xy 0 inf))))",
45        ] {
46            for header in ["fp_text user \"X\"", "property \"Reference\" \"X\""] {
47                let source = format!(
48                    "(footprint \"cache\" (layer \"F.Cu\") ({header} (at 1 2) (layer \"F.SilkS\" knockout) (effects (font (size 1 1))) {cache}))"
49                );
50                let view = crate::FootprintView::parse(&source, crate::FootprintLimits::default())
51                    .unwrap();
52                if header.starts_with("fp_text") {
53                    let owner = view.texts().next().unwrap().unwrap();
54                    assert!(owner.knockout && owner.render_cache_range.is_some());
55                    assert_eq!((owner.text.as_str(), owner.at_x, owner.at_y), ("X", 1., 2.));
56                    assert!(owner.read_render_cache(&source).is_err());
57                } else {
58                    let owner = view.graphical_properties().next().unwrap().unwrap();
59                    assert!(owner.knockout && owner.render_cache_range.is_some());
60                    assert_eq!(
61                        (owner.value.as_str(), owner.at_x, owner.at_y),
62                        ("X", 1., 2.)
63                    );
64                    assert!(owner.read_render_cache(&source).is_err());
65                }
66            }
67        }
68        let source = "(footprint \"cache\" (layer \"F.Cu\") (fp_text user \"X\" (at 0 0) (layer \"F.SilkS\")) (fp_text user \"X\" (at 0 0) (layer \"F.SilkS\") (render_cache \"X\" 0)))";
69        let view = crate::FootprintView::parse(source, crate::FootprintLimits::default()).unwrap();
70        let owners = view.texts().collect::<Result<Vec<_>, _>>().unwrap();
71        assert!(owners[0].read_render_cache(source).unwrap().is_none());
72        assert!(
73            owners[1]
74                .read_render_cache(source)
75                .unwrap()
76                .unwrap()
77                .polygons
78                .is_empty()
79        );
80        assert!(owners[1].read_render_cache("").is_err());
81    }
82}
83
84#[derive(Clone, Debug, PartialEq)]
85pub struct FootprintGraphicalProperty {
86    pub name: String,
87    pub value: String,
88    pub at_x: f64,
89    pub at_y: f64,
90    pub angle: f64,
91    pub layer: String,
92    pub knockout: bool,
93    pub hidden: bool,
94    pub unlocked: bool,
95    pub graphical: bool,
96    pub effects: KiCadTextEffects,
97    pub render_cache_range: Option<Range<usize>>,
98    pub uuid: Option<String>,
99    pub source_range: Range<usize>,
100}
101
102#[derive(Clone, Debug, PartialEq)]
103pub struct FootprintText {
104    pub kind: String,
105    pub text: String,
106    pub at_x: f64,
107    pub at_y: f64,
108    pub angle: f64,
109    pub layer: String,
110    pub knockout: bool,
111    pub hidden: bool,
112    pub unlocked: bool,
113    pub effects: KiCadTextEffects,
114    pub render_cache_range: Option<Range<usize>>,
115    pub uuid: Option<String>,
116    pub source_range: Range<usize>,
117}
118
119impl FootprintText {
120    /// Read only this owner's optional source realization. Absence is `None`;
121    /// present malformed data is an error, while the authored owner survives.
122    /// Consumers choose recovery policy rather than mistaking failure for absence.
123    pub fn read_render_cache(
124        &self,
125        source: &str,
126    ) -> Result<Option<crate::TextRenderCache>, crate::TextRenderCacheError> {
127        read_optional_render_cache(self.render_cache_range.as_ref(), source)
128    }
129}
130
131impl FootprintGraphicalProperty {
132    /// Same optional realization read as `FootprintText`, retaining property intent.
133    pub fn read_render_cache(
134        &self,
135        source: &str,
136    ) -> Result<Option<crate::TextRenderCache>, crate::TextRenderCacheError> {
137        read_optional_render_cache(self.render_cache_range.as_ref(), source)
138    }
139}
140
141fn read_optional_render_cache(
142    range: Option<&Range<usize>>,
143    source: &str,
144) -> Result<Option<crate::TextRenderCache>, crate::TextRenderCacheError> {
145    let Some(range) = range else {
146        return Ok(None);
147    };
148    let bytes =
149        source
150            .as_bytes()
151            .get(range.clone())
152            .ok_or_else(|| crate::TextRenderCacheError {
153                kind: crate::TextRenderCacheErrorKind::InvalidInput,
154                path: "$".into(),
155                message: "owner render-cache range is outside its source",
156            })?;
157    crate::read_text_render_cache_a0(bytes).map(Some)
158}
159
160#[derive(Clone, Debug, PartialEq)]
161pub struct FootprintTextBox {
162    pub text: String,
163    pub start_x: f64,
164    pub start_y: f64,
165    pub end_x: f64,
166    pub end_y: f64,
167    pub margins: [f64; 4],
168    pub angle: f64,
169    pub polygon_points: Vec<[f64; 2]>,
170    pub layer: String,
171    pub locked: bool,
172    pub effects: Option<KiCadTextEffects>,
173    pub stroke_width: Option<f64>,
174    pub stroke_kind: Option<String>,
175    pub border: Option<bool>,
176    pub knockout: Option<bool>,
177    pub render_cache_range: Option<Range<usize>>,
178    pub uuid: Option<String>,
179    pub source_range: Range<usize>,
180}
181
182impl FootprintView<'_> {
183    /// Standalone-owned custom values, excluding source-version standard/system fields.
184    pub fn custom_parameters(&self) -> Result<std::collections::BTreeMap<String, String>, Error> {
185        crate::pcb::standalone_parameter_values(
186            self.source,
187            &self.root,
188            &self.properties,
189            self.pcb_limits(),
190        )
191    }
192
193    /// Classify one exact original property under this source file's version.
194    pub fn primary_property_name(&self, name: &str) -> Result<Option<&'static str>, Error> {
195        crate::pcb::standalone_primary_property_name(
196            self.source,
197            &self.root,
198            name,
199            self.pcb_limits(),
200        )
201    }
202
203    /// Source-ordered exact primary values; missing and explicitly empty differ.
204    pub fn effective_primary_values(
205        &self,
206    ) -> Result<std::collections::BTreeMap<String, String>, Error> {
207        crate::pcb::standalone_primary_values(
208            self.source,
209            &self.root,
210            &self.properties,
211            &self.texts,
212            self.pcb_limits(),
213        )
214    }
215
216    /// Resolve authored primary slots into existing property records.
217    pub fn effective_primary_fields(&self) -> Result<Vec<FootprintGraphicalProperty>, Error> {
218        let mut rows = Vec::new();
219        for name in ["Reference", "Value", "Description"] {
220            if let Some(row) = self.effective_primary_field(name)? {
221                rows.push(row);
222            }
223        }
224        Ok(rows)
225    }
226
227    /// A per-slot read allows a caller to localize unsupported source history.
228    pub fn effective_primary_field(
229        &self,
230        name: &str,
231    ) -> Result<Option<FootprintGraphicalProperty>, Error> {
232        Ok(crate::pcb::standalone_primary_fields(
233            self.source,
234            &self.root,
235            &self.properties,
236            &self.texts,
237            self.pcb_limits(),
238            name,
239        )?
240        .map(|value| FootprintGraphicalProperty {
241            name: value.name,
242            value: value.value,
243            at_x: value.at.x,
244            at_y: value.at.y,
245            angle: value.angle,
246            layer: value.layer,
247            knockout: value.knockout,
248            hidden: value.hidden,
249            unlocked: value.unlocked,
250            graphical: value.graphical,
251            effects: value.effects,
252            render_cache_range: value.render_cache_range,
253            uuid: value.uuid,
254            source_range: value.source_range,
255        }))
256    }
257
258    /// Decode graphical property facts from their selected top-level spans.
259    pub fn graphical_properties(
260        &self,
261    ) -> impl Iterator<Item = Result<FootprintGraphicalProperty, Error>> + '_ {
262        self.properties.iter().map(|span| {
263            let value = standalone_property_from_span(self.source, span, self.pcb_limits())?;
264            Ok(FootprintGraphicalProperty {
265                name: value.name,
266                value: value.value,
267                at_x: value.at.x,
268                at_y: value.at.y,
269                angle: value.angle,
270                layer: value.layer,
271                knockout: value.knockout,
272                hidden: value.hidden,
273                unlocked: value.unlocked,
274                graphical: value.graphical,
275                effects: value.effects,
276                render_cache_range: value.render_cache_range,
277                uuid: value.uuid,
278                source_range: value.source_range,
279            })
280        })
281    }
282
283    /// Decode footprint-local `fp_text` carriers in source order.
284    pub fn texts(&self) -> impl Iterator<Item = Result<FootprintText, Error>> + '_ {
285        self.texts.iter().map(|span| {
286            let value = standalone_text_from_span(self.source, span, self.pcb_limits())?;
287            Ok(FootprintText {
288                kind: value.kind,
289                text: value.text,
290                at_x: value.at.x,
291                at_y: value.at.y,
292                angle: value.angle,
293                layer: value.layer,
294                knockout: value.knockout,
295                hidden: value.hidden,
296                unlocked: value.unlocked,
297                effects: value.effects,
298                render_cache_range: value.render_cache_range,
299                uuid: value.uuid,
300                source_range: value.source_range,
301            })
302        })
303    }
304
305    /// Decode standalone `fp_text_box` carriers in source order.
306    pub fn text_boxes(&self) -> impl Iterator<Item = Result<FootprintTextBox, Error>> + '_ {
307        self.text_boxes.iter().map(|span| {
308            let value = standalone_text_box_from_span(self.source, span, self.pcb_limits())?;
309            Ok(FootprintTextBox {
310                text: value.text,
311                start_x: value.start.x,
312                start_y: value.start.y,
313                end_x: value.end.x,
314                end_y: value.end.y,
315                margins: value.margins,
316                angle: value.angle,
317                polygon_points: value
318                    .polygon_points
319                    .into_iter()
320                    .map(|point| [point.x, point.y])
321                    .collect(),
322                layer: value.layer,
323                locked: value.locked,
324                effects: value.effects,
325                stroke_width: value.stroke_width,
326                stroke_kind: value.stroke_kind,
327                border: value.border,
328                knockout: value.knockout,
329                render_cache_range: value.render_cache_range,
330                uuid: value.uuid,
331                source_range: value.source_range,
332            })
333        })
334    }
335}