Skip to main content

font_model/
parse.rs

1//! The bridge from [`font-parse`]'s borrowed views to this owned model.
2//!
3//! Everything else in the crate takes owned data; [`from_sfnt`] is the one
4//! function that takes foreign bytes. It runs the L0 parser (which is total —
5//! malformed input yields a typed [`ParseError`]) and *resolves* what it finds
6//! into the model: outlines become [`Command`] streams, `hmtx` pairs become
7//! per-glyph [`Metrics`], `cmap` becomes owned subtables, `name` becomes owned
8//! strings.
9//!
10//! What the bridge does **not** do:
11//!
12//! - **CFF outlines.** `font-parse` exposes the `CFF` table raw and does not
13//!   decode charstrings; an `'OTTO'` font loads with empty outlines and a
14//!   `CFF ` opaque table attached.
15//! - **Layout tables.** `GSUB`/`GPOS`/`GDEF` are carried through opaquely so a
16//!   read-modify-write round trip stays lossless. `font-shape` reorders runs by
17//!   codepoint class rather than interpreting `GSUB`.
18//! - **Variation.** `gvar` deltas are not applied; the default instance's
19//!   outlines are what load.
20//! - **Instructions.** Hinting bytecode is not interpreted; outlines load
21//!   unhinted.
22
23use alloc::string::String;
24use alloc::vec::Vec;
25use font_parse::{FontRef, GlyphOutline, OutlinePoint};
26
27use crate::cmap::{self, Cmap, CmapSubtable};
28use crate::error::ModelError;
29use crate::font::{Font, Kerning, TableTag};
30use crate::glyph::{Glyph, GlyphId};
31use crate::metrics::{FontMetrics, Metrics};
32use crate::name::NameRecord;
33use crate::os2::Os2Metrics;
34use crate::outline::{Outline, Path};
35
36/// Tables carried through the model opaquely, in load order.
37///
38/// Layout tables first (they are the ones a layout engine needs and this crate
39/// must not lose), then everything else the parser knows, then any unknown tag
40/// found in the directory — so a read-modify-write round trip loses nothing.
41const OPAQUE_TAGS: [TableTag; 3] = [crate::TAG_GSUB, crate::TAG_GPOS, *b"GDEF"];
42
43/// Resolve a parsed font into the owned model.
44///
45/// # Errors
46/// [`ModelError::Parse`] when the parser rejects the bytes, or the model
47/// rejects what the parser found — a `cmap` referencing a glyph past
48/// `numGlyphs`, or an `hmtx` inconsistency the model catches.
49///
50/// ```
51/// # fn main() -> Result<(), font_model::ModelError> {
52/// // A font with no bytes at all is a parse error, not a panic.
53/// assert!(font_model::from_sfnt(&[]).is_err());
54/// # Ok(())
55/// # }
56/// ```
57#[allow(clippy::result_large_err)]
58pub fn from_sfnt(bytes: &[u8]) -> Result<Font, ModelError> {
59    let parsed = FontRef::new(bytes)?;
60    from_font_ref(&parsed)
61}
62
63/// Resolve an already-parsed [`FontRef`] into the owned model.
64///
65/// Takes the parser's view by reference so a caller who already has one does
66/// not re-parse.
67///
68/// # Errors
69/// See [`from_sfnt`].
70#[allow(clippy::result_large_err)]
71pub fn from_font_ref(parsed: &FontRef<'_>) -> Result<Font, ModelError> {
72    let units_per_em = parsed.head()?.units_per_em()?;
73    let num_glyphs = parsed.num_glyphs();
74    if num_glyphs == 0 {
75        return Err(ModelError::UnknownGlyph {
76            glyph: GlyphId::NOTDEF,
77            glyph_count: 0,
78        });
79    }
80    // -- glyphs ------------------------------------------------------------
81    let hmtx = parsed.hmtx().ok();
82    let mut glyphs = Vec::with_capacity(usize::from(num_glyphs));
83    for index in 0..num_glyphs {
84        let id = GlyphId::new(index);
85        let outline = parsed
86            .outline(font_parse::GlyphId::new(u32::from(index)))
87            .unwrap_or(None);
88        let outline = outline.map(to_outline).unwrap_or_default();
89        let (advance, lsb) = match &hmtx {
90            Some(h) => (
91                h.advance(index).unwrap_or(0),
92                h.left_side_bearing(index).unwrap_or(0),
93            ),
94            None => (0, 0),
95        };
96        glyphs.push(Glyph::new(id, advance, lsb, outline));
97    }
98    // -- cmap --------------------------------------------------------------
99    let cmap = load_cmap(parsed)?;
100    // -- headers -----------------------------------------------------------
101    let mut metrics = FontMetrics::derive(&glyphs);
102    if let Ok(hhea) = parsed.hhea() {
103        if let (Ok(a), Ok(d), Ok(g)) = (hhea.ascender(), hhea.descender(), hhea.line_gap()) {
104            metrics.ascender = a;
105            metrics.descender = d;
106            metrics.line_gap = g;
107        }
108    }
109    if let Some(v) = load_vertical(parsed) {
110        metrics.vertical = Some(v);
111    }
112    // -- name --------------------------------------------------------------
113    let mut names = Vec::new();
114    if let Ok(table) = parsed.name() {
115        if let Ok(records) = table.records() {
116            for r in records {
117                names.push(NameRecord::with_locale(
118                    r.name_id,
119                    r.platform_id,
120                    r.encoding_id,
121                    r.language_id,
122                    decode_name(&r),
123                ));
124            }
125        }
126    }
127    // -- OS/2 --------------------------------------------------------------
128    let os2 = parsed.os2().ok().map(|t| load_os2(&t));
129    // -- kerning -----------------------------------------------------------
130    let kerning = parsed
131        .table_by_tag(font_parse::Tag::new(b"kern"))
132        .map_or_else(Kerning::new, Kerning::from_kern_bytes);
133    // -- opaque tables -----------------------------------------------------
134    let mut tables: Vec<(TableTag, Vec<u8>)> = Vec::new();
135    for tag in OPAQUE_TAGS {
136        if let Some(data) = raw_table(parsed, tag) {
137            tables.push((tag, data));
138        }
139    }
140    for (raw_tag, _checksum, _offset, _length) in parsed.table_directory() {
141        if tables.iter().any(|(t, _)| *t == raw_tag) {
142            continue;
143        }
144        if is_modelled(raw_tag) {
145            continue;
146        }
147        if let Some(data) = parsed.table_by_tag(font_parse::Tag::new(&raw_tag)) {
148            tables.push((raw_tag, data.to_vec()));
149        }
150    }
151    // A font whose `cmap` or kerning points past `numGlyphs` is malformed as
152    // a *model*; report it precisely rather than dropping the entry silently.
153    validate_references(&glyphs, &cmap, &kerning)?;
154    Ok(Font::from_parts(
155        units_per_em,
156        metrics,
157        glyphs,
158        cmap,
159        names,
160        os2,
161        kerning,
162        tables,
163    ))
164}
165
166/// Raw bytes for one four-byte tag.
167fn raw_table(parsed: &FontRef<'_>, tag: TableTag) -> Option<Vec<u8>> {
168    parsed
169        .table_by_tag(font_parse::Tag::new(&tag))
170        .map(<[u8]>::to_vec)
171}
172
173/// Tags the model interprets directly and therefore does not carry opaquely.
174fn is_modelled(tag: TableTag) -> bool {
175    const MODELLED: [TableTag; 10] = [
176        *b"cmap", *b"head", *b"hhea", *b"hmtx", *b"maxp", *b"name", *b"OS/2", *b"glyf", *b"loca",
177        *b"kern",
178    ];
179    MODELLED.contains(&tag)
180}
181
182/// Load the `cmap` into owned subtables.
183///
184/// Every Unicode-capable subtable is enumerated and decoded — the model keeps
185/// both format 4 and format 12, so a font with a UCS-4 table keeps its astral
186/// coverage rather than collapsing to the BMP.
187fn load_cmap(parsed: &FontRef<'_>) -> Result<Cmap, ModelError> {
188    let Ok(table) = parsed.cmap() else {
189        return Ok(Cmap::format4());
190    };
191    let mut out = Cmap::new();
192    let records = table.records();
193    for (i, record) in records.iter().enumerate() {
194        if !record.is_unicode() {
195            continue;
196        }
197        let Ok(sub) = table.subtable(i) else { continue };
198        let format = match sub {
199            font_parse::CmapSubtable::Format4(_) => 4,
200            font_parse::CmapSubtable::Format12(_) => 12,
201            // Formats 0 and 6 are read by the parser but are not modelled for
202            // encoding; fold them into the format-4 representation.
203            font_parse::CmapSubtable::Format0(_) | font_parse::CmapSubtable::Format6(_) => 4,
204        };
205        let entries = enumerate_subtable(&sub);
206        if entries.is_empty() {
207            continue;
208        }
209        out.subtables_mut()
210            .push(cmap::from_entries(&entries, format));
211    }
212    if out.subtables().is_empty() {
213        out.subtables_mut().push(CmapSubtable::empty_format4());
214    }
215    Ok(out)
216}
217
218/// Enumerate a parsed subtable's mapped codepoints.
219///
220/// The parser's view offers point lookups, not enumeration, so the range is
221/// walked: surrogates are skipped (they are not scalar values), and a
222/// subtable that reaches above the BMP costs 4× the walk of a BMP one.
223fn enumerate_subtable(sub: &font_parse::CmapSubtable<'_>) -> Vec<(u32, GlyphId)> {
224    const MAX: u32 = 0x10_FFFF;
225    let mut out = Vec::new();
226    let mut cp = 0u32;
227    while cp <= MAX {
228        if !(0xD800..=0xDFFF).contains(&cp) {
229            if let Some(gid) = sub.lookup(cp) {
230                out.push((cp, GlyphId::new(gid)));
231            }
232        }
233        cp += 1;
234    }
235    out
236}
237
238/// Decode a `name` record's bytes to an owned string.
239fn decode_name(record: &font_parse::NameRecord<'_>) -> String {
240    record.decode()
241}
242
243/// Load `OS/2` fields, using the model defaults for anything absent.
244fn load_os2(t: &font_parse::Os2Table<'_>) -> Os2Metrics {
245    let mut o = Os2Metrics::default();
246    if let Ok(v) = t.version() {
247        o.version = v;
248    }
249    if let Ok(v) = t.avg_char_width() {
250        o.avg_char_width = v;
251    }
252    if let Ok(v) = t.weight_class() {
253        o.weight_class = v;
254    }
255    if let Ok(v) = t.width_class() {
256        o.width_class = v;
257    }
258    if let Ok(v) = t.fs_type() {
259        o.fs_type = v;
260    }
261    if let Ok(p) = t.panose() {
262        for (slot, byte) in o.panose.iter_mut().zip(p.iter().take(10)) {
263            *slot = *byte;
264        }
265    }
266    if let Ok(r) = t.unicode_ranges() {
267        o.unicode_ranges = r;
268    }
269    if let Ok(v) = t.vendor_id() {
270        for (slot, byte) in o.vendor_id.iter_mut().zip(v.iter().take(4)) {
271            *slot = *byte;
272        }
273    }
274    if let Ok(v) = t.fs_selection() {
275        o.fs_selection = v;
276    }
277    if let Ok(v) = t.typo_ascender() {
278        o.typo_ascender = v;
279    }
280    if let Ok(v) = t.typo_descender() {
281        o.typo_descender = v;
282    }
283    if let Ok(v) = t.typo_line_gap() {
284        o.typo_line_gap = v;
285    }
286    if let Ok(v) = t.win_ascent() {
287        o.win_ascent = v;
288    }
289    if let Ok(v) = t.win_descent() {
290        o.win_descent = v;
291    }
292    if let Ok(v) = t.code_page_ranges() {
293        o.code_page_ranges = v;
294    }
295    if let Ok(v) = t.x_height() {
296        o.x_height = v;
297    }
298    if let Ok(v) = t.cap_height() {
299        o.cap_height = v;
300    }
301    o
302}
303
304/// Load `vhea` + `vmtx` into the vertical header, when both are present.
305fn load_vertical(parsed: &FontRef<'_>) -> Option<crate::VerticalMetrics> {
306    // Both tables must be present: `vhea` alone carries no per-glyph advances,
307    // and `vmtx` alone has no line box to interpret it against.
308    let vhea = parsed.table_by_tag(font_parse::Tag::new(b"vhea"))?;
309    parsed.table_by_tag(font_parse::Tag::new(b"vmtx"))?;
310    let be16 = |at: usize| -> i16 {
311        match (vhea.get(at), vhea.get(at + 1)) {
312            (Some(&a), Some(&b)) => i16::from_be_bytes([a, b]),
313            _ => 0,
314        }
315    };
316    Some(crate::VerticalMetrics {
317        ascender: be16(4),
318        descender: be16(6),
319        line_gap: be16(8),
320        advance_height_max: be16(10).max(0) as u16,
321        min_top_side_bearing: be16(12),
322        min_bottom_side_bearing: be16(14),
323        y_max_extent: be16(16),
324    })
325}
326
327/// Reject a `cmap` or kerning set that points at a glyph the store lacks.
328fn validate_references(glyphs: &[Glyph], cmap: &Cmap, kerning: &Kerning) -> Result<(), ModelError> {
329    for cp in cmap.codepoints().iter() {
330        if let Some(gid) = cmap.lookup(*cp) {
331            if glyphs.get(gid.index()).is_none() {
332                return Err(ModelError::UnknownGlyph {
333                    glyph: gid,
334                    glyph_count: glyphs.len(),
335                });
336            }
337        }
338    }
339    for pair in kerning.iter() {
340        for gid in [pair.left, pair.right] {
341            if glyphs.get(gid.index()).is_none() {
342                return Err(ModelError::UnknownGlyph {
343                    glyph: gid,
344                    glyph_count: glyphs.len(),
345                });
346            }
347        }
348    }
349    Ok(())
350}
351
352/// Convert a parser contour list into a resolved [`Outline`].
353///
354/// TrueType contours carry on-curve and off-curve (quadratic control) points.
355/// Two off-curve points in a row imply an on-curve point at their midpoint,
356/// and a contour that starts off-curve is started at the midpoint of its last
357/// and first points — both handled here, so the resulting [`Path`] is a
358/// proper segment stream rather than a raw point dump.
359#[must_use]
360pub fn to_outline(outline: GlyphOutline) -> Outline {
361    let mut out = Outline::new();
362    for contour in &outline.contours {
363        if let Some(path) = contour_to_path(&contour.points) {
364            out.push_contour(path);
365        }
366    }
367    out
368}
369
370/// Convert one contour's points into a closed [`Path`].
371fn contour_to_path(points: &[OutlinePoint]) -> Option<Path> {
372    let n = points.len();
373    if n == 0 {
374        return None;
375    }
376    if n == 1 {
377        let p = points.first()?;
378        let mut path = Path::starting_at(p.x, p.y);
379        path.close();
380        return Some(path);
381    }
382    // Start at an on-curve point; if there is none, start at the implied
383    // midpoint between the last and first off-curve points.
384    let start_index = points.iter().position(|p| p.on_curve).unwrap_or(0);
385    // The modulus keeps both lookups in range: `start_index < n` and `k < n`.
386    let first = points.get(start_index)?;
387    let last = points.get((start_index + n - 1) % n)?;
388    let last_xy = (last.x, last.y);
389    let (sx, sy) = if first.on_curve {
390        (first.x, first.y)
391    } else if last.on_curve {
392        last_xy
393    } else {
394        midpoint(last_xy, (first.x, first.y))
395    };
396    let mut path = Path::starting_at(sx, sy);
397    let mut pending_control: Option<(f32, f32)> = None;
398    // Walk the contour from *after* the chosen start point, wrapping around.
399    // The wrap-around segment back to the start is deliberately not emitted:
400    // `close` accounts for it implicitly, and drawing it twice would leave a
401    // redundant line in the segment stream.
402    for k in 1..n {
403        let Some(p) = points.get((start_index + k) % n) else {
404            break;
405        };
406        if p.on_curve {
407            match pending_control.take() {
408                Some(c) => {
409                    path.quad_to(c.0, c.1, p.x, p.y);
410                }
411                None => {
412                    path.line_to(p.x, p.y);
413                }
414            }
415        } else {
416            if let Some(c) = pending_control {
417                // Two controls in a row: the implied on-curve point between
418                // them is the segment's endpoint.
419                let m = midpoint(c, (p.x, p.y));
420                path.quad_to(c.0, c.1, m.0, m.1);
421            }
422            pending_control = Some((p.x, p.y));
423        }
424    }
425    // Close back to the start, finishing any dangling control.
426    if let Some(c) = pending_control {
427        path.quad_to(c.0, c.1, sx, sy);
428    }
429    path.close();
430    Some(path)
431}
432
433/// The midpoint of two points.
434fn midpoint(a: (f32, f32), b: (f32, f32)) -> (f32, f32) {
435    ((a.0 + b.0) * 0.5, (a.1 + b.1) * 0.5)
436}
437
438/// Per-glyph metrics, extracted from a glyph store — what a writer serialises
439/// into `hmtx`.
440///
441/// # Errors
442/// Never in the current model; the signature keeps the door open for metrics
443/// that can fail validation.
444#[allow(clippy::result_large_err)]
445pub fn hmtx_rows(glyphs: &[Glyph]) -> Result<Vec<Metrics>, ModelError> {
446    glyphs.iter().map(Glyph::metrics).collect()
447}
448
449#[cfg(test)]
450mod tests {
451    #![allow(
452        clippy::unwrap_used,
453        clippy::expect_used,
454        clippy::indexing_slicing,
455        clippy::panic
456    )]
457    use super::{contour_to_path, from_sfnt, hmtx_rows, to_outline};
458    use crate::cmap::Cmap;
459    use crate::font::{TAG_GPOS, TAG_GSUB};
460    use crate::glyph::GlyphId;
461    use crate::outline::{Command, Outline, Winding};
462    use alloc::vec;
463    use alloc::vec::Vec;
464
465    // Test harness: assertions legitimately panic; the lib target stays
466    // lint-clean.
467
468    fn pt(x: f32, y: f32, on: bool) -> font_parse::OutlinePoint {
469        font_parse::OutlinePoint { x, y, on_curve: on }
470    }
471
472    #[test]
473    fn rejects_non_font_bytes() {
474        assert!(from_sfnt(&[]).is_err());
475        assert!(
476            from_sfnt(&[0u8; 64]).is_err(),
477            "a zeroed buffer is not a font"
478        );
479    }
480
481    #[test]
482    fn contour_with_only_on_curve_points_becomes_lines() {
483        let path = contour_to_path(&[
484            pt(0.0, 0.0, true),
485            pt(100.0, 0.0, true),
486            pt(0.0, 100.0, true),
487        ])
488        .expect("contour");
489        // MoveTo + two lines + Close.
490        assert_eq!(path.commands().len(), 4);
491        assert!(matches!(path.commands()[1], Command::LineTo(..)));
492        assert!(path.is_closed());
493        // A right triangle with legs of 100: half of 100 x 100.
494        assert!((path.area() - 5000.0).abs() < 1e-2, "{}", path.area());
495    }
496
497    #[test]
498    fn contour_with_one_control_becomes_a_quad() {
499        // on, off, on, on -> one quad then one line.
500        let path = contour_to_path(&[
501            pt(0.0, 0.0, true),
502            pt(50.0, 100.0, false),
503            pt(100.0, 0.0, true),
504            pt(100.0, -100.0, true),
505        ])
506        .expect("contour");
507        assert!(matches!(path.commands()[1], Command::QuadTo(..)));
508        assert!(matches!(path.commands()[2], Command::LineTo(..)));
509        assert_eq!(path.commands().len(), 4, "MoveTo, quad, line, Close");
510        // Exact: the quad contributes -10000/3 of signed area and the closing
511        // edge -5000, for -25000/3 overall.
512        assert!(
513            (path.signed_area() + 8_333.333).abs() < 1e-2,
514            "area {}",
515            path.signed_area()
516        );
517    }
518
519    #[test]
520    fn two_controls_in_a_row_imply_an_on_curve_midpoint() {
521        // on, off, off, on: the two controls' midpoint becomes the endpoint
522        // of the first quad, so the contour has two quads.
523        let path = contour_to_path(&[
524            pt(0.0, 0.0, true),
525            pt(50.0, 100.0, false),
526            pt(50.0, -100.0, false),
527            pt(100.0, 0.0, true),
528        ])
529        .expect("contour");
530        let quads = path
531            .commands()
532            .iter()
533            .filter(|c| matches!(c, Command::QuadTo(..)))
534            .count();
535        assert_eq!(quads, 2, "implied midpoint split the segment");
536        // Midpoint of (50,100) and (50,-100) is (50,0).
537        assert!(matches!(
538            path.commands()[1],
539            Command::QuadTo(50.0, 100.0, 50.0, 0.0)
540        ));
541    }
542
543    #[test]
544    fn contour_starting_off_curve_starts_at_the_midpoint() {
545        // off, on, off: start index 1 (the on-curve point), so the contour
546        // begins there.
547        let path = contour_to_path(&[
548            pt(50.0, 100.0, false),
549            pt(0.0, 0.0, true),
550            pt(-50.0, 100.0, false),
551        ])
552        .expect("contour");
553        assert_eq!(path.start_point(), (0.0, 0.0));
554        assert!(path.is_closed());
555        // A contour with no on-curve point at all starts at the implied
556        // midpoint of the last and first points — here (0, 0) and (0, 100).
557        let all_off = contour_to_path(&[
558            pt(0.0, 0.0, false),
559            pt(100.0, 0.0, false),
560            pt(0.0, 100.0, false),
561        ])
562        .expect("contour");
563        assert_eq!(all_off.start_point(), (0.0, 50.0));
564        assert!(all_off.is_closed());
565    }
566
567    #[test]
568    fn degenerate_contours() {
569        assert!(contour_to_path(&[]).is_none());
570        let single = contour_to_path(&[pt(5.0, 5.0, true)]).expect("contour");
571        assert_eq!(single.len(), 2);
572        assert_eq!(single.winding(), Winding::Degenerate);
573        // All points identical: zero area, no panic.
574        let same = contour_to_path(&[pt(1.0, 1.0, true), pt(1.0, 1.0, true), pt(1.0, 1.0, false)])
575            .expect("contour");
576        assert_eq!(same.area(), 0.0);
577    }
578
579    #[test]
580    fn to_outline_assembles_contours() {
581        let outline = font_parse::GlyphOutline {
582            contours: vec![
583                font_parse::Contour {
584                    points: vec![
585                        pt(0.0, 0.0, true),
586                        pt(10.0, 0.0, true),
587                        pt(10.0, 10.0, true),
588                    ],
589                },
590                font_parse::Contour {
591                    points: vec![
592                        pt(20.0, 0.0, true),
593                        pt(30.0, 0.0, true),
594                        pt(30.0, 10.0, true),
595                    ],
596                },
597                font_parse::Contour { points: Vec::new() },
598            ],
599        };
600        let o = to_outline(outline);
601        assert_eq!(o.len(), 2, "the empty contour was dropped");
602        assert!(o.validate(GlyphId::new(1)).is_ok());
603        assert_eq!(o.bbox().expect("bbox").max_x(), 30.0);
604    }
605
606    #[test]
607    fn hmtx_rows_follow_the_glyph_store() {
608        let glyphs = crate::glyph::stub_glyphs(&[0x41]);
609        let rows = hmtx_rows(&glyphs).expect("rows");
610        assert_eq!(rows.len(), glyphs.len());
611        assert_eq!(rows[1].advance_width(), 600);
612    }
613
614    #[test]
615    fn opaque_tag_helpers() {
616        assert_eq!(TAG_GSUB, *b"GSUB");
617        assert_eq!(TAG_GPOS, *b"GPOS");
618        // The model's own tables are not carried opaquely.
619        assert!(super::is_modelled(*b"cmap"));
620        assert!(super::is_modelled(*b"head"));
621        assert!(!super::is_modelled(*b"GSUB"));
622        assert!(!super::is_modelled(*b"CFF "));
623    }
624
625    #[test]
626    fn empty_outline_default_is_blank() {
627        let o = Outline::new();
628        assert!(to_outline(font_parse::GlyphOutline {
629            contours: Vec::new()
630        })
631        .is_empty());
632        assert!(o.is_empty());
633        // A cmap with no subtables is tolerated by identity_cmap's guard.
634        assert!(Cmap::new().lookup(0x41).is_none());
635    }
636}