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

kicad_monkey_core/
text_block_layout.rs

1//! Bounded KiCad multiline, tabbed, and markup outline-text layout.
2
3use crate::text_contours::{HintedTextContourSession, TextRunStyle};
4use crate::text_layout::{transform_contours, transform_point, validated_transform};
5use crate::{
6    TextContour, TextContourError, TextContourErrorKind, TextContourOutput,
7    TextHorizontalAlignment, TextLayoutRequest, TextPoint, TextVerticalAlignment,
8};
9use cad_text_realization::{ShapingFeature, ShapingInput};
10use cad_text_realization::{
11    TextMarkupErrorKind, TextMarkupMarker, TextMarkupNode, parse_text_markup,
12};
13use std::ops::Range;
14
15/// KiCad draws an outline (TrueType) text's em at 1.4 times its authored
16/// size (`OUTLINE_FONT`'s size compensation, so its capitals stand about as
17/// tall as the stroke font's). The shared realizer takes the em; this is the
18/// one place KiCad's size convention meets it.
19pub const KICAD_OUTLINE_EM_PER_SIZE: f64 = 1.4;
20/// KiCad's baseline-to-baseline multiplier for outline text.
21pub const KICAD_TEXT_INTERLINE_FACTOR: f64 = 1.68;
22/// KiCad's four-character tab stop using an average character width of 0.6.
23pub const KICAD_TEXT_TAB_WIDTH_FACTOR: f64 = 2.4;
24/// KiCad's overbar baseline offset as a fraction of the character height.
25pub const KICAD_TEXT_OVERBAR_HEIGHT_RATIO: f64 = 1.23;
26// KiCad trims the overbar by one tenth of the character width at each end.
27const OVERBAR_TRIM_RATIO: f64 = 0.1;
28// `CALLBACK_GAL::DrawGlyph()` strokes ovals with error `strokeWidth / 180`.
29const OVERBAR_STROKE_ERROR_DIVISOR: f64 = 180.0;
30
31/// One multiline text request including fake bold/italic synthesis flags.
32#[derive(Clone, Copy, Debug)]
33pub struct TextBlockLayoutRequest<'a> {
34    pub shaping: &'a ShapingInput,
35    pub size_x: f64,
36    pub size_y: f64,
37    pub position_x: f64,
38    pub position_y: f64,
39    pub angle_degrees: f64,
40    pub mirrored: bool,
41    pub horizontal_alignment: TextHorizontalAlignment,
42    pub vertical_alignment: TextVerticalAlignment,
43    pub line_spacing: f64,
44    pub stroke_width: f64,
45    pub max_error: f64,
46    pub fake_bold: bool,
47    pub fake_italic: bool,
48}
49
50/// Positioned block contours and bounded construction accounting.
51#[derive(Clone, Debug)]
52pub struct TextBlockLayoutOutput {
53    pub contours: Vec<TextContour>,
54    /// Contiguous per-glyph (and per-overbar) contour counts in draw order,
55    /// summing to `contours.len()`.
56    pub contour_group_sizes: Vec<usize>,
57    pub line_widths: Vec<f64>,
58    pub width: f64,
59    pub height: f64,
60    pub glyphs: usize,
61    pub outline_commands: usize,
62    pub bezier_work_items: usize,
63    pub peak_temporary_bezier_points: usize,
64}
65
66/// Plain baseline-local ink and source-owned placement for compact consumers.
67/// Contours are a transient metric bridge; callers need not normalize or emit
68/// them. Markup, tabs, multiple lines and synthetic faces use the block API.
69pub struct PlainTextLayoutOutput {
70    pub local: TextContourOutput,
71    pub baseline: [f64; 2],
72    /// Source Y-down linear basis, before glyph em compensation.
73    pub x_axis: [f64; 2],
74    pub y_axis: [f64; 2],
75    pub em_compensation: f64,
76}
77
78/// Reuse the native hinted plain-run metrics and block alignment, without an
79/// adapter-private copy of baseline, mirror or rotation conventions.
80pub fn layout_plain_text_hinted_a0(
81    font_bytes: &[u8],
82    request: TextBlockLayoutRequest<'_>,
83) -> Result<PlainTextLayoutOutput, TextContourError> {
84    validate_request(request)?;
85    if request.fake_bold
86        || request.fake_italic
87        || request.shaping.text.contains(['\n', '\r', '\t'])
88        || ["_{", "^{", "~{"]
89            .iter()
90            .any(|marker| request.shaping.text.contains(*marker))
91    {
92        return Err(invalid(
93            "$.text",
94            "plain layout requires one unstyled text run",
95        ));
96    }
97    let line = build_plain_line(font_bytes, request)?;
98    let lines = [line];
99    let metrics = block_metrics(request, &lines)?;
100    let [line] = lines;
101    assert_eq!(line.items.len(), 1, "one literal plain-text run");
102    let PendingItem::Run(run) = line.items.into_iter().next().expect("plain run present") else {
103        unreachable!("plain run contains no decoration")
104    };
105    let local = run.output;
106    let transform = validated_transform(single_line_request(request, request.shaping))?;
107    let baseline = transform_point(
108        request.position_x + horizontal_offset(request.horizontal_alignment, metrics.width),
109        request.position_y + metrics.vertical_offset,
110        transform,
111    )?;
112    let linear = TextBlockLayoutRequest {
113        position_x: 0.0,
114        position_y: 0.0,
115        ..request
116    };
117    let linear = validated_transform(single_line_request(linear, request.shaping))?;
118    let x_axis = transform_point(1.0, 0.0, linear)?;
119    let y_axis = transform_point(0.0, 1.0, linear)?;
120    Ok(PlainTextLayoutOutput {
121        local,
122        baseline: [baseline.0, baseline.1],
123        x_axis: [x_axis.0, x_axis.1],
124        y_axis: [y_axis.0, y_axis.1],
125        em_compensation: KICAD_OUTLINE_EM_PER_SIZE,
126    })
127}
128
129fn build_plain_line(
130    font_bytes: &[u8],
131    request: TextBlockLayoutRequest<'_>,
132) -> Result<PendingLine, TextContourError> {
133    if request.shaping.text.is_empty() {
134        return Err(invalid("$.text", "plain layout requires nonempty text"));
135    }
136    let spans = delimited_spans(&request.shaping.text, '\n', "$.lines")?;
137    let mut work = AggregateWork::default();
138    charge(
139        &mut work.feature_inspections,
140        request.shaping.features.len(),
141        "$.features.inspections",
142        "aggregate feature inspection limit exceeded",
143    )?;
144    let run_metadata_bytes = shaping_metadata_bytes(request.shaping)?;
145    let session = HintedTextContourSession::new(font_bytes, request.shaping)?;
146    let inputs = LineBuildInputs {
147        session: &session,
148        request,
149        run_metadata_bytes,
150    };
151    build_line(&inputs, spans[0].clone(), &mut 0, &mut work)
152}
153
154struct PendingRun {
155    x: f64,
156    output: TextContourOutput,
157}
158
159/// One line item retained in markup source order for deferred placement.
160enum PendingItem {
161    Run(PendingRun),
162    /// Overbar endpoints in unaligned line-local x coordinates.
163    Bar {
164        start_x: f64,
165        end_x: f64,
166    },
167}
168
169pub(crate) struct PendingLine {
170    items: Vec<PendingItem>,
171    pub(crate) width: f64,
172}
173
174struct BlockMetrics {
175    interline: f64,
176    height: f64,
177    vertical_offset: f64,
178    width: f64,
179    line_widths: Vec<f64>,
180}
181
182#[derive(Default)]
183pub(crate) struct AggregateWork {
184    runs: usize,
185    run_metadata_bytes: usize,
186    feature_inspections: usize,
187    feature_applications: usize,
188    glyphs: usize,
189    outline_commands: usize,
190    bezier_work_items: usize,
191    contours: usize,
192    points: usize,
193    peak_temporary_bezier_points: usize,
194}
195
196/// Render multiline/tabbed/markup text with one reusable shaping and hinted face.
197pub fn layout_text_block_hinted_a0(
198    font_bytes: &[u8],
199    request: TextBlockLayoutRequest<'_>,
200) -> Result<TextBlockLayoutOutput, TextContourError> {
201    validate_request(request)?;
202    let mut line_spans = delimited_spans(&request.shaping.text, '\n', "$.lines")?;
203    // KiCad's `getLinePositions` splits with `wxStringSplit`, which never
204    // emits a trailing empty segment: text ending in '\n' contributes no
205    // extra line to the count used for vertical alignment.
206    if line_spans.last().is_some_and(|span| span.is_empty()) {
207        line_spans.pop();
208    }
209    let mut work = AggregateWork::default();
210    charge(
211        &mut work.feature_inspections,
212        request.shaping.features.len(),
213        "$.features.inspections",
214        "aggregate feature inspection limit exceeded",
215    )?;
216    let run_metadata_bytes = shaping_metadata_bytes(request.shaping)?;
217    let session = HintedTextContourSession::new(font_bytes, request.shaping)?;
218    let inputs = LineBuildInputs {
219        session: &session,
220        request,
221        run_metadata_bytes,
222    };
223    let mut markup_budget = 0usize;
224    let mut lines = Vec::with_capacity(line_spans.len().min(256));
225    for line_span in line_spans {
226        lines.push(build_line(
227            &inputs,
228            line_span,
229            &mut markup_budget,
230            &mut work,
231        )?);
232    }
233
234    let metrics = block_metrics(request, &lines)?;
235    place_lines(request, lines, work, metrics)
236}
237
238fn block_metrics(
239    request: TextBlockLayoutRequest<'_>,
240    lines: &[PendingLine],
241) -> Result<BlockMetrics, TextContourError> {
242    let interline = request.size_y * KICAD_TEXT_INTERLINE_FACTOR * request.line_spacing;
243    let height = request.size_y * cad_text_realization::TEXT_HEIGHT_FUDGE_FACTOR
244        + interline * lines.len().saturating_sub(1) as f64;
245    let vertical_offset = match request.vertical_alignment {
246        TextVerticalAlignment::Top => request.size_y,
247        TextVerticalAlignment::Center => request.size_y - height / 2.0,
248        TextVerticalAlignment::Bottom => request.size_y - height,
249    };
250    if !interline.is_finite() || !height.is_finite() || !vertical_offset.is_finite() {
251        return Err(invalid(
252            "$.line_spacing",
253            "derived text block metrics are not finite",
254        ));
255    }
256    let width = lines.iter().map(|line| line.width).fold(0.0_f64, f64::max);
257    let line_widths = lines.iter().map(|line| line.width).collect::<Vec<_>>();
258    Ok(BlockMetrics {
259        interline,
260        height,
261        vertical_offset,
262        width,
263        line_widths,
264    })
265}
266
267fn place_lines(
268    request: TextBlockLayoutRequest<'_>,
269    lines: Vec<PendingLine>,
270    work: AggregateWork,
271    metrics: BlockMetrics,
272) -> Result<TextBlockLayoutOutput, TextContourError> {
273    let single_request = single_line_request(request, request.shaping);
274    let transform = validated_transform(single_request)?;
275    let mut contours = Vec::with_capacity(work.contours.min(256));
276    let mut contour_group_sizes = Vec::new();
277    for (line_index, line) in lines.into_iter().enumerate() {
278        let horizontal_offset = horizontal_offset(request.horizontal_alignment, line.width);
279        let line_y =
280            request.position_y + metrics.vertical_offset + line_index as f64 * metrics.interline;
281        for item in line.items {
282            match item {
283                PendingItem::Run(mut run) => {
284                    let translation = (request.position_x + horizontal_offset + run.x, line_y);
285                    if !translation.0.is_finite() || !translation.1.is_finite() {
286                        return Err(invalid(
287                            "$.position",
288                            "aligned text run position is not finite",
289                        ));
290                    }
291                    transform_contours(&mut run.output.contours, translation, transform)?;
292                    contour_group_sizes.extend(run.output.contour_group_sizes);
293                    contours.extend(run.output.contours);
294                }
295                PendingItem::Bar { start_x, end_x } => {
296                    // The reference transforms the bar endpoints and then
297                    // strokes the oval in final coordinates, so mirrored bars
298                    // keep the reference's normalized point order.
299                    let bar_y = line_y - request.size_y * KICAD_TEXT_OVERBAR_HEIGHT_RATIO;
300                    let bar_x = request.position_x + horizontal_offset;
301                    if !(bar_x + start_x).is_finite() || !(bar_x + end_x).is_finite() {
302                        return Err(invalid(
303                            "$.position",
304                            "aligned overbar position is not finite",
305                        ));
306                    }
307                    let start = transform_point(bar_x + start_x, bar_y, transform)?;
308                    let end = transform_point(bar_x + end_x, bar_y, transform)?;
309                    let points = stroke_segment_to_polygon(start, end, request.stroke_width);
310                    if !points.is_empty() {
311                        contours.push(TextContour { points });
312                        contour_group_sizes.push(1);
313                    }
314                }
315            }
316        }
317    }
318    Ok(TextBlockLayoutOutput {
319        contours,
320        contour_group_sizes,
321        line_widths: metrics.line_widths,
322        width: metrics.width,
323        height: metrics.height,
324        glyphs: work.glyphs,
325        outline_commands: work.outline_commands,
326        bezier_work_items: work.bezier_work_items,
327        peak_temporary_bezier_points: work.peak_temporary_bezier_points,
328    })
329}
330
331fn horizontal_offset(alignment: TextHorizontalAlignment, width: f64) -> f64 {
332    match alignment {
333        TextHorizontalAlignment::Left => 0.0,
334        TextHorizontalAlignment::Center => -width / 2.0,
335        TextHorizontalAlignment::Right => -width,
336    }
337}
338
339/// Shared read-only inputs threaded through one block layout.
340pub(crate) struct LineBuildInputs<'a> {
341    pub(crate) session: &'a HintedTextContourSession<'a>,
342    pub(crate) request: TextBlockLayoutRequest<'a>,
343    pub(crate) run_metadata_bytes: usize,
344}
345
346/// One open markup group on the explicit walk stack.
347struct MarkupFrame<'a> {
348    nodes: &'a [TextMarkupNode],
349    index: usize,
350    marker: Option<TextMarkupMarker>,
351    bar_start: f64,
352    style: TextRunStyle,
353}
354
355pub(crate) fn build_line(
356    inputs: &LineBuildInputs<'_>,
357    line_span: Range<usize>,
358    markup_budget: &mut usize,
359    work: &mut AggregateWork,
360) -> Result<PendingLine, TextContourError> {
361    let text = &inputs.request.shaping.text;
362    let nodes = parse_text_markup(&text[line_span.clone()], markup_budget).map_err(|error| {
363        TextContourError {
364            kind: match error.kind {
365                TextMarkupErrorKind::ResourceLimit => TextContourErrorKind::ResourceLimit,
366                TextMarkupErrorKind::InvalidInput => TextContourErrorKind::InvalidInput,
367            },
368            path: error.path.to_owned(),
369            message: error.message,
370        }
371    })?;
372    let mut line = PendingLine {
373        items: Vec::with_capacity(nodes.len().min(32)),
374        width: 0.0,
375    };
376    // Group frames were already charged one markup node each by the parser, so
377    // this explicit stack cannot outgrow the shared markup ceiling.
378    let mut frames = vec![MarkupFrame {
379        nodes: &nodes,
380        index: 0,
381        marker: None,
382        bar_start: 0.0,
383        style: TextRunStyle::Normal,
384    }];
385    while let Some(frame) = frames.last_mut() {
386        let Some(node) = frame.nodes.get(frame.index) else {
387            let closed = frames.pop().expect("frame presence was checked");
388            if closed.marker == Some(TextMarkupMarker::Overbar) {
389                append_overbar(inputs.request, closed.bar_start, &mut line, work)?;
390            }
391            continue;
392        };
393        frame.index += 1;
394        match node {
395            TextMarkupNode::Text(span) => {
396                let style = frame.style;
397                let text_span = (line_span.start + span.start)..(line_span.start + span.end);
398                build_text_runs(inputs, text_span, style, &mut line, work)?;
399            }
400            TextMarkupNode::Group { marker, children } => {
401                let style = child_style(frame.style, *marker);
402                frames.push(MarkupFrame {
403                    nodes: children,
404                    index: 0,
405                    marker: Some(*marker),
406                    bar_start: line.width,
407                    style,
408                });
409            }
410        }
411    }
412    Ok(line)
413}
414
415/// Combine one parent style with a group marker exactly like the reference's
416/// subscript/superscript flag pair: subscript wins once set, an overbar keeps
417/// the surrounding style, and offsets never accumulate across nesting.
418fn child_style(style: TextRunStyle, marker: TextMarkupMarker) -> TextRunStyle {
419    match marker {
420        TextMarkupMarker::Overbar => style,
421        TextMarkupMarker::Subscript => TextRunStyle::Subscript,
422        TextMarkupMarker::Superscript => {
423            if style == TextRunStyle::Subscript {
424                TextRunStyle::Subscript
425            } else {
426                TextRunStyle::Superscript
427            }
428        }
429    }
430}
431
432fn build_text_runs(
433    inputs: &LineBuildInputs<'_>,
434    text_span: Range<usize>,
435    style: TextRunStyle,
436    line: &mut PendingLine,
437    work: &mut AggregateWork,
438) -> Result<(), TextContourError> {
439    let LineBuildInputs {
440        session,
441        request,
442        run_metadata_bytes,
443    } = *inputs;
444    let text = &request.shaping.text;
445    let run_spans = delimited_spans(&text[text_span.clone()], '\t', "$.runs")?;
446    let tab_width = request.size_x * KICAD_TEXT_TAB_WIDTH_FACTOR;
447    for (run_index, local_span) in run_spans.iter().enumerate() {
448        charge(&mut work.runs, 1, "$.runs", "text run limit exceeded")?;
449        let run_span = (text_span.start + local_span.start)..(text_span.start + local_span.end);
450        charge(
451            &mut work.run_metadata_bytes,
452            run_metadata_bytes,
453            "$.runs.metadata",
454            "aggregate text run metadata limit exceeded",
455        )?;
456        let run_input = shaping_run(request.shaping, run_span.clone(), work)?;
457        let output = session.shape_input_styled(
458            crate::TextContourRequest {
459                shaping: &run_input,
460                em_x: request.size_x * KICAD_OUTLINE_EM_PER_SIZE,
461                em_y: request.size_y * KICAD_OUTLINE_EM_PER_SIZE,
462                origin_x: 0.0,
463                origin_y: 0.0,
464                max_error: request.max_error,
465                fake_bold: request.fake_bold,
466                fake_italic: request.fake_italic,
467            },
468            style,
469        )?;
470        charge_output(work, &output)?;
471        let advance = output.advance_x;
472        line.items.push(PendingItem::Run(PendingRun {
473            x: line.width,
474            output,
475        }));
476        line.width += advance;
477        if run_index + 1 < run_spans.len() {
478            let intrusion = line.width.rem_euclid(tab_width);
479            line.width += tab_width - intrusion;
480        }
481        if !line.width.is_finite() {
482            return Err(invalid("$.runs", "derived tabbed line width is not finite"));
483        }
484    }
485    Ok(())
486}
487
488fn append_overbar(
489    request: TextBlockLayoutRequest<'_>,
490    bar_start: f64,
491    line: &mut PendingLine,
492    work: &mut AggregateWork,
493) -> Result<(), TextContourError> {
494    if request.stroke_width <= 0.0 {
495        return Ok(());
496    }
497    let trim = request.size_x * OVERBAR_TRIM_RATIO;
498    let start_x = bar_start + trim;
499    let end_x = line.width - trim;
500    if !start_x.is_finite() || !end_x.is_finite() {
501        return Err(invalid("$.markup", "derived overbar span is not finite"));
502    }
503    charge(
504        &mut work.contours,
505        1,
506        "$.contours",
507        "aggregate contour limit exceeded",
508    )?;
509    charge(
510        &mut work.points,
511        oval_polygon_point_count(request.stroke_width),
512        "$.points",
513        "aggregate point limit exceeded",
514    )?;
515    line.items.push(PendingItem::Bar { start_x, end_x });
516    Ok(())
517}
518
519/// Port of the reference `_round_to_int`, KiCad's `KiROUND` for finite input.
520fn round_to_int(value: f64) -> i64 {
521    (value + 0.5).floor() as i64
522}
523
524/// Port of the reference `_arc_segment_count` for one full circle.
525fn arc_segment_count(radius: f64, error: f64) -> i64 {
526    let radius = radius.max(1e-9);
527    let error = error.max(1e-9);
528    let relative_error = error / radius;
529    let arc_increment =
530        (180.0 / std::f64::consts::PI * (1.0 - relative_error).max(-1.0).acos() * 2.0)
531            .min(360.0 / 8.0);
532    round_to_int(360.0 / arc_increment).max(2)
533}
534
535/// Full-circle segment count for one stroked oval of the given width.
536fn oval_segment_count(width: f64) -> usize {
537    let segments = arc_segment_count(width / 2.0, width / OVERBAR_STROKE_ERROR_DIVISOR).max(8);
538    usize::try_from(segments)
539        .expect("segment count is positive")
540        .div_ceil(8)
541        * 8
542}
543
544/// Retained point count for one positive-width stroked oval polygon.
545fn oval_polygon_point_count(width: f64) -> usize {
546    oval_segment_count(width) + 4
547}
548
549/// Port KiCad's ERROR_INSIDE `TransformOvalToPolygon()` point order.
550fn stroke_segment_to_polygon(start: (f64, f64), end: (f64, f64), width: f64) -> Vec<TextPoint> {
551    if width <= 0.0 {
552        return Vec::new();
553    }
554    let (mut start_x, mut start_y) = start;
555    let (mut end_x, mut end_y) = end;
556    let mut delta_x = end_x - start_x;
557    let mut delta_y = end_y - start_y;
558    if delta_x < 0.0 {
559        std::mem::swap(&mut start_x, &mut end_x);
560        std::mem::swap(&mut start_y, &mut end_y);
561        delta_x = end_x - start_x;
562        delta_y = end_y - start_y;
563    }
564    let segment_length = delta_x.hypot(delta_y);
565    let radius = width / 2.0;
566    let segments = oval_segment_count(width);
567    let delta = std::f64::consts::PI * 2.0 / segments as f64;
568    let (unit_x, unit_y) = if segment_length > 1e-12 {
569        (delta_x / segment_length, delta_y / segment_length)
570    } else {
571        (1.0, 0.0)
572    };
573    let place = |local_x: f64, local_y: f64| TextPoint {
574        x: start_x + local_x * unit_x - local_y * unit_y,
575        y: start_y + local_x * unit_y + local_y * unit_x,
576    };
577    let mut points = Vec::with_capacity(segments + 4);
578    for index in 0..segments / 2 {
579        let angle = delta / 2.0 + index as f64 * delta;
580        points.push(place(
581            segment_length + radius * angle.sin(),
582            -radius * angle.cos(),
583        ));
584    }
585    points.push(place(segment_length, radius));
586    points.push(place(0.0, radius));
587    for index in 0..segments / 2 {
588        let angle = delta / 2.0 + index as f64 * delta;
589        points.push(place(-radius * angle.sin(), radius * angle.cos()));
590    }
591    points.push(place(0.0, -radius));
592    points.push(place(segment_length, -radius));
593    points
594}
595
596fn single_line_request<'a>(
597    request: TextBlockLayoutRequest<'a>,
598    shaping: &'a ShapingInput,
599) -> TextLayoutRequest<'a> {
600    TextLayoutRequest {
601        shaping,
602        em_x: request.size_x * KICAD_OUTLINE_EM_PER_SIZE,
603        em_y: request.size_y * KICAD_OUTLINE_EM_PER_SIZE,
604        alignment_height: request.size_y,
605        position_x: request.position_x,
606        position_y: request.position_y,
607        angle_degrees: request.angle_degrees,
608        mirrored: request.mirrored,
609        horizontal_alignment: request.horizontal_alignment,
610        vertical_alignment: request.vertical_alignment,
611        max_error: request.max_error,
612    }
613}
614
615pub(crate) fn validate_request(
616    request: TextBlockLayoutRequest<'_>,
617) -> Result<(), TextContourError> {
618    if !request.line_spacing.is_finite() || request.line_spacing <= 0.0 {
619        return Err(invalid(
620            "$.line_spacing",
621            "line spacing must be positive and finite",
622        ));
623    }
624    let tab_width = request.size_x * KICAD_TEXT_TAB_WIDTH_FACTOR;
625    if !tab_width.is_finite() || tab_width <= 0.0 {
626        return Err(invalid(
627            "$.size_x",
628            "derived tab width must be positive and finite",
629        ));
630    }
631    if !request.stroke_width.is_finite() {
632        return Err(invalid("$.stroke_width", "stroke width must be finite"));
633    }
634    Ok(())
635}
636
637fn delimited_spans(
638    text: &str,
639    delimiter: char,
640    path: &'static str,
641) -> Result<Vec<Range<usize>>, TextContourError> {
642    let _ = path;
643    let mut spans = Vec::new();
644    let mut start = 0usize;
645    for (index, character) in text.char_indices() {
646        if character == delimiter {
647            spans.push(start..index);
648            start = index + character.len_utf8();
649        }
650    }
651    spans.push(start..text.len());
652    Ok(spans)
653}
654
655fn shaping_run(
656    base: &ShapingInput,
657    span: Range<usize>,
658    work: &mut AggregateWork,
659) -> Result<ShapingInput, TextContourError> {
660    Ok(ShapingInput {
661        buffer_properties: base.buffer_properties.clone(),
662        direction: base.direction,
663        face_index: base.face_index,
664        features: rebase_features(&base.features, span.clone(), work)?,
665        font_id: base.font_id.clone(),
666        font_sha256: base.font_sha256.clone(),
667        language: base.language.clone(),
668        scale_x: base.scale_x,
669        scale_y: base.scale_y,
670        script: base.script.clone(),
671        text: base.text[span].to_owned(),
672        text_index_unit: base.text_index_unit.clone(),
673        variations: base.variations.clone(),
674    })
675}
676
677fn rebase_features(
678    features: &[ShapingFeature],
679    span: Range<usize>,
680    work: &mut AggregateWork,
681) -> Result<Vec<ShapingFeature>, TextContourError> {
682    charge(
683        &mut work.feature_inspections,
684        features.len(),
685        "$.features.inspections",
686        "aggregate feature inspection limit exceeded",
687    )?;
688    let run_start = u32::try_from(span.start)
689        .map_err(|_| resource("$.features", "text feature offset exceeds uint32"))?;
690    let run_end = u32::try_from(span.end)
691        .map_err(|_| resource("$.features", "text feature offset exceeds uint32"))?;
692    let mut rebased_features = Vec::with_capacity(features.len().min(16));
693    for feature in features {
694        if feature.end <= run_start || feature.start >= run_end {
695            continue;
696        }
697        charge(
698            &mut work.feature_applications,
699            1,
700            "$.features.applications",
701            "aggregate feature application limit exceeded",
702        )?;
703        let mut rebased = feature.clone();
704        rebased.start = feature.start.max(run_start) - run_start;
705        rebased.end = if feature.end == u32::MAX {
706            u32::MAX
707        } else {
708            feature.end.min(run_end) - run_start
709        };
710        rebased_features.push(rebased);
711    }
712    Ok(rebased_features)
713}
714
715pub(crate) fn shaping_metadata_bytes(input: &ShapingInput) -> Result<usize, TextContourError> {
716    let mut total = input.font_id.len().checked_add(input.font_sha256.0.len());
717    total = total.and_then(|value| value.checked_add(input.text_index_unit.len()));
718    total =
719        total.and_then(|value| value.checked_add(input.language.as_deref().map_or(0, str::len)));
720    total = total.and_then(|value| {
721        value.checked_add(input.script.as_ref().map_or(0, |script| script.0.len()))
722    });
723    for feature in &input.features {
724        total = total.and_then(|value| value.checked_add(feature.tag.0.len()));
725    }
726    for variation in &input.variations {
727        total = total.and_then(|value| value.checked_add(variation.axis.0.len()));
728    }
729    total.ok_or_else(|| resource("$.runs.metadata", "text run metadata byte count overflowed"))
730}
731
732fn charge_output(
733    work: &mut AggregateWork,
734    output: &TextContourOutput,
735) -> Result<(), TextContourError> {
736    charge(
737        &mut work.glyphs,
738        output.glyphs,
739        "$.glyphs",
740        "aggregate shaped glyph limit exceeded",
741    )?;
742    charge(
743        &mut work.outline_commands,
744        output.outline_commands,
745        "$.outline_commands",
746        "aggregate outline command limit exceeded",
747    )?;
748    charge(
749        &mut work.bezier_work_items,
750        output.bezier_work_items,
751        "$.bezier_work",
752        "aggregate Bezier work limit exceeded",
753    )?;
754    charge(
755        &mut work.contours,
756        output.contours.len(),
757        "$.contours",
758        "aggregate contour limit exceeded",
759    )?;
760    let points = output
761        .contours
762        .iter()
763        .try_fold(0usize, |total, contour| {
764            total.checked_add(contour.points.len())
765        })
766        .ok_or_else(|| resource("$.points", "aggregate point count overflowed"))?;
767    charge(
768        &mut work.points,
769        points,
770        "$.points",
771        "aggregate point limit exceeded",
772    )?;
773    work.peak_temporary_bezier_points = work
774        .peak_temporary_bezier_points
775        .max(output.peak_temporary_bezier_points);
776    Ok(())
777}
778
779fn charge(
780    total: &mut usize,
781    amount: usize,
782    _path: &'static str,
783    _message: &'static str,
784) -> Result<(), TextContourError> {
785    let next = *total + amount;
786    *total = next;
787    Ok(())
788}
789
790fn invalid(path: &'static str, message: &'static str) -> TextContourError {
791    TextContourError {
792        kind: TextContourErrorKind::InvalidInput,
793        path: path.to_owned(),
794        message,
795    }
796}
797
798fn resource(path: &'static str, message: &'static str) -> TextContourError {
799    TextContourError {
800        kind: TextContourErrorKind::ResourceLimit,
801        path: path.to_owned(),
802        message,
803    }
804}
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809    use cad_text_realization::OpenTypeTag;
810
811    fn feature(tag: &str, start: u32, end: u32) -> ShapingFeature {
812        ShapingFeature {
813            end,
814            start,
815            tag: OpenTypeTag(tag.to_owned()),
816            value: 0,
817        }
818    }
819
820    #[test]
821    fn utf8_and_global_feature_ranges_rebase_in_source_order_under_exact_work() {
822        let features = vec![
823            feature("kern", 0, u32::MAX),
824            feature("liga", 0, 2),
825            feature("calt", 3, 4),
826        ];
827        let mut work = AggregateWork::default();
828        let first = rebase_features(&features, 0..2, &mut work).unwrap();
829        let second = rebase_features(&features, 3..4, &mut work).unwrap();
830
831        assert_eq!(
832            first
833                .iter()
834                .map(|item| (item.tag.0.as_str(), item.start, item.end))
835                .collect::<Vec<_>>(),
836            [("kern", 0, u32::MAX), ("liga", 0, 2)]
837        );
838        assert_eq!(
839            second
840                .iter()
841                .map(|item| (item.tag.0.as_str(), item.start, item.end))
842                .collect::<Vec<_>>(),
843            [("kern", 0, u32::MAX), ("calt", 0, 1)]
844        );
845        assert_eq!(work.feature_inspections, 6);
846        assert_eq!(work.feature_applications, 4);
847    }
848}