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

cad_text_realization/
lib.rs

1//! Bounded, deterministic CAD text realization: OpenType shaping, glyph
2//! outlines, contour layout and topology, and stroke-font polylines.
3//!
4//! [`contract`] is the public text contract (shaping input, shaped glyphs,
5//! outline commands and their primitives). The built-in stroke font is the
6//! Newstroke glyph table; its layout follows the profile KiCad's renderer
7//! uses (provenance noted at each rule).
8
9pub mod contract;
10mod face_metrics;
11mod fake_style;
12pub mod font_container;
13mod multiline;
14pub use multiline::{
15    realize_stroke_text_multiline_a0, realize_stroke_text_multiline_profile_a0,
16    realize_stroke_text_multiline_spaced_a0,
17};
18pub mod font_outline;
19mod opentype;
20mod stroke_font;
21pub mod text_bezier;
22mod text_box_wrap;
23pub mod text_contours;
24pub mod text_layout;
25mod text_markup;
26pub mod text_shaping;
27pub mod text_topology;
28pub use text_box_wrap::wrap_stroke_text_box;
29
30pub use contract::{
31    DefaultIgnorablePolicy, FiniteFloat, FiniteFloatError, FontVariationCoordinate, OpenTypeTag,
32    OutlineClose, OutlineCommand, OutlineCurveTo, OutlineLineTo, OutlineMoveTo, OutlineQuadTo,
33    SafeInteger, SafeIntegerError, Sha256Hex, ShapedGlyph, ShapingBufferProperties,
34    ShapingClusterLevel, ShapingFeature, ShapingInput, StableTextId, StableTextIdError,
35    TextDirection, ValidationError, validate_font_sha256, validate_font_variations,
36    validate_shaping_input,
37};
38
39pub use face_metrics::windows_cell_em;
40pub use font_outline::{
41    FONT_OUTLINE_ENGINE, FontOutlineError, FontOutlineErrorKind, FontOutlineFace,
42    FontOutlineFaceRequest, FontOutlineOutput, FontOutlineRequest, HINTED_FONT_OUTLINE_ENGINE,
43    HintedFontOutlineFace, extract_font_outline_a0,
44};
45pub use text_bezier::{
46    TextBezierError, TextBezierErrorKind, TextBezierOutput, TextPoint, flatten_cubic_bezier,
47    flatten_quadratic_bezier,
48};
49pub use text_contours::{
50    OUTLINE_FACE_SCALER, SUBSCRIPT_FACE_SCALER, SUBSCRIPT_SUPERSCRIPT_SIZE_RATIO,
51    SUBSCRIPT_VERTICAL_OFFSET_RATIO, SUPERSCRIPT_VERTICAL_OFFSET_RATIO, TEXT_BEZIER_ERROR,
52    TextContour, TextContourError, TextContourErrorKind, TextContourOutput, TextContourRequest,
53    TextContourSession, shape_text_contours_a0, shape_text_contours_hinted_a0,
54};
55pub use text_layout::{
56    TEXT_HEIGHT_FUDGE_FACTOR, TextLayoutRequest, layout_single_line_text_a0,
57    layout_single_line_text_hinted_a0,
58};
59pub use text_shaping::{
60    TEXT_SHAPING_ENGINE, TextShapingError, TextShapingErrorKind, TextShapingOutput, shape_text_a0,
61};
62pub use text_topology::{
63    TextContourRegion, TextTopologyOutput, fracture_text_contours_a0, group_text_contours_a0,
64};
65
66pub use opentype::{
67    OPENTYPE_REALIZATION_ENGINE, OpenTypeContour, OpenTypeError, OpenTypeErrorKind, OpenTypeGlyph,
68    OpenTypeOutput, OpenTypePoint, OpenTypeRegion, OpenTypeRequest, realize_opentype,
69};
70
71use crate::stroke_font::{NEWSTROKE_GLYPH_DATA, NEWSTROKE_GLYPH_OFFSETS, NEWSTROKE_WIDTH_UNITS};
72use std::fmt;
73
74#[doc(hidden)]
75pub use crate::text_markup::{
76    TextMarkupError, TextMarkupErrorKind, TextMarkupMarker, TextMarkupNode, parse_text_markup,
77};
78
79/// Return the built-in stroke font's advance-width units for one supported codepoint.
80#[doc(hidden)]
81pub fn stroke_width_units(character: char) -> Option<u8> {
82    let index = (character as usize).checked_sub(0x20)?;
83    NEWSTROKE_WIDTH_UNITS.get(index).copied()
84}
85
86const STROKE_SCALE: f64 = 1.0 / 21.0;
87const FONT_OFFSET: f64 = -8.0;
88const ITALIC_TILT: f64 = 1.0 / 8.0;
89const SUPER_SUB_SIZE_MULTIPLIER: f64 = 0.8;
90const SUPER_HEIGHT_OFFSET: f64 = 0.35;
91const SUB_HEIGHT_OFFSET: f64 = 0.15;
92const OVERBAR_POSITION_FACTOR: f64 = 1.23;
93const OVERBAR_TRIM_RATIO: f64 = 0.1;
94
95/// Horizontal placement of a single realized text line.
96#[derive(Clone, Copy, Debug, Eq, PartialEq)]
97pub enum TextHorizontalAlignment {
98    Left,
99    Center,
100    Right,
101}
102
103/// Vertical placement of a single realized text line.
104#[derive(Clone, Copy, Debug, Eq, PartialEq)]
105pub enum TextVerticalAlignment {
106    Top,
107    Center,
108    Bottom,
109}
110
111/// One stroke-font text realization request in source millimetres.
112///
113/// Positive source angles use a y-down placement convention (KiCad's). Newlines
114/// are not laid out as a text block by this single-line API; an embedded
115/// newline follows missing-glyph fallback.
116#[derive(Clone, Copy, Debug)]
117pub struct StrokeTextRequest<'a> {
118    pub text: &'a str,
119    pub position_x_mm: f64,
120    pub position_y_mm: f64,
121    pub size_x_mm: f64,
122    pub size_y_mm: f64,
123    pub angle_degrees: f64,
124    pub horizontal_alignment: TextHorizontalAlignment,
125    pub vertical_alignment: TextVerticalAlignment,
126    pub mirrored: bool,
127    pub italic: bool,
128    pub bold: bool,
129    /// Authored thickness in millimetres. `None` applies the automatic
130    /// normal/bold stroke thickness rule (KiCad's).
131    pub stroke_width_mm: Option<f64>,
132}
133
134/// How a stroke realization slants italic text: part of a
135/// [`StrokeTextProfile`].
136#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
137pub enum StrokeItalicSlant {
138    /// The realizer's own rule: each placed point moves along x by its y
139    /// (millimetres, y down, from the request's position, after the line,
140    /// alignment and script offsets) times the tilt.
141    #[default]
142    PositionLine,
143    /// KiCad's: each glyph's scaled point is sheared about the glyph's own
144    /// baseline, its top to the right, before the cursor, line and script
145    /// offsets move it (`STROKE_GLYPH::Transform`, `point *= aGlyphSize;
146    /// point.x -= point.y * aTilt; point += aOffset`, common/font/glyph.cpp,
147    /// with `aTilt` `ITALIC_TILT` and `aOffset` the cursor,
148    /// common/font/stroke_font.cpp; KiCad 10.0.8).
149    GlyphBaseline,
150}
151
152/// How a single-line stroke realization places a tab: part of a
153/// [`StrokeTextProfile`]. A block's lines
154/// ([`realize_stroke_text_multiline_a0`]) always take KiCad's stops.
155#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
156pub enum StrokeTabRule {
157    /// The realizer's own rule: a tab is a codepoint the font lacks, drawn
158    /// and advanced as `?` and counted in `missing_glyphs`.
159    #[default]
160    MissingGlyph,
161    /// KiCad's: a tab moves the cursor to the next stop, every four columns
162    /// of the text's width from the start of its markup run, a space's width
163    /// in (`STROKE_FONT::GetTextAsGlyphs`, common/font/stroke_font.cpp:225-240;
164    /// KiCad 10.0.8). It draws nothing.
165    ColumnStops,
166}
167
168/// The rules a stroke realization follows beyond its request. The default
169/// keeps the realizer's own rules; [`StrokeTextProfile::kicad`] is the one
170/// KiCad draws its stroke font with.
171#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
172pub struct StrokeTextProfile {
173    pub italic_slant: StrokeItalicSlant,
174    pub tabs: StrokeTabRule,
175}
176
177impl StrokeTextProfile {
178    /// KiCad's stroke-font rules: italic slanted about each glyph's baseline,
179    /// tabs to KiCad's column stops.
180    #[must_use]
181    pub const fn kicad() -> Self {
182        Self {
183            italic_slant: StrokeItalicSlant::GlyphBaseline,
184            tabs: StrokeTabRule::ColumnStops,
185        }
186    }
187}
188
189/// One placed stroke-text point in source millimetres.
190#[derive(Clone, Copy, Debug, PartialEq)]
191pub struct StrokeTextPoint {
192    pub x_mm: f64,
193    pub y_mm: f64,
194}
195
196/// One connected pen-down path. Pen-up markers always split polylines.
197#[derive(Clone, Debug, PartialEq)]
198pub struct StrokeTextPolyline {
199    pub points: Vec<StrokeTextPoint>,
200}
201
202/// Realized centerlines and source-font metrics.
203#[derive(Clone, Debug, PartialEq)]
204pub struct StrokeTextOutput {
205    pub polylines: Vec<StrokeTextPolyline>,
206    /// Centerline bounds `[min_x, min_y, max_x, max_y]` in millimetres.
207    /// Stroke-radius expansion is intentionally left to the consumer.
208    pub bounds_mm: Option<[f64; 4]>,
209    /// Actual cursor advance, including `?` fallback for unsupported glyphs.
210    pub advance_width_mm: f64,
211    /// Width used for alignment (the KiCad Monkey/Python reference rule).
212    /// Unsupported glyphs contribute no width here even though realization
213    /// draws and advances by `?`.
214    pub alignment_width_mm: f64,
215    pub effective_stroke_width_mm: f64,
216    pub missing_glyphs: usize,
217    pub markup_nodes: usize,
218    pub point_count: usize,
219}
220
221#[derive(Clone, Copy, Debug, Eq, PartialEq)]
222pub enum StrokeTextErrorKind {
223    ResourceLimit,
224    InvalidInput,
225}
226
227#[derive(Clone, Debug, Eq, PartialEq)]
228pub struct StrokeTextError {
229    pub kind: StrokeTextErrorKind,
230    pub message: &'static str,
231}
232
233impl fmt::Display for StrokeTextError {
234    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
235        formatter.write_str(self.message)
236    }
237}
238
239impl std::error::Error for StrokeTextError {}
240
241/// Realize text in the built-in stroke font as ordered, disconnected polylines.
242///
243/// The returned coordinates use the same y-down millimetre space as PCB and
244/// footprint source values. Alignment is applied before mirroring, the source
245/// rotation transform, and translation. A source angle of `+90` maps local
246/// `+X` toward global `-Y`. Markup supports the `~{overbar}`, `_{subscript}`,
247/// and `^{superscript}` rules (KiCad's markup). Unsupported
248/// codepoints are drawn with `?` and counted in `missing_glyphs`.
249pub fn realize_stroke_text_a0(
250    request: StrokeTextRequest<'_>,
251) -> Result<StrokeTextOutput, StrokeTextError> {
252    realize_stroke_text_profile_a0(request, StrokeTextProfile::default())
253}
254
255/// [`realize_stroke_text_a0`] following `profile`'s rules.
256pub fn realize_stroke_text_profile_a0(
257    request: StrokeTextRequest<'_>,
258    profile: StrokeTextProfile,
259) -> Result<StrokeTextOutput, StrokeTextError> {
260    realize_stroke_text_line(request, false, false, profile)
261}
262
263/// [`realize_stroke_text_a0`] laid out as pcbnew plots board text: the pen is
264/// clamped to a quarter of the smaller text size (size 1 mm with thickness
265/// 0.3 plots a 0.25 mm pen), left- and right-justified text moves inward
266/// by the pen / 1.52 (KiCad `FONT::getLinePositions`; measured with kicad-cli
267/// 10.0.5 at every size and angle; centred text has none), and the line sits
268/// where `FONT::getLinePositions` puts it for its vertical justification.
269pub fn realize_stroke_text_plot_a0(
270    request: StrokeTextRequest<'_>,
271) -> Result<StrokeTextOutput, StrokeTextError> {
272    realize_stroke_text_plot_profile_a0(request, StrokeTextProfile::default())
273}
274
275/// [`realize_stroke_text_plot_a0`] following `profile`'s rules.
276pub fn realize_stroke_text_plot_profile_a0(
277    request: StrokeTextRequest<'_>,
278    profile: StrokeTextProfile,
279) -> Result<StrokeTextOutput, StrokeTextError> {
280    realize_stroke_text_line(request, false, true, profile)
281}
282
283fn realize_stroke_text_pcb_line(
284    request: StrokeTextRequest<'_>,
285    profile: StrokeTextProfile,
286) -> Result<StrokeTextOutput, StrokeTextError> {
287    realize_stroke_text_line(request, true, true, profile)
288}
289
290/// pcbnew's plotted pen: an authored pen clamped to a quarter of the smaller
291/// text size.
292fn plot_request(request: StrokeTextRequest<'_>) -> StrokeTextRequest<'_> {
293    let minimum_size = request.size_x_mm.abs().min(request.size_y_mm.abs());
294    StrokeTextRequest {
295        stroke_width_mm: request.stroke_width_mm.map(|width| {
296            if minimum_size != 0.0 {
297                width.min(minimum_size * 0.25)
298            } else {
299                width
300            }
301        }),
302        ..request
303    }
304}
305
306fn realize_stroke_text_line(
307    request: StrokeTextRequest<'_>,
308    pcb_tabs: bool,
309    plot: bool,
310    profile: StrokeTextProfile,
311) -> Result<StrokeTextOutput, StrokeTextError> {
312    let request = if plot { plot_request(request) } else { request };
313    validate_request(request)?;
314    if request.text.is_empty() {
315        return Ok(StrokeTextOutput {
316            polylines: Vec::new(),
317            bounds_mm: None,
318            advance_width_mm: 0.0,
319            alignment_width_mm: 0.0,
320            effective_stroke_width_mm: effective_stroke_width(request),
321            missing_glyphs: 0,
322            markup_nodes: 0,
323            point_count: 0,
324        });
325    }
326    let (nodes, markup_nodes) = parsed_markup(request.text)?;
327    let alignment_width_mm = if pcb_tabs {
328        pcb_markup_width(request.text, &nodes, request.size_x_mm)?
329    } else if profile.tabs == StrokeTabRule::ColumnStops {
330        tab_stop_markup_width(request.text, &nodes, request.size_x_mm)?
331    } else {
332        markup_width(request.text, &nodes) * request.size_x_mm
333    };
334    if !alignment_width_mm.is_finite() {
335        return Err(invalid_geometry_error());
336    }
337    // KiCad's FONT::getLinePositions moves left- and right-justified stroke
338    // text inward by the pen width / 1.52 (measured with kicad-cli 10.0.5:
339    // the shift is width / 1.52 at every size and angle; centred text has
340    // none).
341    let justify_inset = if plot {
342        effective_stroke_width(request) / 1.52
343    } else {
344        0.0
345    };
346    let cursor = match request.horizontal_alignment {
347        TextHorizontalAlignment::Left => justify_inset,
348        TextHorizontalAlignment::Center => -alignment_width_mm / 2.0,
349        TextHorizontalAlignment::Right => -alignment_width_mm - justify_inset,
350    };
351    let initial_cursor = cursor;
352    let mut state = RealizationState {
353        request,
354        polylines: Vec::new(),
355        point_count: 0,
356        missing_glyphs: 0,
357        cursor,
358        offset_y: if plot {
359            plot_vertical_offset(request)
360        } else {
361            vertical_offset(request)
362        },
363        pcb_tabs,
364        profile,
365    };
366    state.walk(request.text, &nodes)?;
367    let advance_width_mm = state.cursor - initial_cursor;
368    if !advance_width_mm.is_finite() {
369        return Err(invalid_geometry_error());
370    }
371    let bounds_mm = bounds(&state.polylines);
372    Ok(StrokeTextOutput {
373        polylines: state.polylines,
374        bounds_mm,
375        advance_width_mm,
376        alignment_width_mm,
377        effective_stroke_width_mm: effective_stroke_width(request),
378        missing_glyphs: state.missing_glyphs,
379        markup_nodes,
380        point_count: state.point_count,
381    })
382}
383
384#[derive(Clone, Copy, Eq, PartialEq)]
385enum Style {
386    Normal,
387    Subscript,
388    Superscript,
389}
390
391struct Frame<'a> {
392    nodes: &'a [TextMarkupNode],
393    index: usize,
394    marker: Option<TextMarkupMarker>,
395    bar_start: f64,
396    style: Style,
397}
398
399struct RealizationState<'a> {
400    request: StrokeTextRequest<'a>,
401    polylines: Vec<StrokeTextPolyline>,
402    point_count: usize,
403    missing_glyphs: usize,
404    cursor: f64,
405    offset_y: f64,
406    pcb_tabs: bool,
407    profile: StrokeTextProfile,
408}
409
410impl RealizationState<'_> {
411    fn walk(&mut self, text: &str, nodes: &[TextMarkupNode]) -> Result<(), StrokeTextError> {
412        let mut frames = vec![Frame {
413            nodes,
414            index: 0,
415            marker: None,
416            bar_start: self.cursor,
417            style: Style::Normal,
418        }];
419        while let Some(frame) = frames.last_mut() {
420            let Some(node) = frame.nodes.get(frame.index) else {
421                let closed = frames.pop().expect("frame presence was checked");
422                if closed.marker == Some(TextMarkupMarker::Overbar) {
423                    self.push_polyline([
424                        self.transform(
425                            closed.bar_start + self.request.size_x_mm * OVERBAR_TRIM_RATIO,
426                            self.offset_y - self.request.size_y_mm * OVERBAR_POSITION_FACTOR,
427                            false,
428                        )?,
429                        self.transform(
430                            self.cursor - self.request.size_x_mm * OVERBAR_TRIM_RATIO,
431                            self.offset_y - self.request.size_y_mm * OVERBAR_POSITION_FACTOR,
432                            false,
433                        )?,
434                    ])?;
435                }
436                continue;
437            };
438            frame.index += 1;
439            match node {
440                TextMarkupNode::Text(span) => self.emit_chars(&text[span.clone()], frame.style)?,
441                TextMarkupNode::Group { marker, children } => {
442                    let style = child_style(frame.style, *marker);
443                    frames.push(Frame {
444                        nodes: children,
445                        index: 0,
446                        marker: Some(*marker),
447                        bar_start: self.cursor,
448                        style,
449                    });
450                }
451            }
452        }
453        Ok(())
454    }
455
456    fn emit_chars(&mut self, characters: &str, style: Style) -> Result<(), StrokeTextError> {
457        let scale = if style == Style::Normal {
458            1.0
459        } else {
460            SUPER_SUB_SIZE_MULTIPLIER
461        };
462        let size_x = self.request.size_x_mm * scale;
463        let size_y = self.request.size_y_mm * scale;
464        let style_y = match style {
465            Style::Normal => 0.0,
466            Style::Subscript => size_y * SUB_HEIGHT_OFFSET,
467            Style::Superscript => -size_y * SUPER_HEIGHT_OFFSET,
468        };
469        let tab_origin = self.cursor;
470        let mut column = 0usize;
471        let tab_stops = self.pcb_tabs || self.profile.tabs == StrokeTabRule::ColumnStops;
472        for character in characters.chars() {
473            if tab_stops && character == '\t' {
474                self.cursor =
475                    pcb_tab_cursor(tab_origin, self.cursor, self.request.size_x_mm, &mut column)?;
476                column += 1;
477                continue;
478            }
479            let Some((glyph, width)) = glyph(character).or_else(|| {
480                self.missing_glyphs = self.missing_glyphs.saturating_add(1);
481                glyph('?')
482            }) else {
483                continue;
484            };
485            if character == ' ' {
486                self.cursor += if self.pcb_tabs {
487                    pcb_advance(width * size_x)?
488                } else {
489                    width * size_x
490                };
491                column += 1;
492                continue;
493            }
494            let start_x = glyph.first().map_or(0.0, |value| {
495                (f64::from(*value) - f64::from(b'R')) * STROKE_SCALE
496            });
497            let mut current = Vec::new();
498            let mut index = 2usize;
499            while index + 1 < glyph.len() {
500                if glyph[index] == b' ' && glyph[index + 1] == b'R' {
501                    self.finish_glyph_stroke(&mut current)?;
502                    index += 2;
503                    continue;
504                }
505                let x = (f64::from(glyph[index]) - f64::from(b'R')) * STROKE_SCALE - start_x;
506                let y =
507                    (f64::from(glyph[index + 1]) - f64::from(b'R') + FONT_OFFSET) * STROKE_SCALE;
508                current.push(match self.profile.italic_slant {
509                    StrokeItalicSlant::PositionLine => self.transform(
510                        x * size_x + self.cursor,
511                        y * size_y + self.offset_y + style_y,
512                        self.request.italic,
513                    )?,
514                    StrokeItalicSlant::GlyphBaseline => {
515                        let mut glyph_x = x * size_x;
516                        if self.request.italic {
517                            glyph_x -= y * size_y * ITALIC_TILT;
518                        }
519                        self.transform(
520                            glyph_x + self.cursor,
521                            y * size_y + self.offset_y + style_y,
522                            false,
523                        )?
524                    }
525                });
526                index += 2;
527            }
528            self.finish_glyph_stroke(&mut current)?;
529            self.cursor += if self.pcb_tabs {
530                pcb_advance(width * size_x)?
531            } else {
532                width * size_x
533            };
534            column += 1;
535        }
536        Ok(())
537    }
538
539    fn finish_glyph_stroke(
540        &mut self,
541        points: &mut Vec<StrokeTextPoint>,
542    ) -> Result<(), StrokeTextError> {
543        if points.len() >= 2 {
544            self.push_polyline(std::mem::take(points))?;
545        } else {
546            points.clear();
547        }
548        Ok(())
549    }
550
551    fn push_polyline(
552        &mut self,
553        points: impl IntoIterator<Item = StrokeTextPoint>,
554    ) -> Result<(), StrokeTextError> {
555        let points = points.into_iter().collect::<Vec<_>>();
556        self.point_count = self
557            .point_count
558            .checked_add(points.len())
559            .ok_or_else(|| limit_error("Newstroke points exceed max_points"))?;
560        self.polylines.push(StrokeTextPolyline { points });
561        Ok(())
562    }
563
564    fn transform(
565        &self,
566        mut x: f64,
567        y: f64,
568        italic: bool,
569    ) -> Result<StrokeTextPoint, StrokeTextError> {
570        if italic {
571            x += y * ITALIC_TILT;
572        }
573        if self.request.mirrored {
574            x = -x;
575        }
576        let radians = (-self.request.angle_degrees).to_radians();
577        let (sine, cosine) = radians.sin_cos();
578        let point = StrokeTextPoint {
579            x_mm: x * cosine - y * sine + self.request.position_x_mm,
580            y_mm: x * sine + y * cosine + self.request.position_y_mm,
581        };
582        if !point.x_mm.is_finite() || !point.y_mm.is_finite() {
583            return Err(invalid_geometry_error());
584        }
585        Ok(point)
586    }
587}
588
589#[doc(hidden)]
590pub fn stroke_text_alignment_width_mm(text: &str, size_x_mm: f64) -> Result<f64, StrokeTextError> {
591    if !size_x_mm.is_finite() {
592        return Err(invalid_geometry_error());
593    }
594    let (nodes, _) = parsed_markup(text)?;
595    let width = markup_width(text, &nodes) * size_x_mm;
596    if !width.is_finite() {
597        return Err(invalid_geometry_error());
598    }
599    Ok(width)
600}
601
602fn validate_request(request: StrokeTextRequest<'_>) -> Result<(), StrokeTextError> {
603    if ![
604        request.position_x_mm,
605        request.position_y_mm,
606        request.size_x_mm,
607        request.size_y_mm,
608        request.angle_degrees,
609    ]
610    .into_iter()
611    .all(f64::is_finite)
612        || request
613            .stroke_width_mm
614            .is_some_and(|width| !width.is_finite() || width < 0.0)
615    {
616        return Err(StrokeTextError {
617            kind: StrokeTextErrorKind::InvalidInput,
618            message: "Newstroke request contains invalid geometry or stroke width",
619        });
620    }
621    Ok(())
622}
623
624fn parsed_markup(text: &str) -> Result<(Vec<TextMarkupNode>, usize), StrokeTextError> {
625    let mut nodes = 0usize;
626    let parsed = parse_text_markup(text, &mut nodes).map_err(|error| StrokeTextError {
627        kind: if error.kind == TextMarkupErrorKind::ResourceLimit {
628            StrokeTextErrorKind::ResourceLimit
629        } else {
630            StrokeTextErrorKind::InvalidInput
631        },
632        message: error.message,
633    })?;
634    Ok((parsed, nodes))
635}
636
637fn vertical_offset(request: StrokeTextRequest<'_>) -> f64 {
638    let cap_top = -20.0 / 21.0;
639    let cap_bottom = 1.0 / 21.0;
640    let cap_center = (cap_top + cap_bottom) / 2.0;
641    match request.vertical_alignment {
642        TextVerticalAlignment::Center => (-cap_center - cap_bottom + 0.0024) * request.size_y_mm,
643        TextVerticalAlignment::Top => (-cap_top + 0.0024) * request.size_y_mm,
644        TextVerticalAlignment::Bottom => (-cap_bottom + 0.0024) * request.size_y_mm,
645    }
646}
647
648/// pcbnew's line origin for stroke text (KiCad `FONT::getLinePositions`):
649/// one text height below the anchor less 0.052 of the pen, then up by the
650/// line height (1.17 text heights) for bottom-justified text and by half of
651/// it for centred text. A block's further lines are placed by
652/// `multiline.rs`.
653fn plot_vertical_offset(request: StrokeTextRequest<'_>) -> f64 {
654    let size = request.size_y_mm;
655    let top = size - effective_stroke_width(request) * 0.052;
656    let height = size * 1.17;
657    match request.vertical_alignment {
658        TextVerticalAlignment::Top => top,
659        TextVerticalAlignment::Center => top - height / 2.0,
660        TextVerticalAlignment::Bottom => top - height,
661    }
662}
663
664fn effective_stroke_width(request: StrokeTextRequest<'_>) -> f64 {
665    let minimum_size = request.size_x_mm.abs().min(request.size_y_mm.abs());
666    if let Some(width) = request.stroke_width_mm {
667        return width;
668    }
669    let text_width = if request.size_x_mm.abs() != 0.0 {
670        request.size_x_mm.abs()
671    } else {
672        request.size_y_mm.abs()
673    };
674    if text_width == 0.0 {
675        return 0.15;
676    }
677    let mut width = if request.bold {
678        text_width / 5.0
679    } else {
680        text_width / 8.0
681    };
682    if minimum_size != 0.0 {
683        width = width.min(minimum_size * 0.25);
684    }
685    width
686}
687
688fn markup_width(text: &str, nodes: &[TextMarkupNode]) -> f64 {
689    let mut width = 0.0;
690    let mut frames = vec![Frame {
691        nodes,
692        index: 0,
693        marker: None,
694        bar_start: 0.0,
695        style: Style::Normal,
696    }];
697    while let Some(frame) = frames.last_mut() {
698        let Some(node) = frame.nodes.get(frame.index) else {
699            frames.pop();
700            continue;
701        };
702        frame.index += 1;
703        match node {
704            TextMarkupNode::Text(span) => {
705                let scale = if frame.style == Style::Normal {
706                    1.0
707                } else {
708                    SUPER_SUB_SIZE_MULTIPLIER
709                };
710                width += text[span.clone()]
711                    .chars()
712                    .filter_map(glyph)
713                    .map(|(_, value)| value * scale)
714                    .sum::<f64>();
715            }
716            TextMarkupNode::Group { marker, children } => {
717                let style = child_style(frame.style, *marker);
718                frames.push(Frame {
719                    nodes: children,
720                    index: 0,
721                    marker: Some(*marker),
722                    bar_start: width,
723                    style,
724                });
725            }
726        }
727    }
728    width
729}
730
731/// [`markup_width`], millimetres, with [`StrokeTabRule::ColumnStops`]: a tab
732/// moves the width to its run's next stop as it moves the cursor.
733fn tab_stop_markup_width(
734    text: &str,
735    nodes: &[TextMarkupNode],
736    size_x: f64,
737) -> Result<f64, StrokeTextError> {
738    let mut width = 0.;
739    let mut frames = vec![Frame {
740        nodes,
741        index: 0,
742        marker: None,
743        bar_start: 0.,
744        style: Style::Normal,
745    }];
746    while let Some(frame) = frames.last_mut() {
747        let Some(node) = frame.nodes.get(frame.index) else {
748            frames.pop();
749            continue;
750        };
751        frame.index += 1;
752        match node {
753            TextMarkupNode::Text(span) => {
754                let scale = if frame.style == Style::Normal {
755                    1.
756                } else {
757                    SUPER_SUB_SIZE_MULTIPLIER
758                };
759                let origin = width;
760                let mut column = 0;
761                for character in text[span.clone()].chars() {
762                    if character == '\t' {
763                        width = pcb_tab_cursor(origin, width, size_x, &mut column)?;
764                    } else if let Some((_, value)) = glyph(character) {
765                        width += value * size_x * scale;
766                    }
767                    column += 1;
768                }
769            }
770            TextMarkupNode::Group { marker, children } => {
771                let style = child_style(frame.style, *marker);
772                frames.push(Frame {
773                    nodes: children,
774                    index: 0,
775                    marker: Some(*marker),
776                    bar_start: width,
777                    style,
778                });
779            }
780        }
781    }
782    Ok(width)
783}
784
785fn pcb_tab_cursor(
786    origin: f64,
787    cursor: f64,
788    size_x: f64,
789    column: &mut usize,
790) -> Result<f64, StrokeTextError> {
791    let space_width = glyph(' ').map_or(0., |(_, width)| width);
792    *column = (*column / 4 + 1) * 4 - 1;
793    let size_iu = multiline::source_iu(size_x)?;
794    let origin_iu = multiline::round_iu(origin * 1e6)?;
795    let cursor_iu = multiline::round_iu(cursor * 1e6)?;
796    // Source assigns this expression to int: truncation, not KiROUND.
797    let raw = origin_iu as f64 + size_iu as f64 * *column as f64 + size_iu as f64 * space_width;
798    if !raw.is_finite() || raw.abs() > i32::MAX as f64 {
799        return Err(invalid_geometry_error());
800    }
801    let mut next = raw.trunc() as i64;
802    while next <= cursor_iu {
803        *column = column.checked_add(4).ok_or_else(invalid_geometry_error)?;
804        next = next
805            .checked_add(size_iu * 4)
806            .ok_or_else(invalid_geometry_error)?;
807        if i32::try_from(next).is_err() || size_iu <= 0 {
808            return Err(invalid_geometry_error());
809        }
810    }
811    Ok(next as f64 / 1e6)
812}
813
814fn pcb_advance(mm: f64) -> Result<f64, StrokeTextError> {
815    Ok(multiline::round_iu(mm * 1e6)? as f64 / 1e6)
816}
817
818fn pcb_markup_width(
819    text: &str,
820    nodes: &[TextMarkupNode],
821    size_x: f64,
822) -> Result<f64, StrokeTextError> {
823    let mut width = 0.;
824    let mut frames = vec![Frame {
825        nodes,
826        index: 0,
827        marker: None,
828        bar_start: 0.,
829        style: Style::Normal,
830    }];
831    while let Some(frame) = frames.last_mut() {
832        let Some(node) = frame.nodes.get(frame.index) else {
833            frames.pop();
834            continue;
835        };
836        frame.index += 1;
837        match node {
838            TextMarkupNode::Text(span) => {
839                let scale = if frame.style == Style::Normal {
840                    1.
841                } else {
842                    SUPER_SUB_SIZE_MULTIPLIER
843                };
844                let origin = width;
845                let mut column = 0;
846                for character in text[span.clone()].chars() {
847                    if character == '\t' {
848                        width = pcb_tab_cursor(origin, width, size_x, &mut column)?;
849                    } else {
850                        width += pcb_advance(
851                            glyph(character)
852                                .or_else(|| glyph('?'))
853                                .map_or(0., |(_, value)| value * size_x * scale),
854                        )?;
855                    }
856                    column += 1;
857                }
858            }
859            TextMarkupNode::Group { marker, children } => {
860                let style = child_style(frame.style, *marker);
861                frames.push(Frame {
862                    nodes: children,
863                    index: 0,
864                    marker: Some(*marker),
865                    bar_start: width,
866                    style,
867                });
868            }
869        }
870    }
871    Ok(width)
872}
873
874fn child_style(style: Style, marker: TextMarkupMarker) -> Style {
875    match marker {
876        TextMarkupMarker::Overbar => style,
877        TextMarkupMarker::Subscript => Style::Subscript,
878        TextMarkupMarker::Superscript if style == Style::Subscript => Style::Subscript,
879        TextMarkupMarker::Superscript => Style::Superscript,
880    }
881}
882
883fn glyph(character: char) -> Option<(&'static [u8], f64)> {
884    let index = (character as usize).checked_sub(0x20)?;
885    let start = usize::try_from(*NEWSTROKE_GLYPH_OFFSETS.get(index)?).ok()?;
886    let end = usize::try_from(*NEWSTROKE_GLYPH_OFFSETS.get(index + 1)?).ok()?;
887    Some((
888        NEWSTROKE_GLYPH_DATA.as_bytes().get(start..end)?,
889        f64::from(*NEWSTROKE_WIDTH_UNITS.get(index)?) * STROKE_SCALE,
890    ))
891}
892
893fn bounds(polylines: &[StrokeTextPolyline]) -> Option<[f64; 4]> {
894    let mut result: Option<[f64; 4]> = None;
895    for point in polylines.iter().flat_map(|polyline| &polyline.points) {
896        match &mut result {
897            Some(value) => {
898                value[0] = value[0].min(point.x_mm);
899                value[1] = value[1].min(point.y_mm);
900                value[2] = value[2].max(point.x_mm);
901                value[3] = value[3].max(point.y_mm);
902            }
903            None => result = Some([point.x_mm, point.y_mm, point.x_mm, point.y_mm]),
904        }
905    }
906    result
907}
908
909fn limit_error(message: &'static str) -> StrokeTextError {
910    StrokeTextError {
911        kind: StrokeTextErrorKind::ResourceLimit,
912        message,
913    }
914}
915
916fn invalid_geometry_error() -> StrokeTextError {
917    StrokeTextError {
918        kind: StrokeTextErrorKind::InvalidInput,
919        message: "Newstroke realization produced nonfinite geometry",
920    }
921}