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

kicad_monkey_core/
text_metadata.rs

1//! Close-to-format text metadata shared by KiCad document families.
2
3use std::ops::Range;
4
5use crate::sexpr::{Error, ErrorKind, ErrorPhase, Position, Sexp};
6
7const DEFAULT_TEXT_SIZE_MM: f64 = 1.27;
8
9/// An optional RGBA color authored in a KiCad font or stroke block.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct KiCadColor {
12    pub red: i64,
13    pub green: i64,
14    pub blue: i64,
15    pub alpha: f64,
16}
17
18/// Font fields common to PCB, footprint, schematic, and symbol text.
19#[derive(Clone, Debug, PartialEq)]
20pub struct KiCadFont {
21    pub face: Option<String>,
22    pub size_x: f64,
23    pub size_y: f64,
24    pub thickness: Option<f64>,
25    pub bold: bool,
26    pub italic: bool,
27    pub line_spacing: Option<f64>,
28    pub color: Option<KiCadColor>,
29}
30
31impl Default for KiCadFont {
32    fn default() -> Self {
33        Self {
34            face: None,
35            size_x: 1.27,
36            size_y: 1.27,
37            thickness: None,
38            bold: false,
39            italic: false,
40            line_spacing: None,
41            color: None,
42        }
43    }
44}
45
46/// Text effects shared across KiCad document families.
47#[derive(Clone, Debug, Default, PartialEq)]
48pub struct KiCadTextEffects {
49    pub font: KiCadFont,
50    pub justify: Vec<String>,
51    pub hidden: bool,
52    pub href: Option<String>,
53    pub source_range: Option<Range<usize>>,
54}
55
56/// Decode the close-to-format `(effects ...)` block shared by footprint and
57/// library-symbol text carriers.
58pub(crate) fn parse_text_effects(form: &Sexp) -> Result<Option<KiCadTextEffects>, Error> {
59    let Some(effects) = child(form, "effects") else {
60        return Ok(None);
61    };
62    let font_form = child(effects, "font");
63    let size = font_form.and_then(|font| child(font, "size"));
64    let font = KiCadFont {
65        face: font_form
66            .and_then(|font| child(font, "face"))
67            .and_then(|value| value_at(value, 1))
68            .filter(|value| !value.is_empty())
69            .map(str::to_owned),
70        size_y: numeric_or(size, 1, DEFAULT_TEXT_SIZE_MM)?,
71        size_x: numeric_or(size, 2, DEFAULT_TEXT_SIZE_MM)?,
72        thickness: optional_numeric_child(font_form, "thickness")?,
73        bold: font_form.is_some_and(|font| named_bool(font, "bold").unwrap_or(false)),
74        italic: font_form.is_some_and(|font| named_bool(font, "italic").unwrap_or(false)),
75        line_spacing: optional_numeric_child(font_form, "line_spacing")?,
76        color: font_form
77            .and_then(|font| child(font, "color"))
78            .filter(|value| list_values(value).is_some_and(|values| values.len() >= 5))
79            .map(parse_color)
80            .transpose()?,
81    };
82    let justify = child(effects, "justify")
83        .and_then(list_values)
84        .map(|values| {
85            values[1..]
86                .iter()
87                .filter_map(text_value)
88                .map(str::to_owned)
89                .collect()
90        })
91        .unwrap_or_default();
92    Ok(Some(KiCadTextEffects {
93        font,
94        justify,
95        hidden: named_bool(effects, "hide").unwrap_or(false),
96        href: child(effects, "href")
97            .and_then(|value| value_at(value, 1))
98            .map(str::to_owned),
99        source_range: None,
100    }))
101}
102
103fn parse_color(form: &Sexp) -> Result<KiCadColor, Error> {
104    Ok(KiCadColor {
105        red: finite_numeric_at(form, 1)? as i64,
106        green: finite_numeric_at(form, 2)? as i64,
107        blue: finite_numeric_at(form, 3)? as i64,
108        alpha: finite_numeric_at(form, 4)?,
109    })
110}
111
112fn numeric_or(form: Option<&Sexp>, index: usize, default: f64) -> Result<f64, Error> {
113    match form {
114        Some(value) if list_values(value).is_some_and(|values| values.len() > index) => {
115            finite_numeric_at(value, index)
116        }
117        _ => Ok(default),
118    }
119}
120
121fn optional_numeric_child(form: Option<&Sexp>, name: &str) -> Result<Option<f64>, Error> {
122    form.and_then(|value| child(value, name))
123        .filter(|value| list_values(value).is_some_and(|values| values.len() > 1))
124        .map(|value| finite_numeric_at(value, 1))
125        .transpose()
126}
127
128fn finite_numeric_at(form: &Sexp, index: usize) -> Result<f64, Error> {
129    let value = list_values(form)
130        .and_then(|values| values.get(index))
131        .ok_or_else(|| text_metadata_error("Expected text-effects numeric value"))?;
132    let value = match value {
133        Sexp::Integer(value) => *value as f64,
134        Sexp::Float(value) => *value,
135        Sexp::Atom(value) | Sexp::Quoted(value) => value
136            .parse()
137            .map_err(|_| text_metadata_error("Expected text-effects numeric value"))?,
138        _ => return Err(text_metadata_error("Expected text-effects numeric value")),
139    };
140    if value.is_finite() {
141        Ok(value)
142    } else {
143        Err(text_metadata_error(
144            "Expected finite text-effects numeric value",
145        ))
146    }
147}
148
149fn named_bool(form: &Sexp, name: &str) -> Option<bool> {
150    if has_flag(form, name) {
151        return Some(true);
152    }
153    let value = child(form, name)?;
154    if list_values(value).is_none_or(|values| values.len() <= 1) {
155        return Some(false);
156    }
157    Some(value_at(value, 1) == Some("yes"))
158}
159
160fn has_flag(form: &Sexp, name: &str) -> bool {
161    list_values(form)
162        .into_iter()
163        .flatten()
164        .any(|value| text_value(value) == Some(name))
165}
166
167fn list_values(form: &Sexp) -> Option<&[Sexp]> {
168    match form {
169        Sexp::List(values) => Some(values),
170        _ => None,
171    }
172}
173
174fn text_value(value: &Sexp) -> Option<&str> {
175    match value {
176        Sexp::Atom(value) | Sexp::Quoted(value) => Some(value),
177        _ => None,
178    }
179}
180
181fn child<'a>(form: &'a Sexp, head: &str) -> Option<&'a Sexp> {
182    list_values(form)?
183        .iter()
184        .find(|candidate| value_at(candidate, 0) == Some(head))
185}
186
187fn value_at(form: &Sexp, index: usize) -> Option<&str> {
188    list_values(form)?.get(index).and_then(text_value)
189}
190
191fn text_metadata_error(message: &'static str) -> Error {
192    Error::at(
193        ErrorPhase::Tree,
194        ErrorKind::UnexpectedToken,
195        message,
196        Position::START,
197    )
198}