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

kicad_monkey_core/pcb/
text.rs

1//! Authored board text, independent of whether plotting produces geometry.
2
3use super::*;
4
5/// One source `gr_text` owner, including empty and hidden text.
6/// Coordinates remain KiCad millimetres and angles remain authored degrees.
7#[derive(Clone, Debug, PartialEq)]
8pub struct PcbBoardText {
9    pub graphic_index: usize,
10    pub text: String,
11    pub at: PcbPoint,
12    pub angle: f64,
13    pub layer: String,
14    pub knockout: bool,
15    pub hidden: bool,
16    pub locked: bool,
17    pub effects: KiCadTextEffects,
18    pub render_cache_range: Option<Range<usize>>,
19    pub uuid: Option<String>,
20    pub source_range: Range<usize>,
21}
22
23impl PcbView<'_> {
24    /// Read the actual nested text of a selected dimension through the existing
25    /// source text decoder. The index belongs to `dimensions()` source order.
26    pub fn dimension_text(&self, index: usize) -> Result<Option<PcbBoardText>, Error> {
27        if !self.selection.contains(PcbFamily::Dimensions) {
28            return Err(Error::build(
29                ErrorKind::UnexpectedToken,
30                "dimensions were not selected",
31            ));
32        }
33        let dimension = self.dimensions.get(index).ok_or_else(|| {
34            Error::build(
35                ErrorKind::UnexpectedToken,
36                "dimension index does not resolve",
37            )
38        })?;
39        let children = direct_children(
40            self.source,
41            dimension,
42            self.limits.max_object_children,
43            self.limits,
44        )?;
45        child(&children, "gr_text")
46            .map(|span| board_text_from_span(self.source, index, span, self.limits))
47            .transpose()
48    }
49
50    /// Read selected board text in source order without invoking the plotter.
51    /// Cache presence is retained even when a plotter would reject its content.
52    pub fn board_texts(&self) -> impl Iterator<Item = Result<PcbBoardText, Error>> + '_ {
53        self.graphics
54            .iter()
55            .enumerate()
56            .filter(move |(_, span)| {
57                self.selection.contains(PcbFamily::Graphics)
58                    && span.head.as_deref() == Some("gr_text")
59            })
60            .map(|(index, span)| board_text_from_span(self.source, index, span, self.limits))
61    }
62
63    /// Read selected board text boxes in source order; the index is the
64    /// graphic's position among all board graphics, as for board text.
65    pub fn board_text_boxes(&self) -> impl Iterator<Item = Result<PcbBoardTextBox, Error>> + '_ {
66        self.graphics
67            .iter()
68            .enumerate()
69            .filter(move |(_, span)| {
70                self.selection.contains(PcbFamily::Graphics)
71                    && span.head.as_deref() == Some("gr_text_box")
72            })
73            .map(|(index, span)| board_text_box_from_span(self.source, index, span, self.limits))
74    }
75}
76
77fn board_text_box_from_span(
78    source: &str,
79    graphic_index: usize,
80    span: &FormSpan,
81    limits: PcbLimits,
82) -> Result<PcbBoardTextBox, Error> {
83    let typed = footprints::footprint_text_box_from_span(
84        source,
85        &IndexedNestedForm {
86            parent_index: 0,
87            span: span.clone(),
88        },
89        limits,
90    )?;
91    // A board box may lead with the legacy `locked` token before its text.
92    let header = bounded_scalar_values(source, span, limits.max_object_children)?;
93    let children = direct_children(source, span, limits.max_object_children, limits)?;
94    Ok(PcbBoardTextBox {
95        graphic_index,
96        text: decode::board_text_value(&header, span)?,
97        start: typed.start,
98        end: typed.end,
99        margins: typed.margins,
100        angle: typed.angle,
101        polygon_points: typed.polygon_points,
102        layer: typed.layer,
103        locked: decode::graphic_locked(source, span, &header, &children, limits)?,
104        effects: typed.effects,
105        stroke_width: typed.stroke_width,
106        stroke_kind: typed.stroke_kind,
107        border: typed.border,
108        knockout: typed.knockout,
109        render_cache_range: typed.render_cache_range,
110        uuid: typed.uuid,
111        source_range: typed.source_range,
112    })
113}
114
115/// The board plotter's border width when the source stores none (or zero).
116const TEXT_BOX_BORDER_DEFAULT_WIDTH_MM: f64 = 0.2;
117/// The wrap glyph width the board plotter uses for a zero-width font.
118const TEXT_BOX_WRAP_DEFAULT_SIZE_NM: i64 = 1_270_000;
119
120impl PcbBoardTextBox {
121    /// The box outline as stored: the rectangle's corners from `start` round
122    /// to `end`, or the polygon's own points.
123    pub fn outline(&self) -> Vec<PcbPoint> {
124        if !self.polygon_points.is_empty() {
125            return self.polygon_points.clone();
126        }
127        let (start, end) = (self.start, self.end);
128        vec![
129            start,
130            PcbPoint {
131                x: end.x,
132                y: start.y,
133            },
134            end,
135            PcbPoint {
136                x: start.x,
137                y: end.y,
138            },
139        ]
140    }
141
142    /// The box's corners in the text's own frame, as the board plotter
143    /// orders them after KiCad `PCB_TEXTBOX::GetCornersInSequence`: top-left,
144    /// top-right, bottom-right and bottom-left as the text reads.
145    pub fn frame_corners(&self) -> [PcbPoint; 4] {
146        self.corners(0.0).map(|[x, y]| PcbPoint { x, y })
147    }
148
149    /// Where the text is drawn: the frame corner its justification names,
150    /// moved in by the margins along the text's axes (the board plotter's
151    /// `GrTextBox._draw_position`). A mirrored box anchors at its other side.
152    pub fn draw_position(&self) -> PcbPoint {
153        let inflate = self
154            .stroke_width
155            .filter(|width| *width > 0.0)
156            .unwrap_or(0.0)
157            / 2.0;
158        let corners = self.corners(inflate);
159        let effects = self.effects.clone().unwrap_or_default();
160        let (mut horizontal, vertical) = justification(&effects.justify);
161        if effects.justify.iter().any(|token| token == "mirror") {
162            horizontal = -horizontal;
163        }
164        // The justified corner, edge midpoint or center of the frame.
165        let along = |a: [f64; 2], b: [f64; 2], sign: i8| {
166            let t = f64::from(sign + 1) / 2.0;
167            [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
168        };
169        let anchor = along(
170            along(corners[0], corners[1], horizontal),
171            along(corners[3], corners[2], horizontal),
172            vertical,
173        );
174        let [left, top, right, bottom] = self.margins;
175        let offset_x = inset(horizontal, left, right);
176        let offset_y = inset(vertical, top, bottom);
177        let (sin, cos) = self.angle.to_radians().sin_cos();
178        PcbPoint {
179            x: anchor[0] + offset_x * cos + offset_y * sin,
180            y: anchor[1] + offset_y * cos - offset_x * sin,
181        }
182    }
183
184    /// The text as the board plotter wraps stroke-font text-box text to the
185    /// box's column (KiCad `PCB_TEXTBOX::GetShownText`, at spaces only).
186    pub fn newstroke_wrapped_text(&self, text: &str) -> Result<String, Error> {
187        let horizontal = {
188            let angle = self.angle.rem_euclid(360.0);
189            angle.abs() <= 1e-9 || (angle - 180.0).abs() <= 1e-9
190        };
191        let [left, top, right, bottom] = self.margins;
192        let width = if horizontal {
193            (self.end.x - self.start.x).abs() - left - right
194        } else {
195            (self.end.y - self.start.y).abs() - top - bottom
196        };
197        let size_x = self.effects.as_ref().map_or_else(
198            || KiCadTextEffects::default().font.size_x,
199            |effects| effects.font.size_x,
200        );
201        let size_x_nm = match crate::plotter_ir::mm_to_nm(size_x)? {
202            0 => TEXT_BOX_WRAP_DEFAULT_SIZE_NM,
203            size => size,
204        };
205        Ok(crate::board_plotter_ir::text_wrap::wrap_text_box(
206            text,
207            width.max(0.0),
208            size_x_nm,
209        ))
210    }
211
212    /// The width the border is drawn with, or none when the box draws no
213    /// border; an absent or zero width is the board plotter's 0.2 mm.
214    pub fn border_width(&self) -> Option<f64> {
215        if self.border != Some(true) {
216            return None;
217        }
218        match self.stroke_width {
219            Some(width) if width < 0.0 => None,
220            Some(width) if width > 0.0 => Some(width),
221            _ => Some(TEXT_BOX_BORDER_DEFAULT_WIDTH_MM),
222        }
223    }
224
225    /// The drawn border in integer nanometres (right/down), as polylines:
226    /// one closed outline for a solid border, each dash of a patterned
227    /// border as its own two-point segment (each side is stroked alone).
228    pub fn border_polylines_nm(&self) -> Result<Vec<Vec<[i64; 2]>>, Error> {
229        let Some(width) = self.border_width() else {
230            return Ok(Vec::new());
231        };
232        let points = self
233            .outline()
234            .into_iter()
235            .map(|point| {
236                Ok([
237                    crate::plotter_ir::mm_to_nm(point.x)?,
238                    crate::plotter_ir::mm_to_nm(point.y)?,
239                ])
240            })
241            .collect::<Result<Vec<_>, Error>>()?;
242        let style = border_style(self.stroke_kind.as_deref())?;
243        let Some(style) = style else {
244            let mut closed = points;
245            if let Some(first) = closed.first().copied() {
246                closed.push(first);
247            }
248            return Ok(vec![closed]);
249        };
250        let width_nm = crate::plotter_ir::mm_to_nm(width)?;
251        let mut result = Vec::new();
252        for (index, start) in points.iter().enumerate() {
253            let end = points[(index + 1) % points.len()];
254            for [x1, y1, x2, y2] in crate::plotter_ir::decompose_segment(
255                start[0],
256                start[1],
257                end[0],
258                end[1],
259                width_nm,
260                style,
261                usize::MAX,
262            )? {
263                result.push(vec![[x1, y1], [x2, y2]]);
264            }
265        }
266        Ok(result)
267    }
268
269    /// The text-frame corners, a rectangle's grown by `inflate` on each side.
270    fn corners(&self, inflate: f64) -> [[f64; 2]; 4] {
271        let points = &self.polygon_points;
272        let angle = self.angle.rem_euclid(360.0);
273        let cardinal = ((angle / 90.0).round() * 90.0 - angle).abs() <= 1e-9;
274        if !points.is_empty() && !cardinal {
275            return noncardinal_corners(points, angle);
276        }
277        let extents = |values: &mut dyn Iterator<Item = f64>| {
278            values.fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), value| {
279                (low.min(value), high.max(value))
280            })
281        };
282        let ((left, right), (top, bottom)) = if points.is_empty() {
283            (
284                (self.start.x.min(self.end.x), self.start.x.max(self.end.x)),
285                (self.start.y.min(self.end.y), self.start.y.max(self.end.y)),
286            )
287        } else {
288            (
289                extents(&mut points.iter().map(|point| point.x)),
290                extents(&mut points.iter().map(|point| point.y)),
291            )
292        };
293        let (left, right, top, bottom) = (
294            left - inflate,
295            right + inflate,
296            top - inflate,
297            bottom + inflate,
298        );
299        // A cardinal angle starts the sequence that many corners back.
300        let base = [[left, top], [right, top], [right, bottom], [left, bottom]];
301        let turns = if cardinal {
302            (angle / 90.0).round() as usize % 4
303        } else {
304            0
305        };
306        std::array::from_fn(|index| base[(index + 4 - turns) % 4])
307    }
308}
309
310/// A rotated polygon box's corners, from the points with the extreme
311/// coordinates, in the order the text reads them.
312fn noncardinal_corners(points: &[PcbPoint], angle: f64) -> [[f64; 2]; 4] {
313    let pick = |better: fn(&PcbPoint, &PcbPoint) -> bool| {
314        let mut best = points[0];
315        for point in &points[1..] {
316            if better(point, &best) {
317                best = *point;
318            }
319        }
320        [best.x, best.y]
321    };
322    let min_x = pick(|a, b| a.x < b.x);
323    let max_x = pick(|a, b| a.x > b.x);
324    let min_y = pick(|a, b| a.y < b.y);
325    let max_y = pick(|a, b| a.y > b.y);
326    if angle < 90.0 {
327        [min_x, min_y, max_x, max_y]
328    } else if angle < 180.0 {
329        [max_y, min_x, min_y, max_x]
330    } else if angle < 270.0 {
331        [max_x, max_y, min_x, min_y]
332    } else {
333        [min_y, max_x, max_y, min_x]
334    }
335}
336
337/// The margin a justification moves in by along one axis: the low side's
338/// inward, the high side's back, none when centered.
339fn inset(sign: i8, low: f64, high: f64) -> f64 {
340    match sign {
341        -1 => low,
342        1 => -high,
343        _ => 0.0,
344    }
345}
346
347/// A border's stroke type as a dash pattern; solid has none.
348fn border_style(kind: Option<&str>) -> Result<Option<crate::plotter_ir::StrokeStyle>, Error> {
349    use crate::plotter_ir::StrokeStyle;
350    Ok(match kind {
351        None | Some("default" | "solid") => None,
352        Some("dash") => Some(StrokeStyle::Dash),
353        Some("dot") => Some(StrokeStyle::Dot),
354        Some("dash_dot") => Some(StrokeStyle::DashDot),
355        Some("dash_dot_dot") => Some(StrokeStyle::DashDotDot),
356        Some(_) => {
357            return Err(Error::build(
358                ErrorKind::UnexpectedToken,
359                "Unsupported text box border stroke type",
360            ));
361        }
362    })
363}
364
365/// Justify tokens as signs: -1 left/top, 0 center, 1 right/bottom.
366fn justification(justify: &[String]) -> (i8, i8) {
367    let (mut horizontal, mut vertical) = (0, 0);
368    for token in justify {
369        match token.as_str() {
370            "left" => horizontal = -1,
371            "right" => horizontal = 1,
372            "top" => vertical = -1,
373            "bottom" => vertical = 1,
374            _ => {}
375        }
376    }
377    (horizontal, vertical)
378}
379
380/// One source `gr_text_box` owner: a text box on the board, typed like a
381/// footprint text box. Coordinates remain KiCad millimetres (right/down) and
382/// the angle is the authored text angle in degrees.
383#[derive(Clone, Debug, PartialEq)]
384pub struct PcbBoardTextBox {
385    pub graphic_index: usize,
386    pub text: String,
387    /// The stored rectangle; a polygon box keeps its points' extents here.
388    pub start: PcbPoint,
389    pub end: PcbPoint,
390    /// `(margins left top right bottom)`, millimetres.
391    pub margins: [f64; 4],
392    pub angle: f64,
393    /// A box rotated off the axes is stored as its four points.
394    pub polygon_points: Vec<PcbPoint>,
395    pub layer: String,
396    pub locked: bool,
397    pub effects: Option<KiCadTextEffects>,
398    pub stroke_width: Option<f64>,
399    pub stroke_kind: Option<String>,
400    pub border: Option<bool>,
401    pub knockout: Option<bool>,
402    pub render_cache_range: Option<Range<usize>>,
403    pub uuid: Option<String>,
404    pub source_range: Range<usize>,
405}
406
407fn board_text_from_span(
408    source: &str,
409    graphic_index: usize,
410    span: &FormSpan,
411    limits: PcbLimits,
412) -> Result<PcbBoardText, Error> {
413    let header = bounded_scalar_values(source, span, limits.max_object_children)?;
414    let children = direct_children(source, span, limits.max_object_children, limits)?;
415    let at = optional_vector(
416        source,
417        &children,
418        "at",
419        [0.0; 3],
420        limits.max_object_children,
421    )?;
422    let effects =
423        footprints::text_effects_from_children(source, &children, limits)?.unwrap_or_default();
424    let (layer, knockout) = footprints::text_layer(source, &children, limits.max_object_children)?;
425    Ok(PcbBoardText {
426        graphic_index,
427        text: decode::board_text_value(&header, span)?,
428        at: PcbPoint { x: at[0], y: at[1] },
429        angle: at[2],
430        layer,
431        knockout,
432        hidden: has_flag(&header, "hide")
433            || child_bool(source, &children, "hide")?
434            || effects.hidden,
435        locked: decode::graphic_locked(source, span, &header, &children, limits)?,
436        effects,
437        render_cache_range: child(&children, "render_cache").map(|span| span.range.clone()),
438        uuid: optional_uuid(source, &children)?,
439        source_range: span.range.clone(),
440    })
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446
447    #[test]
448    fn empty_text_retains_authored_pose_effects_and_absolute_ranges() {
449        let source = r#"(kicad_pcb (version 20250114)
450          (gr_line (start 0 0) (end 1 1) (layer "F.Cu"))
451          (gr_text locked "" (at 2 3 47) (layer "B.SilkS" knockout)
452            (uuid "11111111-1111-4111-8111-111111111111")
453            (effects (font (face "Arial") (size 1.5 2) (thickness 0.2)
454              bold italic (line_spacing 1.4)) (justify right bottom mirror) hide)
455            (render_cache "stale" 0)))"#;
456        let view = PcbView::parse(source, PcbLimits::default()).unwrap();
457        let text = view.board_texts().next().unwrap().unwrap();
458        assert_eq!(text.graphic_index, 1);
459        assert_eq!(
460            (&*text.text, text.at.x, text.at.y, text.angle),
461            ("", 2., 3., 47.)
462        );
463        assert_eq!(text.layer, "B.SilkS");
464        assert!(text.hidden && text.locked && text.knockout);
465        assert_eq!(
466            (text.effects.font.size_x, text.effects.font.size_y),
467            (2., 1.5)
468        );
469        assert_eq!(text.effects.font.thickness, Some(0.2));
470        assert_eq!(text.effects.font.line_spacing, Some(1.4));
471        assert!(text.effects.font.bold && text.effects.font.italic);
472        assert_eq!(text.effects.justify, ["right", "bottom", "mirror"]);
473        assert_eq!(
474            &source[text.render_cache_range.unwrap()],
475            "(render_cache \"stale\" 0)"
476        );
477        assert!(source[text.effects.source_range.unwrap()].starts_with("(effects"));
478        assert!(source[text.source_range].starts_with("(gr_text"));
479    }
480
481    #[test]
482    fn board_text_box_keeps_its_box_frame_border_and_wrap() {
483        let source = r#"(kicad_pcb (version 20250114)
484          (gr_text "plain" (at 1 1 0) (layer "F.SilkS"))
485          (gr_text_box "two words"
486            (start 10 20) (end 22 25) (margins 1 1 1 1) (angle 90)
487            (layer "F.Cu") (uuid "11111111-1111-4111-8111-111111111111")
488            (effects (font (size 1.2 1.2) (thickness 0.18)) (justify left top))
489            (border yes) (stroke (width 0.15) (type dash)) (knockout no)))"#;
490        let view = PcbView::parse(source, PcbLimits::default()).unwrap();
491        let boxes = view
492            .board_text_boxes()
493            .collect::<Result<Vec<_>, _>>()
494            .unwrap();
495        let [text_box] = boxes.as_slice() else {
496            panic!("one board text box")
497        };
498        assert_eq!(text_box.graphic_index, 1);
499        assert_eq!(text_box.text, "two words");
500        assert_eq!(
501            (text_box.layer.as_str(), text_box.margins),
502            ("F.Cu", [1.0; 4])
503        );
504        assert_eq!(
505            (text_box.border, text_box.knockout, text_box.stroke_width),
506            (Some(true), Some(false), Some(0.15))
507        );
508        // At 90 degrees the text reads up: its top-left is the bottom-left.
509        let corners = text_box.frame_corners();
510        assert_eq!((corners[0].x, corners[0].y), (10.0, 25.0));
511        assert_eq!((corners[1].x, corners[1].y), (10.0, 20.0));
512        let at = text_box.draw_position();
513        assert!((at.x - 10.925).abs() < 1e-9 && (at.y - 24.075).abs() < 1e-9);
514        // A 5 mm tall box less its margins is 3 mm: the words wrap.
515        assert_eq!(
516            text_box.newstroke_wrapped_text("two words").unwrap(),
517            "two\nwords"
518        );
519        assert_eq!(text_box.border_width(), Some(0.15));
520        let dashes = text_box.border_polylines_nm().unwrap();
521        assert!(dashes.len() > 4 && dashes.iter().all(|dash| dash.len() == 2));
522        let solid = PcbBoardTextBox {
523            stroke_kind: Some("solid".into()),
524            ..text_box.clone()
525        };
526        assert_eq!(
527            solid.border_polylines_nm().unwrap(),
528            vec![vec![
529                [10_000_000, 20_000_000],
530                [22_000_000, 20_000_000],
531                [22_000_000, 25_000_000],
532                [10_000_000, 25_000_000],
533                [10_000_000, 20_000_000],
534            ]]
535        );
536        let unbordered = PcbBoardTextBox {
537            border: None,
538            ..text_box.clone()
539        };
540        assert!(unbordered.border_polylines_nm().unwrap().is_empty());
541        assert!(view.board_texts().all(|text| text.unwrap().text == "plain"));
542    }
543
544    #[test]
545    fn board_text_defaults_selection_and_limits_follow_source_reader() {
546        let source = r#"(kicad_pcb (version 20250114) (gr_text ""))"#;
547        let view = PcbView::parse(source, PcbLimits::default()).unwrap();
548        let text = view.board_texts().next().unwrap().unwrap();
549        assert_eq!((text.at.x, text.at.y, text.angle), (0., 0., 0.));
550        assert_eq!(text.effects, KiCadTextEffects::default());
551        assert!(!text.hidden && !text.locked && text.render_cache_range.is_none());
552        let view =
553            PcbView::parse_selected(source, PcbLimits::default(), PcbSelection::none()).unwrap();
554        assert!(view.board_texts().next().is_none());
555        let source = r#"(kicad_pcb (version 20250114)
556          (gr_text "" (effects (font (size 1 1)) (justify left right top bottom))))"#;
557        let limits = PcbLimits {
558            max_text_justify_tokens: 2,
559            ..Default::default()
560        };
561        let view = PcbView::parse(source, limits).unwrap();
562        assert!(view.board_texts().next().unwrap().is_err());
563    }
564}