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

cad_text_realization/
font_outline.rs

1//! Bounded native glyph-outline extraction over caller-supplied font bytes.
2
3use crate::contract::FiniteFloat;
4use crate::contract::{
5    FontVariationCoordinate, OutlineClose, OutlineCommand, OutlineCurveTo, OutlineLineTo,
6    OutlineMoveTo, OutlineQuadTo,
7};
8use sha2::{Digest, Sha256};
9use skrifa::{
10    FontRef as SkrifaFontRef, GlyphId as SkrifaGlyphId, MetadataProvider,
11    instance::{LocationRef, Size},
12    outline::{DrawSettings, Hinting, HintingInstance, OutlinePen},
13};
14use std::collections::HashSet;
15use std::fmt;
16use ttf_parser::{Face, GlyphId, OutlineBuilder, Tag};
17
18/// Outline implementation and upstream parser version pinned by this workspace.
19pub const FONT_OUTLINE_ENGINE: &str = "ttf-parser-0.25.1";
20/// Safe-Rust hinted outline backend used for final KiCad cache parity.
21pub const HINTED_FONT_OUTLINE_ENGINE: &str = "skrifa-0.46.0";
22const KICAD_HINTED_PPEM: f32 = 358.25;
23// KiCad's rounded subscript/superscript face size 917 over the same four
24// internal units per pixel: `917 / 4`.
25const KICAD_SUBSCRIPT_HINTED_PPEM: f32 = 229.25;
26// Skrifa emits pixel coordinates. KiCad's FreeType path emits 26.6 values and
27// then applies 72 / 1152, leaving the equivalent four internal units per pixel.
28const KICAD_HIGH_RESOLUTION_SCALE: f32 = 4.0;
29
30/// Contract-aligned metadata for one out-of-band glyph request.
31#[derive(Clone, Copy, Debug)]
32pub struct FontOutlineRequest<'a> {
33    pub font_id: &'a str,
34    pub font_sha256: &'a str,
35    pub face_index: u32,
36    pub variations: &'a [FontVariationCoordinate],
37    pub glyph_id: u32,
38}
39
40/// Contract-aligned metadata shared by every glyph extracted from one face.
41#[derive(Clone, Copy, Debug)]
42pub struct FontOutlineFaceRequest<'a> {
43    pub font_id: &'a str,
44    pub font_sha256: &'a str,
45    pub face_index: u32,
46    pub variations: &'a [FontVariationCoordinate],
47}
48
49/// Validated, variation-configured face reusable across a bounded text run.
50pub struct FontOutlineFace<'a> {
51    face: Face<'a>,
52}
53
54/// Validated safe-Rust hinted face reusable across a bounded text run.
55pub struct HintedFontOutlineFace<'a> {
56    outlines: skrifa::outline::OutlineGlyphCollection<'a>,
57    hinting: HintingInstance,
58    units_per_em: u16,
59}
60
61/// Native outline in unscaled font design units.
62#[derive(Clone, Debug)]
63pub struct FontOutlineOutput {
64    pub commands: Vec<OutlineCommand>,
65    pub units_per_em: u16,
66}
67
68/// Stable failure categories for native outline extraction.
69#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70pub enum FontOutlineErrorKind {
71    ResourceLimit,
72    InvalidContract,
73    HashMismatch,
74    InvalidFont,
75    InvalidInput,
76    MissingOutline,
77}
78
79/// Fail-closed native outline extraction error.
80#[derive(Clone, Debug, Eq, PartialEq)]
81pub struct FontOutlineError {
82    pub kind: FontOutlineErrorKind,
83    pub path: String,
84    pub message: &'static str,
85}
86
87impl fmt::Display for FontOutlineError {
88    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89        write!(formatter, "{} at {}", self.message, self.path)
90    }
91}
92
93impl std::error::Error for FontOutlineError {}
94
95/// Extract one validated glyph outline without exposing the parser dependency.
96pub fn extract_font_outline_a0(
97    font_bytes: &[u8],
98    request: FontOutlineRequest<'_>,
99) -> Result<FontOutlineOutput, FontOutlineError> {
100    let face = FontOutlineFace::new(
101        font_bytes,
102        FontOutlineFaceRequest {
103            font_id: request.font_id,
104            font_sha256: request.font_sha256,
105            face_index: request.face_index,
106            variations: request.variations,
107        },
108    )?;
109    face.extract_glyph(request.glyph_id)
110}
111
112impl<'a> FontOutlineFace<'a> {
113    /// Validate and configure one face once for reuse across many glyphs.
114    pub fn new(
115        font_bytes: &'a [u8],
116        request: FontOutlineFaceRequest<'_>,
117    ) -> Result<Self, FontOutlineError> {
118        preflight_face(font_bytes, request)?;
119        validate_hash(font_bytes, request.font_sha256)?;
120        let mut face = Face::parse(font_bytes, request.face_index).map_err(|_| {
121            outline_error(
122                FontOutlineErrorKind::InvalidFont,
123                "$.face_index",
124                "font bytes or face index are invalid",
125            )
126        })?;
127        apply_variations(&mut face, request.variations)?;
128        Ok(Self { face })
129    }
130
131    /// Return the face's OpenType units per em.
132    pub fn units_per_em(&self) -> u16 {
133        self.face.units_per_em()
134    }
135
136    /// Extract one glyph. KiCad draws every outline command (#612).
137    pub fn extract_glyph(&self, glyph_id: u32) -> Result<FontOutlineOutput, FontOutlineError> {
138        let glyph_id = u16::try_from(glyph_id).map(GlyphId).map_err(|_| {
139            outline_error(
140                FontOutlineErrorKind::InvalidInput,
141                "$.glyph_id",
142                "glyph ID exceeds the OpenType uint16 range",
143            )
144        })?;
145        let mut builder = BoundedOutlineBuilder::new();
146        let outlined = self.face.outline_glyph(glyph_id, &mut builder).is_some();
147        if outlined {
148            builder.finish_open_contour();
149        }
150        if builder.exceeded {
151            return Err(outline_error(
152                FontOutlineErrorKind::ResourceLimit,
153                "$.commands",
154                "outline command count exceeds the configured limit",
155            ));
156        }
157        if !outlined {
158            if builder.saw_callback {
159                return Err(outline_error(
160                    FontOutlineErrorKind::InvalidFont,
161                    "$.glyph_id",
162                    "font emitted a partial malformed glyph outline",
163                ));
164            }
165            return Err(outline_error(
166                FontOutlineErrorKind::MissingOutline,
167                "$.glyph_id",
168                "font does not contain an outline for the requested glyph",
169            ));
170        }
171        Ok(FontOutlineOutput {
172            commands: builder.commands,
173            units_per_em: self.face.units_per_em(),
174        })
175    }
176}
177
178impl<'a> HintedFontOutlineFace<'a> {
179    /// Build a FreeType-normal-target compatible hinted face from caller bytes.
180    pub fn new(
181        font_bytes: &'a [u8],
182        request: FontOutlineFaceRequest<'_>,
183    ) -> Result<Self, FontOutlineError> {
184        Self::new_with_ppem(font_bytes, request, KICAD_HINTED_PPEM)
185    }
186
187    /// Build a hinted face at KiCad's subscript/superscript run size.
188    pub(crate) fn new_subscript(
189        font_bytes: &'a [u8],
190        request: FontOutlineFaceRequest<'_>,
191    ) -> Result<Self, FontOutlineError> {
192        Self::new_with_ppem(font_bytes, request, KICAD_SUBSCRIPT_HINTED_PPEM)
193    }
194
195    fn new_with_ppem(
196        font_bytes: &'a [u8],
197        request: FontOutlineFaceRequest<'_>,
198        ppem: f32,
199    ) -> Result<Self, FontOutlineError> {
200        preflight_face(font_bytes, request)?;
201        validate_hash(font_bytes, request.font_sha256)?;
202        if !request.variations.is_empty() {
203            return Err(outline_error(
204                FontOutlineErrorKind::InvalidInput,
205                "$.variations",
206                "hinted outline variation coordinates are not yet supported",
207            ));
208        }
209        let font = SkrifaFontRef::from_index(font_bytes, request.face_index).map_err(|_| {
210            outline_error(
211                FontOutlineErrorKind::InvalidFont,
212                "$.face_index",
213                "font bytes or face index are invalid",
214            )
215        })?;
216        let units_per_em = Face::parse(font_bytes, request.face_index)
217            .map_err(|_| {
218                outline_error(
219                    FontOutlineErrorKind::InvalidFont,
220                    "$.face_index",
221                    "font bytes or face index are invalid",
222                )
223            })?
224            .units_per_em();
225        let outlines = font.outline_glyphs();
226        let hinting = HintingInstance::new(
227            &outlines,
228            Size::new(ppem),
229            LocationRef::default(),
230            skrifa::outline::HintingOptions::default(),
231        )
232        .map_err(|_| {
233            outline_error(
234                FontOutlineErrorKind::InvalidFont,
235                "$.font",
236                "font hinting instance could not be initialized",
237            )
238        })?;
239        Ok(Self {
240            outlines,
241            hinting,
242            units_per_em,
243        })
244    }
245
246    /// Return the face's OpenType units per em.
247    pub fn units_per_em(&self) -> u16 {
248        self.units_per_em
249    }
250
251    /// Return the scratch-memory requirement for one embedded-hinted draw.
252    pub fn glyph_hinting_memory_size(&self, glyph_id: u32) -> Result<usize, FontOutlineError> {
253        let glyph = self.outline_glyph(glyph_id)?;
254        Ok(glyph.draw_memory_size(Hinting::Embedded))
255    }
256
257    /// Extract one glyph. KiCad draws every outline command (#612).
258    pub fn extract_glyph(&self, glyph_id: u32) -> Result<FontOutlineOutput, FontOutlineError> {
259        let glyph = self.outline_glyph(glyph_id)?;
260        let memory_size = glyph.draw_memory_size(Hinting::Embedded);
261        let mut memory = vec![0_u8; memory_size];
262        let mut builder = BoundedOutlineBuilder::new_scaled(KICAD_HIGH_RESOLUTION_SCALE);
263        glyph
264            .draw(
265                DrawSettings::hinted(&self.hinting, false).with_memory(Some(&mut memory)),
266                &mut builder,
267            )
268            .map_err(|_| {
269                outline_error(
270                    FontOutlineErrorKind::InvalidFont,
271                    "$.glyph_id",
272                    "hinted glyph outline could not be drawn",
273                )
274            })?;
275        builder.finish_open_contour();
276        if builder.exceeded {
277            return Err(outline_error(
278                FontOutlineErrorKind::ResourceLimit,
279                "$.commands",
280                "outline command count exceeds the configured limit",
281            ));
282        }
283        if !builder.saw_callback {
284            return Err(outline_error(
285                FontOutlineErrorKind::MissingOutline,
286                "$.glyph_id",
287                "font does not contain an outline for the requested glyph",
288            ));
289        }
290        Ok(FontOutlineOutput {
291            commands: builder.commands,
292            units_per_em: self.units_per_em,
293        })
294    }
295
296    fn outline_glyph(
297        &self,
298        glyph_id: u32,
299    ) -> Result<skrifa::outline::OutlineGlyph<'a>, FontOutlineError> {
300        self.outlines
301            .get(SkrifaGlyphId::from(glyph_id))
302            .ok_or_else(|| {
303                outline_error(
304                    FontOutlineErrorKind::MissingOutline,
305                    "$.glyph_id",
306                    "font does not contain an outline for the requested glyph",
307                )
308            })
309    }
310}
311
312fn preflight_face(
313    _font_bytes: &[u8],
314    request: FontOutlineFaceRequest<'_>,
315) -> Result<(), FontOutlineError> {
316    validate_request_contract(request)
317}
318
319fn validate_request_contract(request: FontOutlineFaceRequest<'_>) -> Result<(), FontOutlineError> {
320    if !valid_stable_text_id(request.font_id) || !valid_sha256(request.font_sha256) {
321        return Err(outline_error(
322            FontOutlineErrorKind::InvalidContract,
323            "$",
324            "outline request metadata does not satisfy the a0 contract",
325        ));
326    }
327    validate_variation_metadata(request.variations)
328}
329
330fn validate_variation_metadata(
331    variations: &[FontVariationCoordinate],
332) -> Result<(), FontOutlineError> {
333    let mut variation_tags = HashSet::with_capacity(variations.len());
334    for (index, variation) in variations.iter().enumerate() {
335        let tag = variation.axis.0.as_str();
336        if tag.len() != 4
337            || !tag.bytes().all(|byte| (b' '..=b'~').contains(&byte))
338            || !variation_tags.insert(tag)
339        {
340            return Err(outline_error(
341                FontOutlineErrorKind::InvalidContract,
342                format!("$.variations[{index}].axis"),
343                "variation axes must be printable, four-byte, and unique",
344            ));
345        }
346    }
347    Ok(())
348}
349
350fn valid_sha256(value: &str) -> bool {
351    value.len() == 64
352        && value
353            .bytes()
354            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
355}
356
357fn valid_stable_text_id(value: &str) -> bool {
358    let mut bytes = value.bytes();
359    bytes
360        .next()
361        .is_some_and(|byte| byte.is_ascii_alphanumeric())
362        && bytes.all(|byte| byte.is_ascii_alphanumeric() || b"._:-".contains(&byte))
363}
364
365fn validate_hash(font_bytes: &[u8], expected: &str) -> Result<(), FontOutlineError> {
366    const HEX: &[u8; 16] = b"0123456789abcdef";
367    let matches = Sha256::digest(font_bytes)
368        .iter()
369        .zip(expected.as_bytes().as_chunks::<2>().0)
370        .all(|(byte, pair)| *pair == [HEX[(byte >> 4) as usize], HEX[(byte & 0x0f) as usize]]);
371    if matches {
372        Ok(())
373    } else {
374        Err(outline_error(
375            FontOutlineErrorKind::HashMismatch,
376            "$.font_sha256",
377            "font buffer does not match the declared SHA-256",
378        ))
379    }
380}
381
382fn apply_variations(
383    face: &mut Face<'_>,
384    variations: &[FontVariationCoordinate],
385) -> Result<(), FontOutlineError> {
386    if variations.is_empty() {
387        return Ok(());
388    }
389    let axis_tags = face
390        .variation_axes()
391        .into_iter()
392        .map(|axis| axis.tag)
393        .collect::<HashSet<_>>();
394    if axis_tags.is_empty() {
395        return Err(outline_error(
396            FontOutlineErrorKind::InvalidInput,
397            "$.variations",
398            "font does not support variation coordinates",
399        ));
400    }
401    for (index, variation) in variations.iter().enumerate() {
402        let bytes: [u8; 4] = variation.axis.0.as_bytes().try_into().map_err(|_| {
403            outline_error(
404                FontOutlineErrorKind::InvalidContract,
405                format!("$.variations[{index}].axis"),
406                "variation axis must be a four-byte OpenType tag",
407            )
408        })?;
409        let tag = Tag::from_bytes(&bytes);
410        if !axis_tags.contains(&tag) {
411            return Err(outline_error(
412                FontOutlineErrorKind::InvalidInput,
413                format!("$.variations[{index}].axis"),
414                "font does not define the requested variation axis",
415            ));
416        }
417        let value = variation.value.get() as f32;
418        if !value.is_finite() {
419            return Err(outline_error(
420                FontOutlineErrorKind::InvalidInput,
421                format!("$.variations[{index}].value"),
422                "variation value is outside the finite f32 range",
423            ));
424        }
425        face.set_variation(tag, value).ok_or_else(|| {
426            outline_error(
427                FontOutlineErrorKind::InvalidFont,
428                format!("$.variations[{index}]"),
429                "font variation coordinates could not be applied",
430            )
431        })?;
432    }
433    Ok(())
434}
435
436struct BoundedOutlineBuilder {
437    commands: Vec<OutlineCommand>,
438    exceeded: bool,
439    saw_callback: bool,
440    contour_open: bool,
441    coordinate_scale: f32,
442}
443
444impl BoundedOutlineBuilder {
445    fn new() -> Self {
446        Self::new_scaled(1.0)
447    }
448
449    fn new_scaled(coordinate_scale: f32) -> Self {
450        Self {
451            commands: Vec::with_capacity(256),
452            exceeded: false,
453            saw_callback: false,
454            contour_open: false,
455            coordinate_scale,
456        }
457    }
458
459    fn push(&mut self, command: OutlineCommand) {
460        self.saw_callback = true;
461        self.commands.push(command);
462    }
463
464    fn finish_open_contour(&mut self) {
465        if self.contour_open {
466            OutlineBuilder::close(self);
467        }
468    }
469
470    fn scaled(&self, value: f32) -> FiniteFloat {
471        finite(value * self.coordinate_scale)
472    }
473}
474
475impl OutlineBuilder for BoundedOutlineBuilder {
476    fn move_to(&mut self, x: f32, y: f32) {
477        self.contour_open = true;
478        self.push(
479            OutlineMoveTo {
480                kind: "move_to".to_owned(),
481                x: self.scaled(x),
482                y: self.scaled(y),
483            }
484            .into(),
485        );
486    }
487
488    fn line_to(&mut self, x: f32, y: f32) {
489        self.push(
490            OutlineLineTo {
491                kind: "line_to".to_owned(),
492                x: self.scaled(x),
493                y: self.scaled(y),
494            }
495            .into(),
496        );
497    }
498
499    fn quad_to(&mut self, control_x: f32, control_y: f32, x: f32, y: f32) {
500        self.push(
501            OutlineQuadTo {
502                control_x: self.scaled(control_x),
503                control_y: self.scaled(control_y),
504                kind: "quad_to".to_owned(),
505                x: self.scaled(x),
506                y: self.scaled(y),
507            }
508            .into(),
509        );
510    }
511
512    fn curve_to(
513        &mut self,
514        control1_x: f32,
515        control1_y: f32,
516        control2_x: f32,
517        control2_y: f32,
518        x: f32,
519        y: f32,
520    ) {
521        self.push(
522            OutlineCurveTo {
523                control1_x: self.scaled(control1_x),
524                control1_y: self.scaled(control1_y),
525                control2_x: self.scaled(control2_x),
526                control2_y: self.scaled(control2_y),
527                kind: "curve_to".to_owned(),
528                x: self.scaled(x),
529                y: self.scaled(y),
530            }
531            .into(),
532        );
533    }
534
535    fn close(&mut self) {
536        self.push(
537            OutlineClose {
538                kind: "close".to_owned(),
539            }
540            .into(),
541        );
542        self.contour_open = false;
543    }
544}
545
546impl OutlinePen for BoundedOutlineBuilder {
547    fn move_to(&mut self, x: f32, y: f32) {
548        OutlineBuilder::move_to(self, x, y);
549    }
550
551    fn line_to(&mut self, x: f32, y: f32) {
552        OutlineBuilder::line_to(self, x, y);
553    }
554
555    fn quad_to(&mut self, control_x: f32, control_y: f32, x: f32, y: f32) {
556        OutlineBuilder::quad_to(self, control_x, control_y, x, y);
557    }
558
559    fn curve_to(
560        &mut self,
561        control1_x: f32,
562        control1_y: f32,
563        control2_x: f32,
564        control2_y: f32,
565        x: f32,
566        y: f32,
567    ) {
568        OutlineBuilder::curve_to(self, control1_x, control1_y, control2_x, control2_y, x, y);
569    }
570
571    fn close(&mut self) {
572        OutlineBuilder::close(self);
573    }
574}
575
576fn finite(value: f32) -> FiniteFloat {
577    FiniteFloat::try_from(f64::from(value)).expect("OpenType outline coordinates are finite")
578}
579
580fn outline_error(
581    kind: FontOutlineErrorKind,
582    path: impl Into<String>,
583    message: &'static str,
584) -> FontOutlineError {
585    FontOutlineError {
586        kind,
587        path: path.into(),
588        message,
589    }
590}