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

cad_text_realization/
text_box_wrap.rs

1//! Streaming Newstroke text-box wrapping, shared by PCB and schematic text
2//! boxes: KiCad wraps both through `FONT::LinebreakText`.
3
4use crate::stroke_width_units;
5
6#[derive(Default)]
7struct MarkupWidthState {
8    stack: Vec<bool>,
9    styled_depth: usize,
10    /// Advance in 1/105 font units: normal deltas use x5, styled x4.
11    width_units: u64,
12}
13
14impl MarkupWidthState {
15    fn reset(&mut self) {
16        self.stack.clear();
17        self.styled_depth = 0;
18        self.width_units = 0;
19    }
20
21    fn feed(&mut self, text: &str) {
22        let mut chars = text.chars().peekable();
23        while let Some(ch) = chars.next() {
24            if matches!(ch, '_' | '^' | '~') && chars.peek() == Some(&'{') {
25                let styled = matches!(ch, '_' | '^');
26                self.stack.push(styled);
27                self.styled_depth += usize::from(styled);
28                chars.next();
29                continue;
30            }
31            if ch == '}'
32                && let Some(styled) = self.stack.pop()
33            {
34                self.styled_depth -= usize::from(styled);
35                continue;
36            }
37            let Some(units) = stroke_width_units(ch) else {
38                continue;
39            };
40            let multiplier = if self.styled_depth > 0 { 4 } else { 5 };
41            self.width_units = self
42                .width_units
43                .saturating_add(u64::from(units) * multiplier);
44        }
45    }
46}
47
48/// Break KiCad-markup `text` into lines no wider than `max_width_mm` at glyph
49/// width `size_x_nm`, at spaces only (Python `_wrap_text_box_lines`). A word
50/// wider than the box keeps its own line. Each byte is appended and measured at
51/// most twice (once more when it triggers a wrap), so a long paragraph cannot
52/// degrade into repeated whole-prefix measurement.
53pub fn wrap_stroke_text_box(text: &str, max_width_mm: f64, size_x_nm: i64) -> String {
54    if max_width_mm <= 0.0 || !text.contains(' ') {
55        return text.to_owned();
56    }
57    let mut lines = Vec::new();
58    for paragraph in text.split('\n') {
59        let mut current = String::new();
60        let mut state = MarkupWidthState::default();
61        for word in paragraph.split(' ') {
62            let previous_len = current.len();
63            if !current.is_empty() {
64                current.push(' ');
65                state.feed(" ");
66            }
67            current.push_str(word);
68            state.feed(word);
69            let scaled_width = state.width_units as f64 * size_x_nm as f64;
70            if previous_len > 0 && scaled_width > max_width_mm * 105_000_000.0 {
71                current.truncate(previous_len);
72                lines.push(std::mem::take(&mut current));
73                state.reset();
74                current.push_str(word);
75                state.feed(word);
76            }
77        }
78        lines.push(current);
79    }
80    lines.join("\n")
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn width_table_and_streaming_wrapper_match_python_edges() {
89        let width = |character: char| stroke_width_units(character).unwrap_or(0);
90        assert_eq!(width('A'), 18);
91        assert_eq!(width(' '), 16);
92        assert_eq!(width('\u{03a9}'), 24);
93        assert_eq!(width('\u{2bff}'), 24);
94
95        let wrap = wrap_stroke_text_box;
96        assert_eq!(wrap("A A", 5.2, 2_100_000), "A A");
97        assert_eq!(wrap("A A", 5.19, 2_100_000), "A\nA");
98        assert_eq!(wrap("oversized", 0.01, 1_270_000), "oversized");
99        assert_eq!(wrap("A  A ", 1.8, 1_270_000), "A\nA\n");
100        assert_eq!(wrap("A _{A A}", 7.0, 2_100_000), "A _{A\nA}");
101        assert_eq!(wrap("A A", 3.15, 1_270_000), "A A");
102        assert_eq!(wrap("A A", 3.13, 1_270_000), "A\nA");
103        assert_eq!(wrap("A \u{4e2d} A", 4.2, 1_270_000), "A \u{4e2d} A");
104    }
105}