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

cad_text_realization/
multiline.rs

1//! PCB stroke-text block placement over the existing single-line engine.
2//!
3//! Behavioural authority: KiCad caf7377e9cb6fa1535ec3596dcb8c99bf44a996e,
4//! EDA_TEXT::GetLinePositions and BRDITEMS_PLOTTER::PlotText. Font pitch is
5//! METRICS::Default().m_InterlinePitch * STROKE_FONT's legacy adjustment.
6//! This does not change the single-line API or infer custom layout policies.
7
8use crate::*;
9
10const PCB_IU_PER_MM: f64 = 1_000_000.;
11const PCB_INT_LIMIT: i64 = i32::MAX as i64 - 10;
12
13fn invalid(message: &'static str) -> StrokeTextError {
14    StrokeTextError {
15        kind: StrokeTextErrorKind::InvalidInput,
16        message,
17    }
18}
19
20pub(super) fn round_iu(value: f64) -> Result<i64, StrokeTextError> {
21    if !value.is_finite() || value.abs() > i32::MAX as f64 {
22        return Err(invalid(
23            "PCB multiline coordinate exceeds defined Source integer arithmetic",
24        ));
25    }
26    // llround's tie rule, without adding 0.5 to an already rounded float.
27    let floor = value.abs().floor();
28    Ok((floor as i64 + i64::from(value.abs() - floor >= 0.5)) * if value < 0. { -1 } else { 1 })
29}
30
31pub(super) fn source_iu(mm: f64) -> Result<i64, StrokeTextError> {
32    if !mm.is_finite() {
33        return Err(invalid("PCB multiline coordinate is nonfinite"));
34    }
35    round_iu((mm * PCB_IU_PER_MM).clamp(-(PCB_INT_LIMIT as f64), PCB_INT_LIMIT as f64))
36}
37
38fn checked(value: i64) -> Result<i64, StrokeTextError> {
39    i32::try_from(value)
40        .map(i64::from)
41        .map_err(|_| invalid("PCB multiline coordinate exceeds defined Source integer arithmetic"))
42}
43
44fn rotate(point: [i64; 2], angle: f64) -> Result<[i64; 2], StrokeTextError> {
45    if !angle.is_finite() {
46        return Err(invalid("PCB multiline angle is nonfinite"));
47    }
48    let angle = angle.rem_euclid(360.);
49    let [x, y] = point;
50    Ok(match angle {
51        0. => point,
52        90. => [y, checked(-x)?],
53        180. => [checked(-x)?, checked(-y)?],
54        270. => [checked(-y)?, x],
55        _ => {
56            let (s, c) = angle.to_radians().sin_cos();
57            [
58                round_iu(x as f64 * c + y as f64 * s)?,
59                round_iu(y as f64 * c - x as f64 * s)?,
60            ]
61        }
62    })
63}
64
65fn baseline(
66    request: StrokeTextRequest<'_>,
67    line_count: usize,
68    line_spacing: Option<f64>,
69) -> Result<([i64; 2], [i64; 2]), StrokeTextError> {
70    let x = source_iu(request.position_x_mm)?;
71    let y = source_iu(request.position_y_mm)?;
72    let height = source_iu(request.size_y_mm)?;
73    // A line spacing scales the font's pitch (KiCad `TEXT_ATTRIBUTES::
74    // m_LineSpacing`, `FONT::getLinePositions`, common/font/font.cpp:192).
75    let interline = match line_spacing {
76        None => round_iu((height as f64 * 1.68) * 0.9583)?,
77        Some(spacing) => round_iu((height as f64 * 1.68) * 0.9583 * spacing)?,
78    };
79    let span = checked(
80        i64::try_from(line_count.saturating_sub(1))
81            .ok()
82            .and_then(|count| count.checked_mul(interline))
83            .ok_or_else(|| invalid("PCB multiline baseline span overflow"))?,
84    )?;
85    let offset = match request.vertical_alignment {
86        TextVerticalAlignment::Top => 0,
87        TextVerticalAlignment::Center => -span / 2,
88        TextVerticalAlignment::Bottom => -span,
89    };
90    // Source first forms the absolute unrotated point, then rotates about its
91    // actual text origin. Guard that intermediate too, not only its result.
92    checked(y + offset)?;
93    let shifted = rotate([0, offset], request.angle_degrees)?;
94    let first = [checked(x + shifted[0])?, checked(y + shifted[1])?];
95    Ok((first, rotate([0, interline], request.angle_degrees)?))
96}
97
98/// Realize a PCB multiline block using Source integer baseline placement.
99///
100/// Literal newlines delimit ordered lines, including a trailing empty line.
101/// Each line keeps the supplied Source horizontal and vertical justification;
102/// mirroring, angle, style and automatic width remain owned by the glyph engine.
103/// Width fields report the greatest per-line width, while bounds/point
104/// counts cover the complete block. CR is an ordinary glyph
105/// under the pinned newline-only Source split and may remain unqualified.
106pub fn realize_stroke_text_multiline_a0(
107    request: StrokeTextRequest<'_>,
108) -> Result<StrokeTextOutput, StrokeTextError> {
109    realize_stroke_text_multiline_profile_a0(request, None, StrokeTextProfile::default())
110}
111
112/// [`realize_stroke_text_multiline_a0`] with the font's line pitch scaled by
113/// `line_spacing` (a positive, finite multiplier; 1 is the font's own pitch).
114pub fn realize_stroke_text_multiline_spaced_a0(
115    request: StrokeTextRequest<'_>,
116    line_spacing: f64,
117) -> Result<StrokeTextOutput, StrokeTextError> {
118    realize_stroke_text_multiline_profile_a0(
119        request,
120        Some(line_spacing),
121        StrokeTextProfile::default(),
122    )
123}
124
125/// [`realize_stroke_text_multiline_a0`] with the font's line pitch scaled by
126/// `line_spacing` when one is given (as
127/// [`realize_stroke_text_multiline_spaced_a0`]), following `profile`'s rules.
128pub fn realize_stroke_text_multiline_profile_a0(
129    request: StrokeTextRequest<'_>,
130    line_spacing: Option<f64>,
131    profile: StrokeTextProfile,
132) -> Result<StrokeTextOutput, StrokeTextError> {
133    if line_spacing.is_some_and(|spacing| !spacing.is_finite() || spacing <= 0.) {
134        return Err(invalid(
135            "multiline line spacing must be positive and finite",
136        ));
137    }
138    validate_request(request)?;
139    if request.text.is_empty() {
140        return realize_stroke_text_profile_a0(request, profile);
141    }
142    let request = StrokeTextRequest {
143        size_x_mm: source_iu(request.size_x_mm)? as f64 / PCB_IU_PER_MM,
144        size_y_mm: source_iu(request.size_y_mm)? as f64 / PCB_IU_PER_MM,
145        ..request
146    };
147    if request.size_x_mm <= 0. || request.size_y_mm <= 0. {
148        return Err(invalid(
149            "PCB multiline text size must be positive after Source rounding",
150        ));
151    }
152    let count = request.text.split('\n').count();
153    let (mut position, step) = baseline(request, count, line_spacing)?;
154    let mut result = StrokeTextOutput {
155        polylines: Vec::new(),
156        bounds_mm: None,
157        advance_width_mm: 0.,
158        alignment_width_mm: 0.,
159        effective_stroke_width_mm: effective_stroke_width(request),
160        missing_glyphs: 0,
161        markup_nodes: 0,
162        point_count: 0,
163    };
164    for (index, line) in request.text.split('\n').enumerate() {
165        let output = realize_stroke_text_pcb_line(
166            StrokeTextRequest {
167                text: line,
168                position_x_mm: position[0] as f64 / PCB_IU_PER_MM,
169                position_y_mm: position[1] as f64 / PCB_IU_PER_MM,
170                ..request
171            },
172            profile,
173        )?;
174        if let Some([a, b, c, d]) = output.bounds_mm {
175            result.bounds_mm = Some(match result.bounds_mm {
176                Some([x, y, z, w]) => [x.min(a), y.min(b), z.max(c), w.max(d)],
177                None => [a, b, c, d],
178            });
179        }
180        result.advance_width_mm = result.advance_width_mm.max(output.advance_width_mm);
181        result.alignment_width_mm = result.alignment_width_mm.max(output.alignment_width_mm);
182        result.markup_nodes += output.markup_nodes;
183        result.point_count += output.point_count;
184        result.missing_glyphs += output.missing_glyphs;
185        result.polylines.extend(output.polylines);
186        if index + 1 < count {
187            position = [
188                checked(position[0] + step[0])?,
189                checked(position[1] + step[1])?,
190            ];
191        }
192    }
193    Ok(result)
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    fn request(text: &str) -> StrokeTextRequest<'_> {
200        StrokeTextRequest {
201            text,
202            position_x_mm: 1.,
203            position_y_mm: 2.,
204            size_x_mm: 1.,
205            size_y_mm: 1.,
206            angle_degrees: 0.,
207            horizontal_alignment: TextHorizontalAlignment::Left,
208            vertical_alignment: TextVerticalAlignment::Center,
209            mirrored: false,
210            italic: false,
211            bold: false,
212            stroke_width_mm: Some(0.15),
213        }
214    }
215
216    #[test]
217    fn baseline_positions_match_all_copied_pinned_cpp_vectors() {
218        for row in include_str!("../tests/pcb_multiline_line_positions.txt").lines() {
219            let (input, expected) = row.split_once('|').unwrap();
220            let input = input
221                .split(',')
222                .map(|value| value.parse::<f64>().unwrap())
223                .collect::<Vec<_>>();
224            let mut req = request("unused");
225            req.position_x_mm = input[0] / 1e6;
226            req.position_y_mm = input[1] / 1e6;
227            req.size_y_mm = input[2] / 1e6;
228            req.vertical_alignment = match input[4] as i64 {
229                0 => TextVerticalAlignment::Top,
230                1 => TextVerticalAlignment::Center,
231                _ => TextVerticalAlignment::Bottom,
232            };
233            req.angle_degrees = input[5];
234            let count = input[3] as usize;
235            let (mut position, step) = baseline(req, count, None).unwrap();
236            let mut actual = Vec::new();
237            for index in 0..count {
238                actual.push(position);
239                if index + 1 < count {
240                    position = [
241                        checked(position[0] + step[0]).unwrap(),
242                        checked(position[1] + step[1]).unwrap(),
243                    ];
244                }
245            }
246            let expected = expected
247                .split(';')
248                .map(|point| {
249                    let mut values = point.split(',').map(|value| value.parse::<i64>().unwrap());
250                    [values.next().unwrap(), values.next().unwrap()]
251                })
252                .collect::<Vec<_>>();
253            assert_eq!(actual, expected, "{input:?}");
254        }
255    }
256
257    #[test]
258    fn empty_lines_and_trailing_newlines_affect_baselines_without_missing_glyph_fallback() {
259        let block = realize_stroke_text_multiline_a0(request("A\n\nB\n")).unwrap();
260        assert_eq!(block.missing_glyphs, 0);
261        let (positions, step) = baseline(request("unused"), 4, None).unwrap();
262        // A block line is laid out as pcbnew plots it (pen clamp, justify
263        // inset): the single-line plot realizer at the line's baseline.
264        let first = realize_stroke_text_plot_a0(StrokeTextRequest {
265            text: "A",
266            position_x_mm: positions[0] as f64 / 1e6,
267            position_y_mm: positions[1] as f64 / 1e6,
268            ..request("A")
269        })
270        .unwrap();
271        assert_eq!(&block.polylines[..first.polylines.len()], first.polylines);
272        assert!(step[1] > 0);
273        assert!(
274            realize_stroke_text_a0(request("A\nB"))
275                .unwrap()
276                .missing_glyphs
277                > 0
278        );
279    }
280
281    #[test]
282    fn plotted_lines_sit_where_kicad_font_line_positions_put_them() {
283        // FONT::getLinePositions: the line origin is the anchor + size -
284        // 0.052 pen, less the line height 1.17 size for bottom-justified text
285        // (half for centred). kicad-cli 10.0.5 plots EEZ DCP405plus's
286        // 0.9144/0.1016 mm bottom-justified layer numbers there, 0.119 mm
287        // (0.1248 size + 0.052 pen) above the cap-height rule's line.
288        let top_of = |vertical, size: f64, pen: f64| {
289            realize_stroke_text_plot_a0(StrokeTextRequest {
290                vertical_alignment: vertical,
291                size_x_mm: size,
292                size_y_mm: size,
293                stroke_width_mm: Some(pen),
294                ..request("H")
295            })
296            .unwrap()
297            .bounds_mm
298            .unwrap()[1]
299        };
300        let close = |left: f64, right: f64| (left - right).abs() < 1e-9;
301        let (size, pen) = (1.5, 0.3);
302        let top = top_of(TextVerticalAlignment::Top, size, pen);
303        assert!(close(
304            top - top_of(TextVerticalAlignment::Center, size, pen),
305            1.17 * size / 2.0
306        ));
307        assert!(close(
308            top - top_of(TextVerticalAlignment::Bottom, size, pen),
309            1.17 * size
310        ));
311        assert!(close(
312            top_of(TextVerticalAlignment::Top, size, 0.2) - top,
313            0.052 * (pen - 0.2)
314        ));
315        // A block's first line is the single-line rule at the block's first
316        // baseline.
317        let mut block = request("A\nB");
318        block.vertical_alignment = TextVerticalAlignment::Bottom;
319        let (positions, _) = baseline(block, 2, None).unwrap();
320        let line = realize_stroke_text_plot_a0(StrokeTextRequest {
321            text: "A",
322            position_x_mm: positions[0] as f64 / 1e6,
323            position_y_mm: positions[1] as f64 / 1e6,
324            ..block
325        })
326        .unwrap();
327        let realized = realize_stroke_text_multiline_a0(block).unwrap();
328        assert_eq!(&realized.polylines[..line.polylines.len()], line.polylines);
329    }
330
331    #[test]
332    fn source_rounding_clamp_and_undefined_integer_intermediates_are_explicit() {
333        assert_eq!(round_iu(f64::from_bits(0.5f64.to_bits() - 1)).unwrap(), 0);
334        assert_eq!(round_iu(0.5).unwrap(), 1);
335        assert_eq!(round_iu(-0.5).unwrap(), -1);
336        assert_eq!(source_iu(1e100).unwrap(), PCB_INT_LIMIT);
337        let mut request = request("A\nB");
338        request.position_y_mm = -2147.483637;
339        request.vertical_alignment = TextVerticalAlignment::Bottom;
340        assert!(realize_stroke_text_multiline_a0(request).is_err());
341        request.position_y_mm = 0.;
342        request.size_y_mm = f64::NAN;
343        assert!(realize_stroke_text_multiline_a0(request).is_err());
344    }
345
346    #[test]
347    fn tab_cursor_and_column_match_all_pinned_cpp_trajectories() {
348        for row in include_str!("../tests/pcb_tab_cursor.txt").lines() {
349            let fields = row.split('|').collect::<Vec<_>>();
350            let origin = fields[0].parse::<i64>().unwrap();
351            let size = fields[1].parse::<i64>().unwrap();
352            let scale = fields[3].parse::<f64>().unwrap();
353            let mut cursor = origin as f64 / 1e6;
354            let mut column = 0;
355            let expected = fields[5]
356                .split_whitespace()
357                .map(|point| {
358                    let values = point
359                        .split(',')
360                        .map(|value| value.parse::<i64>().unwrap())
361                        .collect::<Vec<_>>();
362                    [values[0], values[1]]
363                })
364                .collect::<Vec<_>>();
365            for (index, token) in fields[4].split(',').enumerate() {
366                if token == "T" {
367                    cursor =
368                        pcb_tab_cursor(origin as f64 / 1e6, cursor, size as f64 / 1e6, &mut column)
369                            .unwrap();
370                } else {
371                    cursor +=
372                        pcb_advance(token.parse::<f64>().unwrap() * size as f64 / 1e6 * scale)
373                            .unwrap();
374                }
375                column += 1;
376                assert_eq!(
377                    [round_iu(cursor * 1e6).unwrap(), column as i64],
378                    expected[index],
379                    "{row}"
380                );
381            }
382        }
383    }
384
385    #[test]
386    fn new_pcb_operation_handles_tabs_while_single_line_api_keeps_fallback_behavior() {
387        let value = request("W\t\tM\nA");
388        let block = realize_stroke_text_multiline_a0(value).unwrap();
389        assert_eq!(block.missing_glyphs, 0);
390        assert!(block.point_count > 0);
391        assert!(realize_stroke_text_a0(value).unwrap().missing_glyphs >= 3);
392    }
393
394    #[test]
395    fn markup_runs_reset_source_tab_columns_at_their_actual_cursor() {
396        // Copied Source GetTextAsGlyphs cursor oracle, called at each markup
397        // run: A=857143 IU, B=1000000 IU (800000 for super/subscript),
398        // followed by a fresh tab/C run. Original C++ outputs are retained in
399        // the pinned Source evidence packet; no whole-string column counting.
400        for (text, expected) in [
401            ("A~{B}\tC", 6_619_047),
402            ("A^{B}\tC", 6_419_047),
403            ("A_{B}\tC", 6_419_047),
404        ] {
405            let output = realize_stroke_text_multiline_a0(request(text)).unwrap();
406            assert_eq!(round_iu(output.advance_width_mm * 1e6).unwrap(), expected);
407            assert_eq!(round_iu(output.alignment_width_mm * 1e6).unwrap(), expected);
408            assert_eq!(output.missing_glyphs, 0);
409            assert!(output.point_count > 0);
410        }
411    }
412}