Skip to main content

sdf_text/
vector_font.rs

1//! Parsed font with real typographic metrics and kerning — a port of lib3's
2//! `src/sdf-text/VectorFont.js`, which itself is a thin layer over opentype.js.
3//!
4//! The grader is `tests/golden/font_roboto.json`, dumped from opentype.js
5//! 2.0.0, so this module's job is not "be a correct font library" but "be
6//! opentype.js". Three places where that means *not* using the obvious
7//! `ttf-parser` call:
8//!
9//! 1. **Outline commands** (`glyph_path`). opentype.js walks each TrueType
10//!    contour starting from its *last* point and then iterates every point of
11//!    the contour, so it emits one segment per point — including a final
12//!    segment back to the point it moved to, and a degenerate `L` at every
13//!    on-curve point that terminates a `Q`. `ttf-parser`'s `OutlineBuilder`
14//!    emits the clean form. We reproduce opentype's form by parsing `glyf`
15//!    ourselves, because the command list is graded verbatim.
16//! 2. **Ink bbox** (`bounding_box`). opentype's `Path.getBoundingBox` solves
17//!    the exact curve extrema (quads elevated to cubics with the 2/3–1/3 rule);
18//!    `ttf-parser`'s `glyph_bounding_box` returns the stored `glyf` header box.
19//!    They disagree, and the difference moves every glyph quad.
20//! 3. **Kerning** (`kerning`). opentype.js's `getKerningValue` uses GPOS only —
21//!    and never falls back to `kern` — whenever the GPOS table exists, and
22//!    returns the *first* coverage hit over the type-2 lookups of the `kern`
23//!    feature in the default script's default langsys. PairPos format 2 returns
24//!    on the first covered subtable even when the class pair is zero.
25//!
26//! Metric precedence uses JS `||`, so a **zero** value falls through
27//! (`sTypoLineGap == 0` → `hhea.lineGap` → `0`). That is deliberate.
28
29use owned_ttf_parser::{AsFaceRef, Face, GlyphId, OwnedFace, Tag};
30
31use crate::error::Error;
32
33/// A path command in the opentype.js `Path.commands` vocabulary.
34///
35/// `Close` exists because `Glyph.path` (the Y-up path the bbox is measured on)
36/// contains `Z`; `Glyph.getPath(0, 0, unitsPerEm)` drops it (it only emits `Z`
37/// when the path is stroked), so the rasteriser never sees one.
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub enum PathCommand {
40    /// Starts a new subpath at `(x, y)`.
41    MoveTo {
42        /// X in font units.
43        x: f64,
44        /// Y in font units.
45        y: f64,
46    },
47    /// A straight segment to `(x, y)`.
48    LineTo {
49        /// X in font units.
50        x: f64,
51        /// Y in font units.
52        y: f64,
53    },
54    /// Quadratic: one control point.
55    QuadTo {
56        /// Control point X.
57        x1: f64,
58        /// Control point Y.
59        y1: f64,
60        /// Endpoint X.
61        x: f64,
62        /// Endpoint Y.
63        y: f64,
64    },
65    /// Cubic: two control points. TrueType never produces these; CFF does.
66    CurveTo {
67        /// First control point X.
68        x1: f64,
69        /// First control point Y.
70        y1: f64,
71        /// Second control point X.
72        x2: f64,
73        /// Second control point Y.
74        y2: f64,
75        /// Endpoint X.
76        x: f64,
77        /// Endpoint Y.
78        y: f64,
79    },
80    /// Closes the current subpath.
81    Close,
82}
83
84impl PathCommand {
85    /// The opentype.js `cmd.type` letter, for golden comparison.
86    pub fn type_letter(&self) -> &'static str {
87        match self {
88            PathCommand::MoveTo { .. } => "M",
89            PathCommand::LineTo { .. } => "L",
90            PathCommand::QuadTo { .. } => "Q",
91            PathCommand::CurveTo { .. } => "C",
92            PathCommand::Close => "Z",
93        }
94    }
95}
96
97/// An axis-aligned box, matching opentype's `BoundingBox` field names.
98#[derive(Clone, Copy, Debug, PartialEq)]
99pub struct BBox {
100    /// Left edge.
101    pub x1: f64,
102    /// Bottom edge (Y-up) or top edge (Y-down), matching the path it was measured on.
103    pub y1: f64,
104    /// Right edge.
105    pub x2: f64,
106    /// Top edge (Y-up) or bottom edge (Y-down), matching the path it was measured on.
107    pub y2: f64,
108}
109
110/// One raw `glyf` point.
111#[derive(Clone, Copy, Debug)]
112struct GlyfPoint {
113    x: f64,
114    y: f64,
115    on_curve: bool,
116    last_of_contour: bool,
117}
118
119/// A parsed font with the metrics and kerning `sdf-text` needs — a port of
120/// lib3's `VectorFont`. See the module doc for what diverges from a plain
121/// `ttf-parser` reading.
122pub struct VectorFont {
123    face: OwnedFace,
124    /// Source URL/label, for cache keying. Mirrors `VectorFont.src`.
125    pub src: String,
126    /// Font units per em.
127    pub units_per_em: f64,
128    /// Typographic ascender, font units.
129    pub ascender: f64,
130    /// Typographic descender, font units (negative).
131    pub descender: f64,
132    /// Typographic line gap, font units.
133    pub line_gap: f64,
134    /// Cap height, font units, or 0 if the font has none.
135    pub cap_height: f64,
136    /// X-height, font units, or 0 if the font has none.
137    pub x_height: f64,
138    /// GPOS type-2 lookup subtable offsets reachable from the default script's
139    /// `kern` feature, in lookup-then-subtable order. Absolute offsets into the
140    /// GPOS table bytes. `None` when there is no GPOS table at all — the only
141    /// case in which opentype.js consults `kern`.
142    kern_subtables: Option<Vec<usize>>,
143}
144
145impl VectorFont {
146    /// Port of `new VectorFont(opentype.parse(buffer), src)`.
147    ///
148    /// `VectorFont.load` in the JS also accepts a URL and `fetch`es it; there
149    /// is no fetch here, so callers read the bytes themselves (see the skip
150    /// register in the crate README).
151    pub fn parse(data: Vec<u8>, src: impl Into<String>) -> Result<Self, Error> {
152        let src = src.into();
153        let face = OwnedFace::from_vec(data, 0).map_err(|source| Error::Parse {
154            src: src.clone(),
155            source,
156        })?;
157
158        let (upem, asc, desc, gap, cap, xh) = {
159            let f = face.as_face_ref();
160            let tables = f.tables();
161            // JS: (os2 && os2.sTypoAscender) || (hhea && hhea.ascender) || font.ascender
162            // `||` so a zero falls through. opentype's own `font.ascender` is
163            // the hhea value, so the third arm repeats the second.
164            let os2 = tables.os2;
165            let hhea_asc = tables.hhea.ascender as f64;
166            let hhea_desc = tables.hhea.descender as f64;
167            let hhea_gap = tables.hhea.line_gap as f64;
168            let or0 = |a: f64, b: f64, c: f64| {
169                if a != 0.0 {
170                    a
171                } else if b != 0.0 {
172                    b
173                } else {
174                    c
175                }
176            };
177            let asc = or0(
178                os2.map(|t| t.typographic_ascender() as f64).unwrap_or(0.0),
179                hhea_asc,
180                hhea_asc,
181            );
182            let desc = or0(
183                os2.map(|t| t.typographic_descender() as f64).unwrap_or(0.0),
184                hhea_desc,
185                hhea_desc,
186            );
187            let gap = or0(
188                os2.map(|t| t.typographic_line_gap() as f64).unwrap_or(0.0),
189                hhea_gap,
190                0.0,
191            );
192            // capHeight / xHeight: `(os2 && os2.sCapHeight) || 0`.
193            let cap = os2
194                .and_then(|t| t.capital_height())
195                .map(|v| v as f64)
196                .unwrap_or(0.0);
197            let xh = os2
198                .and_then(|t| t.x_height())
199                .map(|v| v as f64)
200                .unwrap_or(0.0);
201            (f.units_per_em() as f64, asc, desc, gap, cap, xh)
202        };
203
204        let kern_subtables = {
205            let f = face.as_face_ref();
206            f.raw_face()
207                .table(Tag::from_bytes(b"GPOS"))
208                .map(collect_kern_subtables)
209        };
210
211        Ok(VectorFont {
212            face,
213            src,
214            units_per_em: upem,
215            ascender: asc,
216            descender: desc,
217            line_gap: gap,
218            cap_height: cap,
219            x_height: xh,
220            kern_subtables,
221        })
222    }
223
224    fn face(&self) -> &Face<'_> {
225        self.face.as_face_ref()
226    }
227
228    /// Whether the font has a `GPOS` table at all — the condition under which
229    /// opentype.js never falls back to `kern`.
230    pub fn has_gpos(&self) -> bool {
231        self.kern_subtables.is_some()
232    }
233
234    /// Whether the font has a legacy `kern` table.
235    pub fn has_kern(&self) -> bool {
236        self.face()
237            .raw_face()
238            .table(Tag::from_bytes(b"kern"))
239            .is_some()
240    }
241
242    /// Port of `glyphForChar`. opentype.js's `charToGlyph` falls back to glyph 0
243    /// (`.notdef`) for an unmapped character rather than returning null, so this
244    /// never fails for a parsed font.
245    pub fn glyph_for_char(&self, ch: char) -> GlyphId {
246        self.face().glyph_index(ch).unwrap_or(GlyphId(0))
247    }
248
249    /// Horizontal advance in font units.
250    pub fn advance_width(&self, ch: char) -> f64 {
251        let gid = self.glyph_for_char(ch);
252        self.face().glyph_hor_advance(gid).unwrap_or(0) as f64
253    }
254
255    /// Ink bounding box in font units, **Y-up**; `None` for blank glyphs.
256    ///
257    /// JS: `if (!(b.x2 > b.x1 && b.y2 > b.y1)) return null;` — so the all-zero
258    /// box opentype hands back for an empty outline becomes `None`.
259    pub fn bounding_box(&self, ch: char) -> Option<BBox> {
260        let gid = self.glyph_for_char(ch);
261        let b = path_bounding_box(&self.glyph_path(gid));
262        if b.x2 > b.x1 && b.y2 > b.y1 {
263            Some(b)
264        } else {
265            None
266        }
267    }
268
269    /// `glyph.path` — the Y-up command list, `Z`-terminated per contour.
270    pub fn glyph_path(&self, gid: GlyphId) -> Vec<PathCommand> {
271        let mut points = Vec::new();
272        self.collect_points(gid, &mut points, &mut Vec::new());
273        contour_path(&points)
274    }
275
276    /// `glyph.getPath(0, 0, unitsPerEm)` — the same outline with Y negated and
277    /// the `Z` commands dropped (opentype only emits `Z` for stroked paths).
278    /// `fontSize == unitsPerEm` makes the scale exactly 1, so coordinates stay
279    /// at their font-unit values (halves appear from implied midpoints).
280    pub fn glyph_path_y_down(&self, gid: GlyphId) -> Vec<PathCommand> {
281        self.glyph_path(gid)
282            .into_iter()
283            .filter_map(|c| match c {
284                PathCommand::MoveTo { x, y } => Some(PathCommand::MoveTo { x, y: -y }),
285                PathCommand::LineTo { x, y } => Some(PathCommand::LineTo { x, y: -y }),
286                PathCommand::QuadTo { x1, y1, x, y } => Some(PathCommand::QuadTo {
287                    x1,
288                    y1: -y1,
289                    x,
290                    y: -y,
291                }),
292                PathCommand::CurveTo {
293                    x1,
294                    y1,
295                    x2,
296                    y2,
297                    x,
298                    y,
299                } => Some(PathCommand::CurveTo {
300                    x1,
301                    y1: -y1,
302                    x2,
303                    y2: -y2,
304                    x,
305                    y: -y,
306                }),
307                PathCommand::Close => None,
308            })
309            .collect()
310    }
311
312    /// The width of one run of text at `font_size`, in the units
313    /// [`Text`](crate::Text) lays out in — the sum of the glyph advances with
314    /// the kerning between each adjacent pair applied, scaled by
315    /// `font_size / units_per_em`.
316    ///
317    /// This is the measurement layout code needs *before* there is anything to
318    /// lay out: a d3 `separation` callback, a fit, a column width. It is the
319    /// same arithmetic `layout_text_vector` uses for its own line widths (it is
320    /// the same function), so the number agrees with the `TextRenderInfo` a
321    /// `Text` of that string and size reports — see the check in
322    /// `tests/vector_font.rs`.
323    ///
324    /// Three things it deliberately does not do, all of them layout rather than
325    /// measurement:
326    ///
327    /// - **`letterSpacing` is zero.** With a non-zero letter spacing the width
328    ///   is `measure( s, size ) + letter_spacing * ( s.chars().count() - 1 )`,
329    ///   spacing being applied between glyphs only.
330    /// - **No line breaking**, so `max_width` plays no part; this is the width
331    ///   the text *wants*.
332    /// - **Newlines are not special**: `'\n'` is measured as the glyph the font
333    ///   maps it to (zero-advance `.notdef` in Roboto). Measure each line
334    ///   separately and take the widest.
335    ///
336    /// The width is the advance sum, not the ink extent: it includes the first
337    /// and last glyphs' side bearings, which is what a layout wants and what
338    /// `TextRenderInfo::block_bounds` (an ink box) is not.
339    ///
340    /// There is no `measure_info` companion: the full-`TextRenderInfo`
341    /// measurement with no scene object already exists as
342    /// [`layout_text_vector( params, Some( font ) )`](crate::layout_text_vector),
343    /// which is what `Text::sync` itself calls.
344    pub fn measure(&self, text: &str, font_size: f64) -> f64 {
345        crate::text_builder::vec_measure_run(self, text, 0.0, font_size / self.units_per_em)
346    }
347
348    /// Kerning adjustment in font units. See the module doc for the semantics.
349    pub fn kerning(&self, left: char, right: char) -> f64 {
350        let l = self.glyph_for_char(left);
351        let r = self.glyph_for_char(right);
352        self.kerning_by_gid(l, r)
353    }
354
355    pub(crate) fn kerning_by_gid(&self, left: GlyphId, right: GlyphId) -> f64 {
356        let Some(subtables) = self.kern_subtables.as_ref() else {
357            // GPOS absent: opentype.js reads `kerningPairs` (the legacy `kern`
358            // table). Not implemented — see the crate README's skip register.
359            // Every font in this port has GPOS.
360            return 0.0;
361        };
362        let face = self.face();
363        let Some(gpos) = face.raw_face().table(Tag::from_bytes(b"GPOS")) else {
364            return 0.0;
365        };
366        for &off in subtables {
367            let Some(sub) = gpos.get(off..) else { continue };
368            match pair_pos_lookup(sub, left, right) {
369                PairPosResult::NotCovered => continue,
370                PairPosResult::NoPair => continue,
371                PairPosResult::Value(v) => return v as f64,
372            }
373        }
374        0.0
375    }
376
377    // ── glyf point collection (opentype.js `parseGlyph` + `buildPath`) ──────
378
379    fn collect_points(&self, gid: GlyphId, out: &mut Vec<GlyfPoint>, resolving: &mut Vec<u16>) {
380        let face = self.face();
381        let Some(glyf) = face.raw_face().table(Tag::from_bytes(b"glyf")) else {
382            return;
383        };
384        // `FaceTables` does not expose `loca`, so read it raw. `indexToLocFormat`
385        // lives at head+50.
386        let Some(loca) = face.raw_face().table(Tag::from_bytes(b"loca")) else {
387            return;
388        };
389        let Some(head) = face.raw_face().table(Tag::from_bytes(b"head")) else {
390            return;
391        };
392        if head.len() < 52 {
393            return;
394        }
395        let long = read_i16(head, 50) != 0;
396        // An empty loca range means an empty glyph; opentype never calls
397        // parseGlyph for it, so it has no points at all.
398        let Some(range) = loca_range(loca, gid.0, long) else {
399            return;
400        };
401        let Some(data) = glyf.get(range) else { return };
402        if data.len() < 10 {
403            return;
404        }
405        let ncont = read_i16(data, 0);
406        if ncont > 0 {
407            parse_simple_glyph(data, ncont as usize, out);
408        } else if ncont < 0 {
409            resolving.push(gid.0);
410            for comp in parse_composite(data) {
411                if resolving.contains(&comp.glyph_index) {
412                    continue;
413                }
414                let mut sub = Vec::new();
415                self.collect_points(GlyphId(comp.glyph_index), &mut sub, resolving);
416                // `matchedPoints` (ARGS_ARE_XY_VALUES clear) is not supported;
417                // see the crate README's skip register.
418                for p in sub.iter_mut() {
419                    let (x, y) = (p.x, p.y);
420                    p.x = comp.x_scale * x + comp.scale10 * y + comp.dx;
421                    p.y = comp.scale01 * x + comp.y_scale * y + comp.dy;
422                }
423                out.extend_from_slice(&sub);
424            }
425            resolving.pop();
426        }
427    }
428}
429
430/// `loca` lookup: the half-open byte range of a glyph inside `glyf`, or `None`
431/// when the entry is empty (a blank glyph) or out of range.
432fn loca_range(loca: &[u8], gid: u16, long: bool) -> Option<std::ops::Range<usize>> {
433    let (start, end) = if long {
434        let at = gid as usize * 4;
435        if at + 8 > loca.len() {
436            return None;
437        }
438        (
439            u32::from_be_bytes([loca[at], loca[at + 1], loca[at + 2], loca[at + 3]]) as usize,
440            u32::from_be_bytes([loca[at + 4], loca[at + 5], loca[at + 6], loca[at + 7]]) as usize,
441        )
442    } else {
443        let at = gid as usize * 2;
444        if at + 4 > loca.len() {
445            return None;
446        }
447        (
448            read_u16(loca, at) as usize * 2,
449            read_u16(loca, at + 2) as usize * 2,
450        )
451    };
452    if start >= end {
453        None
454    } else {
455        Some(start..end)
456    }
457}
458
459// ── opentype.js's contour walk (`getPath(points)`) ──────────────────────────
460
461fn contour_path(points: &[GlyfPoint]) -> Vec<PathCommand> {
462    let mut out = Vec::new();
463    let mut contour: Vec<GlyfPoint> = Vec::new();
464    for p in points {
465        contour.push(*p);
466        if !p.last_of_contour {
467            continue;
468        }
469        emit_contour(&contour, &mut out);
470        contour.clear();
471    }
472    out
473}
474
475fn emit_contour(contour: &[GlyfPoint], out: &mut Vec<PathCommand>) {
476    if contour.is_empty() {
477        return;
478    }
479    let mut curr = contour[contour.len() - 1];
480    let mut next = contour[0];
481    if curr.on_curve {
482        out.push(PathCommand::MoveTo {
483            x: curr.x,
484            y: curr.y,
485        });
486    } else if next.on_curve {
487        out.push(PathCommand::MoveTo {
488            x: next.x,
489            y: next.y,
490        });
491    } else {
492        out.push(PathCommand::MoveTo {
493            x: (curr.x + next.x) * 0.5,
494            y: (curr.y + next.y) * 0.5,
495        });
496    }
497    for i in 0..contour.len() {
498        curr = next;
499        next = contour[(i + 1) % contour.len()];
500        if curr.on_curve {
501            out.push(PathCommand::LineTo {
502                x: curr.x,
503                y: curr.y,
504            });
505        } else {
506            let (nx, ny) = if next.on_curve {
507                (next.x, next.y)
508            } else {
509                ((curr.x + next.x) * 0.5, (curr.y + next.y) * 0.5)
510            };
511            out.push(PathCommand::QuadTo {
512                x1: curr.x,
513                y1: curr.y,
514                x: nx,
515                y: ny,
516            });
517        }
518    }
519    out.push(PathCommand::Close);
520}
521
522// ── opentype's exact-extrema bounding box (`Path.getBoundingBox`) ───────────
523
524/// Exact-extrema bbox over a Y-up or Y-down command list, in `f64`.
525/// Empty path → `(0, 0, 0, 0)`, matching `if (box.isEmpty()) box.addPoint(0,0)`.
526pub fn path_bounding_box(commands: &[PathCommand]) -> BBox {
527    let mut b = Builder::new();
528    let (mut start_x, mut start_y) = (0.0, 0.0);
529    let (mut prev_x, mut prev_y) = (0.0, 0.0);
530    for cmd in commands {
531        match *cmd {
532            PathCommand::MoveTo { x, y } => {
533                b.add_point(Some(x), Some(y));
534                start_x = x;
535                start_y = y;
536                prev_x = x;
537                prev_y = y;
538            }
539            PathCommand::LineTo { x, y } => {
540                b.add_point(Some(x), Some(y));
541                prev_x = x;
542                prev_y = y;
543            }
544            PathCommand::QuadTo { x1, y1, x, y } => {
545                b.add_quad(prev_x, prev_y, x1, y1, x, y);
546                prev_x = x;
547                prev_y = y;
548            }
549            PathCommand::CurveTo {
550                x1,
551                y1,
552                x2,
553                y2,
554                x,
555                y,
556            } => {
557                b.add_bezier(prev_x, prev_y, x1, y1, x2, y2, x, y);
558                prev_x = x;
559                prev_y = y;
560            }
561            PathCommand::Close => {
562                prev_x = start_x;
563                prev_y = start_y;
564            }
565        }
566    }
567    if b.empty {
568        b.add_point(Some(0.0), Some(0.0));
569    }
570    BBox {
571        x1: b.x1,
572        y1: b.y1,
573        x2: b.x2,
574        y2: b.y2,
575    }
576}
577
578struct Builder {
579    empty: bool,
580    x1: f64,
581    y1: f64,
582    x2: f64,
583    y2: f64,
584}
585
586impl Builder {
587    fn new() -> Self {
588        Builder {
589            empty: true,
590            x1: 0.0,
591            y1: 0.0,
592            x2: 0.0,
593            y2: 0.0,
594        }
595    }
596
597    /// `BoundingBox.addPoint`, where a `null` argument skips that axis. The JS
598    /// initialises both axes from NaN and seeds them on the first numeric value
599    /// *of that axis*, but every path starts with an `M` that seeds both, so a
600    /// single `empty` flag is equivalent.
601    fn add_point(&mut self, x: Option<f64>, y: Option<f64>) {
602        if self.empty {
603            if let Some(x) = x {
604                self.x1 = x;
605                self.x2 = x;
606            }
607            if let Some(y) = y {
608                self.y1 = y;
609                self.y2 = y;
610            }
611            if x.is_some() && y.is_some() {
612                self.empty = false;
613            }
614            return;
615        }
616        if let Some(x) = x {
617            if x < self.x1 {
618                self.x1 = x;
619            }
620            if x > self.x2 {
621                self.x2 = x;
622            }
623        }
624        if let Some(y) = y {
625            if y < self.y1 {
626                self.y1 = y;
627            }
628            if y > self.y2 {
629                self.y2 = y;
630            }
631        }
632    }
633
634    /// `BoundingBox.addQuad` — elevate to a cubic with the 2/3–1/3 rule.
635    fn add_quad(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, x: f64, y: f64) {
636        let cp1x = x0 + 2.0 / 3.0 * (x1 - x0);
637        let cp1y = y0 + 2.0 / 3.0 * (y1 - y0);
638        let cp2x = cp1x + 1.0 / 3.0 * (x - x0);
639        let cp2y = cp1y + 1.0 / 3.0 * (y - y0);
640        self.add_bezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y);
641    }
642
643    /// `BoundingBox.addBezier` — solve the derivative quadratic per axis and add
644    /// the curve point at every root strictly inside (0, 1).
645    #[allow(clippy::too_many_arguments)]
646    fn add_bezier(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, x2: f64, y2: f64, x: f64, y: f64) {
647        let p0 = [x0, y0];
648        let p1 = [x1, y1];
649        let p2 = [x2, y2];
650        let p3 = [x, y];
651        self.add_point(Some(x0), Some(y0));
652        self.add_point(Some(x), Some(y));
653        for i in 0..2 {
654            let b = 6.0 * p0[i] - 12.0 * p1[i] + 6.0 * p2[i];
655            let a = -3.0 * p0[i] + 9.0 * p1[i] - 9.0 * p2[i] + 3.0 * p3[i];
656            let c = 3.0 * p1[i] - 3.0 * p0[i];
657            let mut add = |v: f64, axis: usize| {
658                if axis == 0 {
659                    self.add_point(Some(v), None)
660                } else {
661                    self.add_point(None, Some(v))
662                }
663            };
664            if a == 0.0 {
665                if b == 0.0 {
666                    continue;
667                }
668                let t = -c / b;
669                if 0.0 < t && t < 1.0 {
670                    add(derive(p0[i], p1[i], p2[i], p3[i], t), i);
671                }
672                continue;
673            }
674            let b2ac = b * b - 4.0 * c * a;
675            if b2ac < 0.0 {
676                continue;
677            }
678            let t1 = (-b + b2ac.sqrt()) / (2.0 * a);
679            if 0.0 < t1 && t1 < 1.0 {
680                add(derive(p0[i], p1[i], p2[i], p3[i], t1), i);
681            }
682            let t2 = (-b - b2ac.sqrt()) / (2.0 * a);
683            if 0.0 < t2 && t2 < 1.0 {
684                add(derive(p0[i], p1[i], p2[i], p3[i], t2), i);
685            }
686        }
687    }
688}
689
690fn derive(v0: f64, v1: f64, v2: f64, v3: f64, t: f64) -> f64 {
691    (1.0 - t).powi(3) * v0
692        + 3.0 * (1.0 - t).powi(2) * t * v1
693        + 3.0 * (1.0 - t) * t.powi(2) * v2
694        + t.powi(3) * v3
695}
696
697// ── `glyf` parsing ─────────────────────────────────────────────────────────
698
699fn read_i16(d: &[u8], at: usize) -> i16 {
700    i16::from_be_bytes([d[at], d[at + 1]])
701}
702
703fn read_u16(d: &[u8], at: usize) -> u16 {
704    u16::from_be_bytes([d[at], d[at + 1]])
705}
706
707fn parse_simple_glyph(data: &[u8], ncont: usize, out: &mut Vec<GlyfPoint>) {
708    let mut p = 10;
709    let mut end_pts = Vec::with_capacity(ncont);
710    for _ in 0..ncont {
711        if p + 2 > data.len() {
712            return;
713        }
714        end_pts.push(read_u16(data, p) as usize);
715        p += 2;
716    }
717    if p + 2 > data.len() {
718        return;
719    }
720    let instr_len = read_u16(data, p) as usize;
721    p += 2 + instr_len;
722    let n = match end_pts.last() {
723        Some(&last) => last + 1,
724        None => return,
725    };
726
727    let mut flags: Vec<u8> = Vec::with_capacity(n);
728    while flags.len() < n {
729        if p >= data.len() {
730            return;
731        }
732        let flag = data[p];
733        p += 1;
734        flags.push(flag);
735        if flag & 8 != 0 {
736            if p >= data.len() {
737                return;
738            }
739            let repeat = data[p];
740            p += 1;
741            for _ in 0..repeat {
742                flags.push(flag);
743            }
744        }
745    }
746    flags.truncate(n);
747
748    let base = out.len();
749    for (i, flag) in flags.iter().enumerate().take(n) {
750        out.push(GlyfPoint {
751            x: 0.0,
752            y: 0.0,
753            on_curve: flag & 1 != 0,
754            last_of_contour: end_pts.contains(&i),
755        });
756    }
757
758    // X then Y, each a delta chain. `parseGlyphCoordinate` with
759    // (short, same) = (0x02, 0x10) then (0x04, 0x20).
760    let coord = |p: &mut usize, flag: u8, prev: f64, short: u8, same: u8| -> f64 {
761        if flag & short != 0 {
762            if *p >= data.len() {
763                return prev;
764            }
765            let v = data[*p] as f64;
766            *p += 1;
767            prev + if flag & same == 0 { -v } else { v }
768        } else if flag & same != 0 {
769            prev
770        } else {
771            if *p + 2 > data.len() {
772                return prev;
773            }
774            let v = read_i16(data, *p) as f64;
775            *p += 2;
776            prev + v
777        }
778    };
779
780    let mut px = 0.0;
781    for i in 0..n {
782        px = coord(&mut p, flags[i], px, 0x02, 0x10);
783        out[base + i].x = px;
784    }
785    let mut py = 0.0;
786    for i in 0..n {
787        py = coord(&mut p, flags[i], py, 0x04, 0x20);
788        out[base + i].y = py;
789    }
790}
791
792struct Component {
793    glyph_index: u16,
794    x_scale: f64,
795    scale01: f64,
796    scale10: f64,
797    y_scale: f64,
798    dx: f64,
799    dy: f64,
800}
801
802fn parse_composite(data: &[u8]) -> Vec<Component> {
803    let mut out = Vec::new();
804    let mut p = 10;
805    loop {
806        if p + 4 > data.len() {
807            break;
808        }
809        let flags = read_u16(data, p);
810        let glyph_index = read_u16(data, p + 2);
811        p += 4;
812        let mut c = Component {
813            glyph_index,
814            x_scale: 1.0,
815            scale01: 0.0,
816            scale10: 0.0,
817            y_scale: 1.0,
818            dx: 0.0,
819            dy: 0.0,
820        };
821        if flags & 1 != 0 {
822            if flags & 2 != 0 {
823                c.dx = read_i16(data, p) as f64;
824                c.dy = read_i16(data, p + 2) as f64;
825            }
826            p += 4;
827        } else {
828            if flags & 2 != 0 {
829                c.dx = data[p] as i8 as f64;
830                c.dy = data[p + 1] as i8 as f64;
831            }
832            p += 2;
833        }
834        let f2dot14 = |at: usize| read_i16(data, at) as f64 / 16384.0;
835        if flags & 8 != 0 {
836            c.x_scale = f2dot14(p);
837            c.y_scale = c.x_scale;
838            p += 2;
839        } else if flags & 64 != 0 {
840            c.x_scale = f2dot14(p);
841            c.y_scale = f2dot14(p + 2);
842            p += 4;
843        } else if flags & 128 != 0 {
844            c.x_scale = f2dot14(p);
845            c.scale01 = f2dot14(p + 2);
846            c.scale10 = f2dot14(p + 4);
847            c.y_scale = f2dot14(p + 6);
848            p += 8;
849        }
850        out.push(c);
851        if flags & 32 == 0 {
852            break;
853        }
854    }
855    out
856}
857
858// ── GPOS `kern` walk (opentype.js `Position.getKerningValue`) ───────────────
859
860/// Collects the subtable offsets of every **type-2** lookup listed by the
861/// `kern` feature of the default script's default langsys, in the order
862/// opentype.js walks them.
863///
864/// Default script name (`getDefaultScriptName`): `DFLT` if present, else `latn`,
865/// else none — in which case there is no feature table and the list is empty.
866fn collect_kern_subtables(gpos: &[u8]) -> Vec<usize> {
867    let mut out = Vec::new();
868    if gpos.len() < 10 {
869        return out;
870    }
871    let script_list_off = read_u16(gpos, 4) as usize;
872    let feature_list_off = read_u16(gpos, 6) as usize;
873    let lookup_list_off = read_u16(gpos, 8) as usize;
874
875    // Script list → the default script's Script table.
876    let Some(sl) = gpos.get(script_list_off..) else {
877        return out;
878    };
879    if sl.len() < 2 {
880        return out;
881    }
882    let script_count = read_u16(sl, 0) as usize;
883    let mut tags = Vec::with_capacity(script_count);
884    for i in 0..script_count {
885        let at = 2 + i * 6;
886        if at + 6 > sl.len() {
887            return out;
888        }
889        tags.push((
890            [sl[at], sl[at + 1], sl[at + 2], sl[at + 3]],
891            read_u16(sl, at + 4) as usize,
892        ));
893    }
894    let pick = tags
895        .iter()
896        .find(|(t, _)| t == b"DFLT")
897        .or_else(|| tags.iter().find(|(t, _)| t == b"latn"));
898    let Some(&(_, script_off)) = pick else {
899        return out;
900    };
901
902    // Script table → defaultLangSys (opentype uses it whenever `language` is
903    // unset, which `getKerningTables` leaves so).
904    let Some(st) = sl.get(script_off..) else {
905        return out;
906    };
907    if st.len() < 2 {
908        return out;
909    }
910    let default_lang_sys_off = read_u16(st, 0) as usize;
911    if default_lang_sys_off == 0 {
912        return out;
913    }
914    let Some(ls) = st.get(default_lang_sys_off..) else {
915        return out;
916    };
917    if ls.len() < 6 {
918        return out;
919    }
920    let feature_index_count = read_u16(ls, 4) as usize;
921    let mut feature_indices = Vec::with_capacity(feature_index_count);
922    for i in 0..feature_index_count {
923        let at = 6 + i * 2;
924        if at + 2 > ls.len() {
925            return out;
926        }
927        feature_indices.push(read_u16(ls, at) as usize);
928    }
929
930    // Feature list → the *first* listed feature tagged `kern` (opentype's
931    // `getFeatureTable` returns on the first match).
932    let Some(fl) = gpos.get(feature_list_off..) else {
933        return out;
934    };
935    if fl.len() < 2 {
936        return out;
937    }
938    let feature_count = read_u16(fl, 0) as usize;
939    let mut feature_off = None;
940    for idx in feature_indices {
941        if idx >= feature_count {
942            continue;
943        }
944        let at = 2 + idx * 6;
945        if at + 6 > fl.len() {
946            continue;
947        }
948        if &fl[at..at + 4] == b"kern" {
949            feature_off = Some(read_u16(fl, at + 4) as usize);
950            break;
951        }
952    }
953    let Some(feature_off) = feature_off else {
954        return out;
955    };
956    let Some(ft) = fl.get(feature_off..) else {
957        return out;
958    };
959    if ft.len() < 4 {
960        return out;
961    }
962    let lookup_count = read_u16(ft, 2) as usize;
963    let mut lookup_indices = Vec::with_capacity(lookup_count);
964    for i in 0..lookup_count {
965        let at = 4 + i * 2;
966        if at + 2 > ft.len() {
967            return out;
968        }
969        lookup_indices.push(read_u16(ft, at) as usize);
970    }
971
972    // Lookup list → keep lookupType == 2 (PairPos) only, as
973    // `getLookupTables(script, language, 'kern', 2)` does. A type-9 extension
974    // lookup wrapping a PairPos is therefore *skipped*, exactly as in the JS.
975    let Some(ll) = gpos.get(lookup_list_off..) else {
976        return out;
977    };
978    if ll.len() < 2 {
979        return out;
980    }
981    let total = read_u16(ll, 0) as usize;
982    for idx in lookup_indices {
983        if idx >= total {
984            continue;
985        }
986        let at = 2 + idx * 2;
987        if at + 2 > ll.len() {
988            continue;
989        }
990        let lookup_off = read_u16(ll, at) as usize;
991        let abs = lookup_list_off + lookup_off;
992        let Some(lt) = gpos.get(abs..) else { continue };
993        if lt.len() < 6 {
994            continue;
995        }
996        if read_u16(lt, 0) != 2 {
997            continue;
998        }
999        let sub_count = read_u16(lt, 4) as usize;
1000        for j in 0..sub_count {
1001            let sat = 6 + j * 2;
1002            if sat + 2 > lt.len() {
1003                break;
1004            }
1005            out.push(abs + read_u16(lt, sat) as usize);
1006        }
1007    }
1008    out
1009}
1010
1011enum PairPosResult {
1012    /// The left glyph is not in the subtable's coverage — try the next subtable.
1013    NotCovered,
1014    /// Covered but format 1 found no matching second glyph — `break` in the JS,
1015    /// which also means "try the next subtable".
1016    NoPair,
1017    Value(i16),
1018}
1019
1020fn pair_pos_lookup(sub: &[u8], left: GlyphId, right: GlyphId) -> PairPosResult {
1021    if sub.len() < 4 {
1022        return PairPosResult::NotCovered;
1023    }
1024    let format = read_u16(sub, 0);
1025    let coverage_off = read_u16(sub, 2) as usize;
1026    let Some(cov) = sub.get(coverage_off..) else {
1027        return PairPosResult::NotCovered;
1028    };
1029    let Some(cov_index) = coverage_index(cov, left) else {
1030        return PairPosResult::NotCovered;
1031    };
1032
1033    match format {
1034        1 => {
1035            if sub.len() < 10 {
1036                return PairPosResult::NotCovered;
1037            }
1038            let v1_format = read_u16(sub, 4);
1039            let v2_format = read_u16(sub, 6);
1040            let set_count = read_u16(sub, 8) as usize;
1041            if cov_index as usize >= set_count {
1042                return PairPosResult::NoPair;
1043            }
1044            let at = 10 + cov_index as usize * 2;
1045            if at + 2 > sub.len() {
1046                return PairPosResult::NoPair;
1047            }
1048            let set_off = read_u16(sub, at) as usize;
1049            let Some(set) = sub.get(set_off..) else {
1050                return PairPosResult::NoPair;
1051            };
1052            if set.len() < 2 {
1053                return PairPosResult::NoPair;
1054            }
1055            let pair_count = read_u16(set, 0) as usize;
1056            let rec_size = 2 + value_size(v1_format) + value_size(v2_format);
1057            for k in 0..pair_count {
1058                let at = 2 + k * rec_size;
1059                if at + rec_size > set.len() {
1060                    break;
1061                }
1062                if read_u16(set, at) == right.0 {
1063                    return PairPosResult::Value(x_advance(set, at + 2, v1_format));
1064                }
1065            }
1066            PairPosResult::NoPair
1067        }
1068        2 => {
1069            if sub.len() < 16 {
1070                return PairPosResult::NotCovered;
1071            }
1072            let v1_format = read_u16(sub, 4);
1073            let v2_format = read_u16(sub, 6);
1074            let cd1_off = read_u16(sub, 8) as usize;
1075            let cd2_off = read_u16(sub, 10) as usize;
1076            let class1_count = read_u16(sub, 12) as usize;
1077            let class2_count = read_u16(sub, 14) as usize;
1078            let c1 = sub
1079                .get(cd1_off..)
1080                .map(|d| glyph_class(d, left))
1081                .unwrap_or(0) as usize;
1082            let c2 = sub
1083                .get(cd2_off..)
1084                .map(|d| glyph_class(d, right))
1085                .unwrap_or(0) as usize;
1086            // The JS indexes `classRecords[class1][class2]` directly and
1087            // returns whatever it finds (zero included), so this always ends
1088            // the walk once the left glyph is covered.
1089            if c1 >= class1_count || c2 >= class2_count {
1090                return PairPosResult::Value(0);
1091            }
1092            let rec_size = value_size(v1_format) + value_size(v2_format);
1093            let at = 16 + (c1 * class2_count + c2) * rec_size;
1094            if at + rec_size > sub.len() {
1095                return PairPosResult::Value(0);
1096            }
1097            PairPosResult::Value(x_advance(sub, at, v1_format))
1098        }
1099        // Unknown posFormat: the JS switch has no default, so it falls out of
1100        // the switch and continues with the next subtable.
1101        _ => PairPosResult::NoPair,
1102    }
1103}
1104
1105fn value_size(format: u16) -> usize {
1106    2 * (format & 0xFF).count_ones() as usize
1107}
1108
1109/// The `xAdvance` field of a ValueRecord, or 0 when the format omits it —
1110/// `pair.value1 && pair.value1.xAdvance || 0`.
1111fn x_advance(d: &[u8], at: usize, format: u16) -> i16 {
1112    if format & 0x0004 == 0 {
1113        return 0;
1114    }
1115    // Fields are emitted in bit order; xAdvance is bit 2.
1116    let before = (format & 0x0003).count_ones() as usize;
1117    let off = at + before * 2;
1118    if off + 2 > d.len() {
1119        return 0;
1120    }
1121    read_i16(d, off)
1122}
1123
1124/// `Layout.getCoverageIndex`, returning `None` for -1.
1125fn coverage_index(cov: &[u8], glyph: GlyphId) -> Option<u16> {
1126    if cov.len() < 4 {
1127        return None;
1128    }
1129    match read_u16(cov, 0) {
1130        1 => {
1131            let count = read_u16(cov, 2) as usize;
1132            // Binary search over a sorted glyph array, as `binSearch` does.
1133            let (mut lo, mut hi) = (0usize, count);
1134            while lo < hi {
1135                let mid = (lo + hi) / 2;
1136                let at = 4 + mid * 2;
1137                if at + 2 > cov.len() {
1138                    return None;
1139                }
1140                let g = read_u16(cov, at);
1141                if g == glyph.0 {
1142                    return Some(mid as u16);
1143                } else if g < glyph.0 {
1144                    lo = mid + 1;
1145                } else {
1146                    hi = mid;
1147                }
1148            }
1149            None
1150        }
1151        2 => {
1152            let count = read_u16(cov, 2) as usize;
1153            for i in 0..count {
1154                let at = 4 + i * 6;
1155                if at + 6 > cov.len() {
1156                    return None;
1157                }
1158                let start = read_u16(cov, at);
1159                let end = read_u16(cov, at + 2);
1160                if glyph.0 >= start && glyph.0 <= end {
1161                    return Some(read_u16(cov, at + 4) + glyph.0 - start);
1162                }
1163            }
1164            None
1165        }
1166        _ => None,
1167    }
1168}
1169
1170/// `Layout.getGlyphClass` — 0 when the glyph is unlisted.
1171fn glyph_class(d: &[u8], glyph: GlyphId) -> u16 {
1172    if d.len() < 4 {
1173        return 0;
1174    }
1175    match read_u16(d, 0) {
1176        1 => {
1177            let start = read_u16(d, 2);
1178            let count = read_u16(d, 4) as usize;
1179            if glyph.0 >= start && (glyph.0 as usize) < start as usize + count {
1180                let at = 6 + (glyph.0 - start) as usize * 2;
1181                if at + 2 <= d.len() {
1182                    return read_u16(d, at);
1183                }
1184            }
1185            0
1186        }
1187        2 => {
1188            let count = read_u16(d, 2) as usize;
1189            for i in 0..count {
1190                let at = 4 + i * 6;
1191                if at + 6 > d.len() {
1192                    return 0;
1193                }
1194                if glyph.0 >= read_u16(d, at) && glyph.0 <= read_u16(d, at + 2) {
1195                    return read_u16(d, at + 4);
1196                }
1197            }
1198            0
1199        }
1200        _ => 0,
1201    }
1202}