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

kicad_monkey_core/
text_linebreak.rs

1//! Bounded KiCad outline-font text-box line breaking.
2
3use crate::text_block_layout::{
4    AggregateWork, LineBuildInputs, TextBlockLayoutRequest, build_line, shaping_metadata_bytes,
5    validate_request,
6};
7use crate::text_contours::HintedTextContourSession;
8use crate::{TextContourError, TextContourErrorKind};
9use std::ops::Range;
10
11/// Insert KiCad-compatible outline-font text-box line breaks with one bounded
12/// hinted face session. Markup groups remain atomic words, normal text keeps
13/// one trailing space per token, and pending spaces trigger wrapping exactly
14/// as `KIFONT::FONT::LinebreakText()` does.
15pub fn linebreak_text_block_hinted_a0(
16    font_bytes: &[u8],
17    request: TextBlockLayoutRequest<'_>,
18    column_width: f64,
19) -> Result<String, TextContourError> {
20    validate_request(request)?;
21    if !column_width.is_finite() {
22        return Err(invalid("$.column_width", "column width must be finite"));
23    }
24    if column_width <= 0.0 || request.shaping.text.is_empty() {
25        return bounded_linebreak_output(request.shaping.text.to_owned());
26    }
27    if !request.shaping.text.contains(' ') {
28        return bounded_linebreak_output(request.shaping.text.to_owned());
29    }
30
31    let session = HintedTextContourSession::new(font_bytes, request.shaping)?;
32    let run_metadata_bytes = shaping_metadata_bytes(request.shaping)?;
33    let inputs = LineBuildInputs {
34        session: &session,
35        request,
36        run_metadata_bytes,
37    };
38    let mut state = LinebreakWork {
39        markup_budget: 0,
40        layout: AggregateWork::default(),
41        token_count: 0,
42        output: String::with_capacity(request.shaping.text.len().min(4096)),
43    };
44
45    for line_span in request.shaping.text.split_inclusive('\n') {
46        let line_start = request.shaping.text[..].as_ptr() as usize;
47        let span_start = line_span.as_ptr() as usize - line_start;
48        let has_newline = line_span.ends_with('\n');
49        let line_end = span_start + line_span.len() - usize::from(has_newline);
50        linebreak_one_line(
51            &request.shaping.text,
52            span_start..line_end,
53            has_newline,
54            &inputs,
55            column_width,
56            &mut state,
57        )?;
58    }
59    bounded_linebreak_output(state.output)
60}
61
62struct LinebreakWork {
63    markup_budget: usize,
64    layout: AggregateWork,
65    token_count: usize,
66    output: String,
67}
68
69fn linebreak_one_line(
70    source: &str,
71    line: Range<usize>,
72    has_newline: bool,
73    inputs: &LineBuildInputs<'_>,
74    column_width: f64,
75    state: &mut LinebreakWork,
76) -> Result<(), TextContourError> {
77    let tokens = linebreak_tokens(source, line, &mut state.token_count)?;
78    let space_span = tokens
79        .iter()
80        .flat_map(|token| token.parts.iter())
81        .find_map(|part| {
82            source[part.clone()]
83                .find(' ')
84                .map(|offset| (part.start + offset)..(part.start + offset + 1))
85        });
86    let space_width = match space_span {
87        Some(span) => measure_line_span(inputs, span, &mut state.markup_budget, &mut state.layout)?,
88        None => 0.0,
89    };
90    let mut line_width = 0.0;
91    let mut pending_spaces = 0usize;
92    let mut bury_mode = false;
93    for token in tokens {
94        let word_width = measure_linebreak_token(source, &token, inputs, state)?;
95        let pending_width = pending_spaces as f64 * space_width;
96        let overflow =
97            line_width + pending_width + word_width > column_width - inputs.request.stroke_width;
98        if overflow && pending_spaces > 0 {
99            push_linebreak_text(&mut state.output, "\n")?;
100            line_width = 0.0;
101            pending_spaces = 0;
102            bury_mode = true;
103        }
104        if token.is_space_only(source) {
105            pending_spaces = pending_spaces
106                .checked_add(1)
107                .ok_or_else(|| resource("$.tokens", "pending space count overflowed"))?;
108            continue;
109        }
110        if bury_mode {
111            bury_mode = false;
112        } else {
113            for _ in 0..pending_spaces {
114                push_linebreak_text(&mut state.output, " ")?;
115            }
116            line_width += pending_spaces as f64 * space_width;
117        }
118        let trailing_space = token.ends_with_space(source);
119        append_linebreak_token(source, &token, trailing_space, state)?;
120        pending_spaces = usize::from(trailing_space);
121        line_width += word_width;
122    }
123    if has_newline {
124        push_linebreak_text(&mut state.output, "\n")?;
125    }
126    Ok(())
127}
128
129fn measure_linebreak_token(
130    source: &str,
131    token: &LinebreakToken,
132    inputs: &LineBuildInputs<'_>,
133    state: &mut LinebreakWork,
134) -> Result<f64, TextContourError> {
135    token.parts.iter().try_fold(0.0, |width, part| {
136        let measured = trim_one_trailing_space(source, part.clone());
137        Ok(width
138            + measure_line_span(
139                inputs,
140                measured,
141                &mut state.markup_budget,
142                &mut state.layout,
143            )?)
144    })
145}
146
147fn append_linebreak_token(
148    source: &str,
149    token: &LinebreakToken,
150    trailing_space: bool,
151    state: &mut LinebreakWork,
152) -> Result<(), TextContourError> {
153    for part in &token.parts {
154        let value = &source[part.clone()];
155        let value = if trailing_space && part == token.parts.last().unwrap() {
156            value.strip_suffix(' ').unwrap_or(value)
157        } else {
158            value
159        };
160        push_linebreak_text(&mut state.output, value)?;
161    }
162    Ok(())
163}
164
165#[derive(Debug)]
166struct LinebreakToken {
167    parts: Vec<Range<usize>>,
168}
169
170impl LinebreakToken {
171    fn ends_with_space(&self, source: &str) -> bool {
172        self.parts
173            .last()
174            .is_some_and(|part| source[part.clone()].ends_with(' '))
175    }
176
177    fn is_space_only(&self, source: &str) -> bool {
178        self.parts.len() == 1 && source[self.parts[0].clone()] == *" "
179    }
180}
181
182fn linebreak_tokens(
183    source: &str,
184    line: Range<usize>,
185    token_count: &mut usize,
186) -> Result<Vec<LinebreakToken>, TextContourError> {
187    let mut tokens: Vec<LinebreakToken> = Vec::new();
188    let bytes = source.as_bytes();
189    let mut index = line.start;
190    while index < line.end {
191        let part = next_linebreak_part(bytes, line.end, &mut index);
192        *token_count += 1;
193        let joins_previous = tokens
194            .last()
195            .is_some_and(|token| !token.ends_with_space(source));
196        if joins_previous {
197            tokens.last_mut().unwrap().parts.push(part);
198        } else {
199            tokens.push(LinebreakToken { parts: vec![part] });
200        }
201    }
202    Ok(tokens)
203}
204
205fn next_linebreak_part(bytes: &[u8], line_end: usize, index: &mut usize) -> Range<usize> {
206    if markup_group_starts(bytes, *index) {
207        markup_group_part(bytes, line_end, index)
208    } else {
209        plain_linebreak_part(bytes, line_end, index)
210    }
211}
212
213fn markup_group_starts(bytes: &[u8], index: usize) -> bool {
214    matches!(bytes.get(index), Some(b'_' | b'^' | b'~')) && bytes.get(index + 1) == Some(&b'{')
215}
216
217fn markup_group_part(bytes: &[u8], line_end: usize, index: &mut usize) -> Range<usize> {
218    let start = *index;
219    *index += 2;
220    let mut depth = 1usize;
221    while *index < line_end && depth > 0 {
222        if markup_group_starts(bytes, *index) {
223            depth += 1;
224            *index += 2;
225        } else {
226            depth -= usize::from(bytes[*index] == b'}');
227            *index += 1;
228        }
229    }
230    start..*index
231}
232
233fn plain_linebreak_part(bytes: &[u8], line_end: usize, index: &mut usize) -> Range<usize> {
234    let start = *index;
235    if bytes[*index] == b' ' {
236        *index += 1;
237        return start..*index;
238    }
239    while *index < line_end && bytes[*index] != b' ' && !markup_group_starts(bytes, *index) {
240        *index += 1;
241    }
242    if *index < line_end && bytes[*index] == b' ' {
243        *index += 1;
244    }
245    start..*index
246}
247
248fn trim_one_trailing_space(source: &str, span: Range<usize>) -> Range<usize> {
249    if span.len() > 1 && source[span.clone()].ends_with(' ') {
250        span.start..span.end - 1
251    } else {
252        span
253    }
254}
255
256fn measure_line_span(
257    inputs: &LineBuildInputs<'_>,
258    span: Range<usize>,
259    markup_budget: &mut usize,
260    work: &mut AggregateWork,
261) -> Result<f64, TextContourError> {
262    Ok(build_line(inputs, span, markup_budget, work)?.width)
263}
264
265fn push_linebreak_text(output: &mut String, value: &str) -> Result<(), TextContourError> {
266    output
267        .len()
268        .checked_add(value.len())
269        .ok_or_else(|| resource("$.output", "linebreak output byte limit exceeded"))?;
270    output.push_str(value);
271    Ok(())
272}
273
274fn bounded_linebreak_output(output: String) -> Result<String, TextContourError> {
275    Ok(output)
276}
277
278fn invalid(path: &'static str, message: &'static str) -> TextContourError {
279    TextContourError {
280        kind: TextContourErrorKind::InvalidInput,
281        path: path.to_owned(),
282        message,
283    }
284}
285
286fn resource(path: &'static str, message: &'static str) -> TextContourError {
287    TextContourError {
288        kind: TextContourErrorKind::ResourceLimit,
289        path: path.to_owned(),
290        message,
291    }
292}