1
//! Font parsing, metrics extraction, and subsetting.
2
//!
3
//! This module provides the core font infrastructure for text layout and PDF generation:
4
//! - `loading`: System font cache construction and font reload errors
5
//! - `mock`: Mock font implementation for testing without real font files
6
//! - `parsed`: Full font parsing via allsorts (outlines, metrics, shaping tables, subsetting)
7

            
8
#![cfg(feature = "font_loading")]
9

            
10
use azul_css::{AzString, U8Vec};
11
use rust_fontconfig::{FcFontCache, OwnedFontSource};
12

            
13
pub mod loading {
14
    #![cfg(feature = "std")]
15
    #![cfg(feature = "font_loading")]
16
    #![cfg_attr(not(feature = "std"), no_std)]
17

            
18
    use std::io::Error as IoError;
19

            
20
    use azul_css::{AzString, StringVec, U8Vec};
21
    use rust_fontconfig::FcFontCache;
22

            
23
    #[cfg(not(miri))]
24
1425
    #[must_use] pub fn build_font_cache() -> FcFontCache {
25
1425
        FcFontCache::build()
26
1425
    }
27

            
28
    #[cfg(miri)]
29
    pub fn build_font_cache() -> FcFontCache {
30
        FcFontCache::default()
31
    }
32

            
33
    #[derive(Debug)]
34
    pub enum FontReloadError {
35
        Io(IoError, AzString),
36
        FontNotFound(AzString),
37
        FontLoadingNotActive(AzString),
38
    }
39

            
40
    impl Clone for FontReloadError {
41
        fn clone(&self) -> Self {
42
            use self::FontReloadError::{Io, FontNotFound, FontLoadingNotActive};
43
            match self {
44
                Io(err, path) => Io(IoError::new(err.kind(), "Io Error"), path.clone()),
45
                FontNotFound(id) => FontNotFound(id.clone()),
46
                FontLoadingNotActive(id) => FontLoadingNotActive(id.clone()),
47
            }
48
        }
49
    }
50

            
51
    azul_core::impl_display!(FontReloadError, {
52
        Io(err, path_buf) => format!("Could not load \"{}\" - IO error: {}", path_buf.as_str(), err),
53
        FontNotFound(id) => format!("Could not locate system font: \"{:?}\" found", id),
54
        FontLoadingNotActive(id) => format!("Could not load system font: \"{:?}\": crate was not compiled with --features=\"font_loading\"", id)
55
    });
56
}
57
pub mod mock {
58
    //! Mock font implementation for testing text layout.
59
    //!
60
    //! Provides a `MockFont` that simulates font behavior without requiring
61
    //! actual font files, useful for unit testing text layout functionality.
62

            
63
    use std::collections::BTreeMap;
64

            
65
    use crate::text3::cache::LayoutFontMetrics;
66

            
67
    /// A mock font implementation for testing text layout without real fonts.
68
    ///
69
    /// This allows testing text shaping, layout, and rendering code paths
70
    /// without needing to load actual TrueType/OpenType font files.
71
    #[derive(Debug, Clone)]
72
    pub struct MockFont {
73
        /// Font metrics (ascent, descent, etc.).
74
        pub font_metrics: LayoutFontMetrics,
75
        /// Width of the space character in font units.
76
        pub space_width: Option<usize>,
77
        /// Horizontal advance widths keyed by glyph ID.
78
        pub glyph_advances: BTreeMap<u16, u16>,
79
        /// Glyph bounding box sizes (width, height) keyed by glyph ID.
80
        pub glyph_sizes: BTreeMap<u16, (i32, i32)>,
81
        /// Unicode codepoint to glyph ID mapping.
82
        pub glyph_indices: BTreeMap<u32, u16>,
83
    }
84

            
85
    impl MockFont {
86
        /// Creates a new `MockFont` with the given font metrics.
87
4
        #[must_use] pub const fn new(font_metrics: LayoutFontMetrics) -> Self {
88
4
            Self {
89
4
                font_metrics,
90
4
                space_width: Some(10),
91
4
                glyph_advances: BTreeMap::new(),
92
4
                glyph_sizes: BTreeMap::new(),
93
4
                glyph_indices: BTreeMap::new(),
94
4
            }
95
4
        }
96

            
97
        /// Sets the space character width.
98
3
        #[must_use] pub const fn with_space_width(mut self, width: usize) -> Self {
99
3
            self.space_width = Some(width);
100
3
            self
101
3
        }
102

            
103
        /// Adds a horizontal advance value for a glyph.
104
4
        #[must_use] pub fn with_glyph_advance(mut self, glyph_index: u16, advance: u16) -> Self {
105
4
            self.glyph_advances.insert(glyph_index, advance);
106
4
            self
107
4
        }
108

            
109
        /// Adds a bounding box size for a glyph.
110
1
        #[must_use] pub fn with_glyph_size(mut self, glyph_index: u16, size: (i32, i32)) -> Self {
111
1
            self.glyph_sizes.insert(glyph_index, size);
112
1
            self
113
1
        }
114

            
115
        /// Adds a Unicode codepoint to glyph ID mapping.
116
2
        #[must_use] pub fn with_glyph_index(mut self, unicode: u32, index: u16) -> Self {
117
2
            self.glyph_indices.insert(unicode, index);
118
2
            self
119
2
        }
120
    }
121
}
122

            
123
pub mod parsed {
124
    use core::fmt;
125
    use std::{collections::BTreeMap, sync::Arc};
126

            
127
    use allsorts::{
128
        binary::read::ReadScope,
129
        font_data::FontData,
130
        layout::{GDEFTable, LayoutCache, LayoutCacheData, GPOS, GSUB},
131
        outline::{OutlineBuilder, OutlineSink},
132
        pathfinder_geometry::{line_segment::LineSegment2F, vector::Vector2F},
133
        subset::{subset as allsorts_subset, whole_font, CmapTarget, SubsetProfile},
134
        tables::{
135
            cmap::owned::CmapSubtable as OwnedCmapSubtable,
136
            glyf::{
137
                Glyph, GlyfVisitorContext, LocaGlyf, Point,
138
                VariableGlyfContext, VariableGlyfContextStore,
139
            },
140
            kern::owned::KernTable,
141
            FontTableProvider, HheaTable, MaxpTable,
142
        },
143
        tag,
144
    };
145
    use azul_core::resources::{
146
        GlyphOutline, GlyphOutlineOperation, OutlineCubicTo, OutlineLineTo, OutlineMoveTo,
147
        OutlineQuadTo, OwnedGlyphBoundingBox,
148
    };
149
    use azul_css::props::basic::FontMetrics as CssFontMetrics;
150

            
151
    // Mock font module for testing
152
    pub use crate::font::mock::MockFont;
153
    use crate::text3::cache::LayoutFontMetrics;
154

            
155
    /// Cached GSUB table for glyph substitution operations.
156
    pub type GsubCache = Arc<LayoutCacheData<GSUB>>;
157
    /// Cached GPOS table for glyph positioning operations.
158
    pub type GposCache = Arc<LayoutCacheData<GPOS>>;
159

            
160
    /// The `wght` variation axis `(min, default, max)` in user units.
161
    ///
162
    /// `None` when the font has no variable `wght` axis. Used to expand a
163
    /// variable font into per-weight STATIC instances so the ordinary (static)
164
    /// weight-selection path can pick the right one — no changes to
165
    /// shaping/decode/PDF needed.
166
    #[must_use]
167
16640
    pub fn read_wght_axis(bytes: &[u8], index: usize) -> Option<(f32, f32, f32)> {
168
16640
        let font_file = ReadScope::new(bytes).read::<FontData<'_>>().ok()?;
169
16640
        let provider = font_file.table_provider(index).ok()?;
170
16640
        let fvar_data = provider.read_table_data(tag::FVAR).ok()?;
171
        let fvar = ReadScope::new(&fvar_data)
172
            .read::<allsorts::tables::variable_fonts::fvar::FvarTable<'_>>()
173
            .ok()?;
174
        // Bind before returning so the (borrowing) axes() iterator is dropped at
175
        // the end of this statement, not after `provider`/`fvar` at block end.
176
        let axis = fvar.axes().find(|a| a.axis_tag == tag::WGHT);
177
        axis.map(|a| {
178
            (
179
                f32::from(a.min_value),
180
                f32::from(a.default_value),
181
                f32::from(a.max_value),
182
            )
183
        })
184
16640
    }
185

            
186
    /// Bake a self-contained STATIC instance of a variable font at `wght`.
187
    ///
188
    /// All other axes are left at their default. Returns fresh TTF bytes that
189
    /// parse and embed exactly like any static font, or `None` if the font is
190
    /// not a bakeable variable font.
191
    #[must_use]
192
    pub fn bake_weight_instance(bytes: &[u8], index: usize, wght: f32) -> Option<Vec<u8>> {
193
        use allsorts::tables::Fixed;
194
        let font_file = ReadScope::new(bytes).read::<FontData<'_>>().ok()?;
195
        let provider = font_file.table_provider(index).ok()?;
196
        let fvar_data = provider.read_table_data(tag::FVAR).ok()?;
197
        let fvar = ReadScope::new(&fvar_data)
198
            .read::<allsorts::tables::variable_fonts::fvar::FvarTable<'_>>()
199
            .ok()?;
200
        let user: Vec<Fixed> = fvar
201
            .axes()
202
            .map(|a| {
203
                if a.axis_tag == tag::WGHT {
204
                    Fixed::from(wght)
205
                } else {
206
                    a.default_value
207
                }
208
            })
209
            .collect();
210
        allsorts::variations::instance(&provider, &user)
211
            .ok()
212
            .map(|(baked, _tuple)| baked)
213
    }
214

            
215
    /// Monotonic-clock nanos since process start. Used to timestamp
216
    /// `ParsedFont.last_used` for LRU eviction. Cheap (single
217
    /// `Instant::now`); resolution is plenty fine for "did this
218
    /// face get touched in the last N seconds" decisions. Exposed
219
    /// `pub(crate)` so `FontManager::evict_unused` reads from the
220
    /// same clock as `last_used` writes.
221
    #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
222
    #[cfg(not(target_family = "wasm"))]
223
8284249
    pub(crate) fn monotonic_now_nanos() -> u64 {
224
        // Safe: `Instant::elapsed` against the same launch instant is
225
        // monotonic and never overflows in any realistic process
226
        // lifetime (>500 years).
227
        use std::sync::OnceLock;
228
        use std::time::Instant;
229
        static LAUNCH: OnceLock<Instant> = OnceLock::new();
230
8284249
        let start = LAUNCH.get_or_init(Instant::now);
231
8284249
        start.elapsed().as_nanos() as u64
232
8284249
    }
233

            
234
    /// On browser wasm `std::time::Instant::now()` panics ("time not
235
    /// implemented on this platform") — it took the whole printpdf wasm demo
236
    /// down with it on the first shaped glyph: every `last_used` store on a
237
    /// font touch aborted the module. LRU eviction only needs *ordering*, not
238
    /// wall time, and a shared atomic counter is exactly as monotonic.
239
    #[cfg(target_family = "wasm")]
240
    pub(crate) fn monotonic_now_nanos() -> u64 {
241
        use std::sync::atomic::{AtomicU64, Ordering};
242
        static TICK: AtomicU64 = AtomicU64::new(1);
243
        TICK.fetch_add(1, Ordering::Relaxed)
244
    }
245

            
246
    /// Glyph-outline decoder state. See the
247
    /// [`ParsedFont::loca_glyf`] field docs for the full description.
248
    #[derive(Clone)]
249
    pub(crate) enum LocaGlyfState {
250
        /// Ready to decode immediately, or known to have no outline
251
        /// data. `None` covers both CFF fonts and fonts where the
252
        /// loca+glyf parse failed.
253
        ///
254
        /// This variant *cannot* be evicted by
255
        /// [`crate::text3::cache::FontManager::evict_unused`]: there
256
        /// are no source bytes retained to re-decode from. The eager
257
        /// `from_bytes` path (tests, `with_source_bytes` PDF callers)
258
        /// produces this variant.
259
        Loaded(Option<Arc<std::sync::Mutex<LocaGlyf>>>),
260
        /// Font bytes retained for lazy `LocaGlyf` construction.
261
        ///
262
        /// `loaded` is `Mutex<Option<…>>` (not `OnceLock`) so an
263
        /// idle eviction can clear it back to `None`; the next
264
        /// `get_or_decode_glyph` will re-parse from `bytes`. Two-step
265
        /// double-check pattern in `resolve_loca_glyf` keeps the
266
        /// expensive `LocaGlyf::load` outside the critical section.
267
        Deferred {
268
            bytes: Arc<rust_fontconfig::FontBytes>,
269
            font_index: usize,
270
            loaded: Arc<std::sync::Mutex<Option<Arc<std::sync::Mutex<LocaGlyf>>>>>,
271
        },
272
    }
273

            
274
    /// Adapter that collects allsorts outline commands into our `GlyphOutline` format.
275
    ///
276
    /// Implements `OutlineSink` so it can be passed to `GlyfVisitorContext::visit()`.
277
    /// This handles composite glyph resolution, transforms, and variable font
278
    /// deltas automatically via allsorts internals.
279
    struct GlyphOutlineCollector {
280
        contours: Vec<GlyphOutline>,
281
        current_contour: Vec<GlyphOutlineOperation>,
282
    }
283

            
284
    impl GlyphOutlineCollector {
285
4830
        const fn new() -> Self {
286
4830
            Self {
287
4830
                contours: Vec::new(),
288
4830
                current_contour: Vec::new(),
289
4830
            }
290
4830
        }
291

            
292
4830
        fn into_outlines(mut self) -> Vec<GlyphOutline> {
293
4830
            if !self.current_contour.is_empty() {
294
3
                self.contours.push(GlyphOutline {
295
3
                    operations: std::mem::take(&mut self.current_contour).into(),
296
3
                });
297
4827
            }
298
4830
            self.contours
299
4830
        }
300
    }
301

            
302
    impl OutlineSink for GlyphOutlineCollector {
303
        #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
304
12253
        fn move_to(&mut self, to: Vector2F) {
305
12253
            if !self.current_contour.is_empty() {
306
                self.contours.push(GlyphOutline {
307
                    operations: std::mem::take(&mut self.current_contour).into(),
308
                });
309
12253
            }
310
12253
            self.current_contour.push(GlyphOutlineOperation::MoveTo(OutlineMoveTo {
311
12253
                x: to.x() as i16,
312
12253
                y: to.y() as i16,
313
12253
            }));
314
12253
        }
315

            
316
        #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
317
44477
        fn line_to(&mut self, to: Vector2F) {
318
44477
            self.current_contour.push(GlyphOutlineOperation::LineTo(OutlineLineTo {
319
44477
                x: to.x() as i16,
320
44477
                y: to.y() as i16,
321
44477
            }));
322
44477
        }
323

            
324
        #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
325
32970
        fn quadratic_curve_to(&mut self, ctrl: Vector2F, to: Vector2F) {
326
32970
            self.current_contour.push(GlyphOutlineOperation::QuadraticCurveTo(
327
32970
                OutlineQuadTo {
328
32970
                    ctrl_1_x: ctrl.x() as i16,
329
32970
                    ctrl_1_y: ctrl.y() as i16,
330
32970
                    end_x: to.x() as i16,
331
32970
                    end_y: to.y() as i16,
332
32970
                },
333
32970
            ));
334
32970
        }
335

            
336
        #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
337
1
        fn cubic_curve_to(&mut self, ctrl: LineSegment2F, to: Vector2F) {
338
1
            self.current_contour.push(GlyphOutlineOperation::CubicCurveTo(
339
1
                OutlineCubicTo {
340
1
                    ctrl_1_x: ctrl.from_x() as i16,
341
1
                    ctrl_1_y: ctrl.from_y() as i16,
342
1
                    ctrl_2_x: ctrl.to_x() as i16,
343
1
                    ctrl_2_y: ctrl.to_y() as i16,
344
1
                    end_x: to.x() as i16,
345
1
                    end_y: to.y() as i16,
346
1
                },
347
1
            ));
348
1
        }
349

            
350
12250
        fn close(&mut self) {
351
12250
            self.current_contour.push(GlyphOutlineOperation::ClosePath);
352
12250
            self.contours.push(GlyphOutline {
353
12250
                operations: std::mem::take(&mut self.current_contour).into(),
354
12250
            });
355
12250
        }
356
    }
357

            
358
    /// Parsed font data with all required tables for text layout and PDF generation.
359
    ///
360
    /// This struct holds the parsed representation of a TrueType/OpenType font,
361
    /// including glyph outlines, metrics, and shaping tables. It's used for:
362
    /// - Text layout (via GSUB/GPOS tables)
363
    /// - Glyph rendering (via glyf/CFF outlines)
364
    /// - PDF font embedding (via font metrics and subsetting)
365
    pub struct ParsedFont {
366
        /// Hash of the font bytes for caching and equality checks.
367
        pub hash: u64,
368
        /// Layout-specific font metrics (ascent, descent, line gap).
369
        pub font_metrics: LayoutFontMetrics,
370
        /// PDF-specific detailed font metrics from HEAD, HHEA, OS/2 tables.
371
        pub pdf_font_metrics: PdfFontMetrics,
372
        /// Total number of glyphs in the font (from maxp table).
373
        pub num_glyphs: u16,
374
        /// Horizontal header table (hhea) containing global horizontal metrics.
375
        pub hhea_table: HheaTable,
376
        /// Offset+length into `original_bytes` for hmtx table (lazy: no copy).
377
        pub hmtx_range: (usize, usize),
378
        /// Offset+length into `original_bytes` for vmtx table (lazy: no copy).
379
        pub vmtx_range: (usize, usize),
380
        /// Vertical header table (vhea), same format as hhea. None if font has no vertical metrics.
381
        pub vhea_table: Option<HheaTable>,
382
        /// Maximum profile table (maxp) containing glyph count and memory hints.
383
        pub maxp_table: MaxpTable,
384
        /// Raw GSUB table bytes, kept as a `Vec<u8>` (tens to low-hundreds
385
        /// of KiB) so the parsed `GsubCache` can be built on first shape
386
        /// call instead of up-front. Access via [`ParsedFont::gsub`] —
387
        /// that getter populates `gsub_cache_lazy` via `OnceLock` and
388
        /// returns a borrow.
389
        pub(crate) gsub_bytes: Option<Vec<u8>>,
390
        /// Lazy GSUB cache: populated on first [`ParsedFont::gsub`] call.
391
        /// `None` means "font has no GSUB table" *after* init attempt;
392
        /// the `OnceLock` wrapper distinguishes "not yet initialised"
393
        /// from "initialised to None".
394
        pub(crate) gsub_cache_lazy: std::sync::OnceLock<Option<GsubCache>>,
395
        /// Raw GPOS table bytes. Same lazy-parse arrangement as
396
        /// `gsub_bytes` — see [`ParsedFont::gpos`].
397
        pub(crate) gpos_bytes: Option<Vec<u8>>,
398
        /// Lazy GPOS cache, populated on first [`ParsedFont::gpos`] call.
399
        pub(crate) gpos_cache_lazy: std::sync::OnceLock<Option<GposCache>>,
400
        /// Glyph definition table (GDEF) for glyph classification.
401
        pub opt_gdef_table: Option<Arc<GDEFTable>>,
402
        /// Legacy kerning table (kern) for fonts without GPOS.
403
        pub opt_kern_table: Option<Arc<KernTable>>,
404
        /// Monotonic-clock nanos at the most recent
405
        /// [`ParsedFont::get_or_decode_glyph`] / `gsub()` / `gpos()`
406
        /// call. `0` means "never touched". Used by
407
        /// [`crate::text3::cache::FontManager::evict_unused`] to
408
        /// decide which `LocaGlyfState::Deferred` faces to release.
409
        pub(crate) last_used: Arc<std::sync::atomic::AtomicU64>,
410
        /// `true` if this font is a variable font (carries a `gvar`
411
        /// table). Cached at parse time so [`decode_glyph_inner`]
412
        /// can short-circuit the variable-context construction for
413
        /// the common non-variable case. Variable-glyph delta
414
        /// application requires the source bytes to be retained,
415
        /// so it only fires on the `LocaGlyfState::Deferred` path.
416
        pub(crate) is_variable_font: bool,
417
        /// Lazy outline cache. Populated on first
418
        /// [`ParsedFont::get_or_decode_glyph`] call per `gid`; entries
419
        /// are wrapped in `Arc` so callers can hold them without
420
        /// keeping the lock. The space glyph (and `.notdef` when
421
        /// present) are pre-inserted by `from_bytes_internal` so the
422
        /// shaper's cmap-miss path has something to render without
423
        /// racing with a decode.
424
        ///
425
        /// Tests that previously walked the public `glyph_records_decoded`
426
        /// `BTreeMap` field now call
427
        /// [`ParsedFont::prime_glyph_cache`] (decodes every glyph into
428
        /// this cache) followed by
429
        /// [`ParsedFont::for_each_decoded_glyph`] /
430
        /// [`ParsedFont::glyph_cache_snapshot`] to walk the result.
431
        // [az-web-lift] queue RwLock spins in lock_contended in single-threaded lifted wasm
432
        // (only the pure-Rust queue RwLock is lifted; Mutex is Leaf-stubbed). Reuse
433
        // rust_fontconfig::StLock (no-atomic single-threaded bypass). One of the 3 RwLocks total.
434
        pub(crate) glyph_cache: Arc<rust_fontconfig::StLock<BTreeMap<u16, Arc<OwnedGlyph>>>>,
435
        /// Glyph outline decoder state.
436
        ///
437
        /// - `Loaded(Some(arc))`: `LocaGlyf` is already loaded (owning
438
        ///   its own `Box<[u8]>` copy of the loca+glyf tables) and
439
        ///   ready to decode glyphs. Produced by the eager `from_bytes`
440
        ///   constructor path (tests).
441
        /// - `Loaded(None)`: the font has no usable loca+glyf (CFF, or
442
        ///   a parse failure). Glyph outlines won't decode; the hmtx
443
        ///   advance fallback fills in the blanks.
444
        /// - `Deferred`: we retain an `Arc<[u8]>` to the full font file
445
        ///   and the `font_index`; the first `get_or_decode_glyph` call
446
        ///   parses a fresh `FontData` / `TableProvider` from those
447
        ///   bytes and loads `LocaGlyf`, storing the result in the
448
        ///   `OnceLock`. Fonts that get resolved into a chain but are
449
        ///   never actually rasterized pay zero decode cost — this is
450
        ///   the big win for pages like `excel.html` where 20+ fallback
451
        ///   faces load but only a handful are touched.
452
        pub(crate) loca_glyf: LocaGlyfState,
453
        /// Cached width of the space character in font units.
454
        pub space_width: Option<usize>,
455
        /// Character-to-glyph mapping (cmap subtable).
456
        pub cmap_subtable: Option<OwnedCmapSubtable>,
457
        /// Mock font data for testing (replaces real font behavior).
458
        pub mock: Option<Box<MockFont>>,
459
        /// Reverse mapping: `glyph_id` -> cluster text (handles ligatures like "fi").
460
        pub reverse_glyph_cache: BTreeMap<u16, String>,
461
        /// Original font bytes — only retained for callers that need to
462
        /// reconstruct or subset the font (PDF export). Layout / shaping /
463
        /// raster never read this, so `ParsedFont::from_bytes` leaves it
464
        /// as `None` by default and callers opt in via
465
        /// [`ParsedFont::with_source_bytes`]. Shared across faces of the
466
        /// same `.ttc` via the `Arc<FontBytes>` that
467
        /// [`rust_fontconfig::FcFontCache::get_font_bytes`] returns —
468
        /// for disk fonts the backing is an mmap so untouched pages
469
        /// don't count toward RSS.
470
        pub original_bytes: Option<Arc<rust_fontconfig::FontBytes>>,
471
        /// Font index within collection (0 for single-font files).
472
        pub original_index: usize,
473
        /// GID to CID mapping for CFF fonts (required for PDF embedding).
474
        pub index_to_cid: BTreeMap<u16, u16>,
475
        /// Font type (TrueType outlines or OpenType CFF).
476
        pub font_type: FontType,
477
        /// PostScript font name from the NAME table.
478
        pub font_name: Option<String>,
479
        /// TrueType bytecode hinting instance (mutable interpreter state).
480
        /// Wrapped in Mutex because hinting mutates internal state.
481
        /// None for CFF fonts or fonts without hinting data.
482
        pub hint_instance: Option<std::sync::Mutex<allsorts::hinting::HintInstance>>,
483
    }
484

            
485
    impl Clone for ParsedFont {
486
10
        fn clone(&self) -> Self {
487
10
            Self {
488
10
                hash: self.hash,
489
10
                font_metrics: self.font_metrics,
490
10
                pdf_font_metrics: self.pdf_font_metrics,
491
10
                num_glyphs: self.num_glyphs,
492
10
                hhea_table: self.hhea_table.clone(),
493
10
                hmtx_range: self.hmtx_range,
494
10
                vmtx_range: self.vmtx_range,
495
10
                vhea_table: self.vhea_table.clone(),
496
10
                maxp_table: self.maxp_table.clone(),
497
10
                // OnceLock<T: Clone>: Clone preserves the init state, so
498
10
                // a clone of a parsed cache skips re-parse on first
499
10
                // access. The raw bytes we keep around for lazy init
500
10
                // are cloned too.
501
10
                gsub_bytes: self.gsub_bytes.clone(),
502
10
                gsub_cache_lazy: self.gsub_cache_lazy.clone(),
503
10
                gpos_bytes: self.gpos_bytes.clone(),
504
10
                gpos_cache_lazy: self.gpos_cache_lazy.clone(),
505
10
                opt_gdef_table: self.opt_gdef_table.clone(),
506
10
                opt_kern_table: self.opt_kern_table.clone(),
507
10
                // Share the lazy cache and loca_glyf across clones: cheap
508
10
                // Arc bump, amortises glyph decode across clones of the
509
10
                // same face.
510
10
                last_used: Arc::clone(&self.last_used),
511
10
                is_variable_font: self.is_variable_font,
512
10
                glyph_cache: Arc::clone(&self.glyph_cache),
513
10
                // `LocaGlyfState` is `Clone` — for `Loaded` this is an
514
10
                // `Arc::clone`; for `Deferred` it's an `Arc::clone` of
515
10
                // the bytes + the `OnceLock`, so a clone of a face
516
10
                // that's already decoded glyphs carries the decode.
517
10
                loca_glyf: self.loca_glyf.clone(),
518
10
                space_width: self.space_width,
519
10
                cmap_subtable: self.cmap_subtable.clone(),
520
10
                mock: self.mock.clone(),
521
10
                reverse_glyph_cache: self.reverse_glyph_cache.clone(),
522
10
                // Arc clone — O(1), just bumps refcount; no byte copy.
523
10
                original_bytes: self.original_bytes.clone(),
524
10
                original_index: self.original_index,
525
10
                index_to_cid: self.index_to_cid.clone(),
526
10
                font_type: self.font_type.clone(),
527
10
                font_name: self.font_name.clone(),
528
10
                // HintInstance has mutable interpreter state and is not Clone.
529
10
                // Clones are used for PDF/serialization where hinting isn't needed.
530
10
                hint_instance: None,
531
10
            }
532
10
        }
533
    }
534

            
535
    /// Distinguishes TrueType fonts from OpenType CFF fonts.
536
    ///
537
    /// This affects how glyph outlines are extracted and how the font
538
    /// is embedded in PDF documents.
539
    #[derive(Debug, Clone, PartialEq, Eq)]
540
    pub enum FontType {
541
        /// TrueType font with quadratic Bézier outlines in glyf table.
542
        TrueType,
543
        /// OpenType font with cubic Bézier outlines in CFF table.
544
        /// Contains the serialized CFF data for PDF embedding.
545
        OpenTypeCFF(Vec<u8>),
546
    }
547

            
548
    /// PDF-specific font metrics from HEAD, HHEA, and OS/2 tables.
549
    ///
550
    /// These metrics are used for PDF font descriptors and accurate
551
    /// text positioning in generated PDF documents.
552
    #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
553
    #[repr(C)]
554
    pub struct PdfFontMetrics {
555
        // -- HEAD table fields --
556
        /// Font units per em-square (typically 1000 or 2048).
557
        pub units_per_em: u16,
558
        /// Font flags (italic, bold, fixed-pitch, etc.).
559
        pub font_flags: u16,
560
        /// Minimum x-coordinate across all glyphs.
561
        pub x_min: i16,
562
        /// Minimum y-coordinate across all glyphs.
563
        pub y_min: i16,
564
        /// Maximum x-coordinate across all glyphs.
565
        pub x_max: i16,
566
        /// Maximum y-coordinate across all glyphs.
567
        pub y_max: i16,
568

            
569
        // -- HHEA table fields --
570
        /// Typographic ascender (distance above baseline).
571
        pub ascender: i16,
572
        /// Typographic descender (distance below baseline, usually negative).
573
        pub descender: i16,
574
        /// Recommended line gap between lines of text.
575
        pub line_gap: i16,
576
        /// Maximum horizontal advance width across all glyphs.
577
        pub advance_width_max: u16,
578
        /// Caret slope rise for italic angle calculation.
579
        pub caret_slope_rise: i16,
580
        /// Caret slope run for italic angle calculation.
581
        pub caret_slope_run: i16,
582

            
583
        // -- OS/2 table fields (0 if table not present) --
584
        /// Average width of lowercase letters.
585
        pub x_avg_char_width: i16,
586
        /// Visual weight class (100-900, 400=normal, 700=bold).
587
        pub us_weight_class: u16,
588
        /// Visual width class (1-9, 5=normal).
589
        pub us_width_class: u16,
590
        /// Thickness of strikeout stroke in font units.
591
        pub y_strikeout_size: i16,
592
        /// Vertical position of strikeout stroke.
593
        pub y_strikeout_position: i16,
594
    }
595

            
596
    impl Default for PdfFontMetrics {
597
1
        fn default() -> Self {
598
1
            Self::zero()
599
1
        }
600
    }
601

            
602
    impl PdfFontMetrics {
603
        /// Returns zeroed metrics with `units_per_em` set to 1000 (standard PostScript default)
604
        /// to avoid division-by-zero in scaling calculations.
605
19849
        #[must_use] pub const fn zero() -> Self {
606
19849
            Self {
607
19849
                units_per_em: 1000,
608
19849
                font_flags: 0,
609
19849
                x_min: 0,
610
19849
                y_min: 0,
611
19849
                x_max: 0,
612
19849
                y_max: 0,
613
19849
                ascender: 0,
614
19849
                descender: 0,
615
19849
                line_gap: 0,
616
19849
                advance_width_max: 0,
617
19849
                caret_slope_rise: 0,
618
19849
                caret_slope_run: 0,
619
19849
                x_avg_char_width: 0,
620
19849
                us_weight_class: 0,
621
19849
                us_width_class: 0,
622
19849
                y_strikeout_size: 0,
623
19849
                y_strikeout_position: 0,
624
19849
            }
625
19849
        }
626
    }
627

            
628
    /// Result of font subsetting operation.
629
    ///
630
    /// Contains the subsetted font bytes and a mapping from original
631
    /// glyph IDs to new glyph IDs in the subset.
632
    #[derive(Debug, Clone)]
633
    pub struct SubsetFont {
634
        /// The subsetted font file bytes (smaller than original).
635
        pub bytes: Vec<u8>,
636
        /// Mapping: original glyph ID -> (new subset glyph ID, source character).
637
        pub glyph_mapping: BTreeMap<u16, (u16, char)>,
638
    }
639

            
640
    impl SubsetFont {
641
        /// Return the changed text so that when rendering with the subset font (instead of the
642
        /// original) the renderer will end up at the same glyph IDs as if we used the original text
643
        /// on the original font
644
11
        #[must_use] pub fn subset_text(&self, text: &str) -> String {
645
11
            text.chars()
646
100021
                .filter_map(|c| {
647
100025
                    self.glyph_mapping.values().find_map(|(ngid, ch)| {
648
100025
                        if *ch == c {
649
100012
                            char::from_u32(u32::from(*ngid))
650
                        } else {
651
13
                            None
652
                        }
653
100025
                    })
654
100021
                })
655
11
                .collect()
656
11
        }
657
    }
658

            
659
    /// Hash-based equality: two fonts are considered equal if their content hash matches.
660
    /// This is a performance optimization — hash collisions are possible but vanishingly
661
    /// unlikely (~1/2^64).
662
    impl PartialEq for ParsedFont {
663
2
        fn eq(&self, other: &Self) -> bool {
664
2
            self.hash == other.hash
665
2
        }
666
    }
667

            
668
    impl Eq for ParsedFont {}
669

            
670
    const FONT_B64_START: &str = "data:font/ttf;base64,";
671

            
672
    impl serde::Serialize for ParsedFont {
673
        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
674
            use base64::Engine;
675
            let s = format!(
676
                "{FONT_B64_START}{}",
677
                base64::prelude::BASE64_STANDARD.encode(self.to_bytes(None).unwrap_or_default())
678
            );
679
            s.serialize(serializer)
680
        }
681
    }
682

            
683
    impl<'de> serde::Deserialize<'de> for ParsedFont {
684
        fn deserialize<D: serde::Deserializer<'de>>(
685
            deserializer: D,
686
        ) -> Result<Self, D::Error> {
687
            use base64::Engine;
688
            let s = String::deserialize(deserializer)?;
689
            let b64 = s.strip_prefix(FONT_B64_START).and_then(|b| base64::prelude::BASE64_STANDARD.decode(b).ok());
690

            
691
            let mut warnings = Vec::new();
692
            Self::from_bytes(&b64.unwrap_or_default(), 0, &mut warnings).ok_or_else(|| {
693
                serde::de::Error::custom(format!("Font deserialization error: {warnings:?}"))
694
            })
695
        }
696
    }
697

            
698
    impl fmt::Debug for ParsedFont {
699
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700
            f.debug_struct("ParsedFont")
701
                .field("hash", &self.hash)
702
                .field("font_metrics", &self.font_metrics)
703
                .field("num_glyphs", &self.num_glyphs)
704
                .field("hhea_table", &self.hhea_table)
705
                .field(
706
                    "hmtx_range",
707
                    &format_args!("<{} bytes>", self.hmtx_range.1),
708
                )
709
                .field("maxp_table", &self.maxp_table)
710
                .field(
711
                    "glyph_cache",
712
                    &format_args!(
713
                        "{} entries (lazy)",
714
                        self.glyph_cache.read().map(|m| m.len()).unwrap_or(0),
715
                    ),
716
                )
717
                .field("space_width", &self.space_width)
718
                .field("cmap_subtable", &self.cmap_subtable)
719
                .finish_non_exhaustive()
720
        }
721
    }
722

            
723
    /// Warning or error message generated during font parsing.
724
    #[derive(Debug, Clone, PartialEq, Eq)]
725
    pub struct FontParseWarning {
726
        /// Severity level of this warning.
727
        pub severity: FontParseWarningSeverity,
728
        /// Human-readable description of the issue.
729
        pub message: String,
730
    }
731

            
732
    /// Severity level for font parsing warnings.
733
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
734
    pub enum FontParseWarningSeverity {
735
        /// Informational message (not an error).
736
        Info,
737
        /// Warning that may affect font rendering.
738
        Warning,
739
        /// Error that prevents proper font usage.
740
        Error,
741
    }
742

            
743
    impl FontParseWarning {
744
        /// Creates an info-level message.
745
1
        #[must_use] pub const fn info(message: String) -> Self {
746
1
            Self {
747
1
                severity: FontParseWarningSeverity::Info,
748
1
                message,
749
1
            }
750
1
        }
751

            
752
        /// Creates a warning-level message.
753
2
        #[must_use] pub const fn warning(message: String) -> Self {
754
2
            Self {
755
2
                severity: FontParseWarningSeverity::Warning,
756
2
                message,
757
2
            }
758
2
        }
759

            
760
        /// Creates an error-level message.
761
455
        #[must_use] pub const fn error(message: String) -> Self {
762
455
            Self {
763
455
                severity: FontParseWarningSeverity::Error,
764
455
                message,
765
455
            }
766
455
        }
767
    }
768

            
769
    // WEB-LIFT FIX (2026-06-02): a `FontTableProvider` that scans the sfnt table directory
770
    // by hand from the raw font bytes. allsorts' `OffsetTableFontProvider` produces garbage
771
    // on the remill/web backend: (1) `ReadArray::read_item`'s nested-tuple `TableRecord` read
772
    // returns `table_tag = 0` for EVERY record (proven: tags[7]=0x0000 while the bytes there
773
    // are 0x68656164 'head'); (2) even a hand-rolled scan added to the *allsorts crate* sees a
774
    // bad `self.scope.data()` (the ReadScope fat-pointer mis-lifts through provider
775
    // construction, or allsorts-crate code lifts differently). This provider lives in
776
    // azul-layout — whose identical byte reads PROVABLY work (the `from_provider` probe read
777
    // num_tables=15 from these same `font_bytes`) — and reads the slice directly. KEEP.
778
    #[inline]
779
19853
    fn manual_be16(d: &[u8], o: usize) -> u32 {
780
19853
        (u32::from(d[o]) << 8) | u32::from(d[o + 1])
781
19853
    }
782
    #[inline]
783
9741002
    fn manual_be32(d: &[u8], o: usize) -> u32 {
784
9741002
        (u32::from(d[o]) << 24)
785
9741002
            | (u32::from(d[o + 1]) << 16)
786
9741002
            | (u32::from(d[o + 2]) << 8)
787
9741002
            | u32::from(d[o + 3])
788
9741002
    }
789

            
790
    struct ManualTableProvider<'a> {
791
        data: &'a [u8],
792
        dir: usize, // byte offset of the first table record (offset-table base + 12)
793
        num: usize, // number of table records
794
    }
795

            
796
    impl<'a> ManualTableProvider<'a> {
797
19857
        fn new(data: &'a [u8], font_index: usize) -> Option<Self> {
798
19857
            if data.len() < 12 {
799
5
                return None;
800
19852
            }
801
19852
            let base = if manual_be32(data, 0) == 0x7474_6366 {
802
                // 'ttcf' (TrueType Collection): the font_index'th offset-table offset.
803
5
                let num_fonts = manual_be32(data, 8) as usize;
804
5
                if font_index >= num_fonts || 12 + font_index * 4 + 4 > data.len() {
805
3
                    return None;
806
2
                }
807
2
                manual_be32(data, 12 + font_index * 4) as usize
808
            } else {
809
19847
                0 // single font: offset table at the start
810
            };
811
19849
            if base + 12 > data.len() {
812
1
                return None;
813
19848
            }
814
19848
            Some(ManualTableProvider {
815
19848
                data,
816
19848
                dir: base + 12,
817
19848
                num: manual_be16(data, base + 4) as usize,
818
19848
            })
819
19857
        }
820
    }
821

            
822
    impl FontTableProvider for ManualTableProvider<'_> {
823
662810
        fn table_data(
824
662810
            &self,
825
662810
            tag: u32,
826
662810
        ) -> Result<Option<std::borrow::Cow<'_, [u8]>>, allsorts::error::ParseError> {
827
662810
            let mut i = 0;
828
9104446
            while i < self.num {
829
8868133
                let r = self.dir + i * 16;
830
8868133
                if r + 16 > self.data.len() {
831
2
                    break;
832
8868131
                }
833
8868131
                if manual_be32(self.data, r) == tag {
834
426495
                    let off = manual_be32(self.data, r + 8) as usize;
835
426495
                    let len = manual_be32(self.data, r + 12) as usize;
836
426495
                    return Ok(off
837
426495
                        .checked_add(len)
838
426495
                        .filter(|&e| e <= self.data.len())
839
426495
                        .map(|e| std::borrow::Cow::Borrowed(&self.data[off..e])));
840
8441636
                }
841
8441636
                i += 1;
842
            }
843
236315
            Ok(None)
844
662810
        }
845

            
846
218246
        fn has_table(&self, tag: u32) -> bool {
847
218246
            self.table_data(tag).ok().flatten().is_some()
848
218246
        }
849

            
850
2
        fn table_tags(&self) -> Option<Vec<u32>> {
851
            // DIAG (REVERT): sentinel 0xFADE as tags[0] proves THIS provider ran; then
852
            // self.num pushes let me see if the usize field survived; then the real reads
853
            // show if self.data (slice field) survived the struct move through generics.
854
2
            let mut tags = Vec::with_capacity(self.num + 1);
855
2
            tags.push(0x0000_FADE);
856
2
            let mut i = 0;
857
15
            while i < self.num {
858
14
                let r = self.dir + i * 16;
859
14
                if r + 4 > self.data.len() {
860
1
                    break;
861
13
                }
862
13
                tags.push(manual_be32(self.data, r));
863
13
                i += 1;
864
            }
865
2
            Some(tags)
866
2
        }
867
    }
868

            
869
    impl allsorts::tables::SfntVersion for ManualTableProvider<'_> {
870
2
        fn sfnt_version(&self) -> u32 {
871
2
            let base = self.dir.saturating_sub(12);
872
2
            if base + 4 <= self.data.len() {
873
2
                manual_be32(self.data, base)
874
            } else {
875
                0
876
            }
877
2
        }
878
    }
879

            
880
    impl ParsedFont {
881
        /// Parse a font from bytes using allsorts
882
        ///
883
        /// # Arguments
884
        /// * `font_bytes` - The font file data
885
        /// * `font_index` - Index of the font in a font collection (0 for single fonts)
886
        /// * `warnings` - Optional vector to collect parsing warnings
887
        ///
888
        /// # Returns
889
        /// `Some(ParsedFont)` if parsing succeeds, `None` otherwise
890
        ///
891
        /// Note: Outlines are decoded lazily by `get_or_decode_glyph`;
892
        /// `LocaGlyf::load` runs eagerly here. Use `from_bytes_shared`
893
        /// for the lazy-LocaGlyf production path.
894
2465
        pub fn from_bytes(
895
2465
            font_bytes: &[u8],
896
2465
            font_index: usize,
897
2465
            warnings: &mut Vec<FontParseWarning>,
898
2465
        ) -> Option<Self> {
899
            // `from_bytes` keeps the eager-LocaGlyf behaviour for the
900
            // small number of callers (mainly tests) that don't have
901
            // an `Arc<[u8]>` to keep alive for the lazy path.
902
2465
            let mut font = Self::from_bytes_internal(font_bytes, font_index, warnings, false)?;
903
            // Retain an owned copy of the source bytes so the face can later be
904
            // subset/embedded (PDF export, save->parse roundtrips). Callers pass a
905
            // borrowed slice that may not outlive us, so we own it here. Mirrors
906
            // `from_bytes_shared`, which retains the caller's `Arc<FontBytes>`.
907
2018
            if font.original_bytes.is_none() {
908
2018
                font.original_bytes = Some(Arc::new(
909
2018
                    rust_fontconfig::FontBytes::Owned(Arc::from(font_bytes.to_vec())),
910
2018
                ));
911
2018
            }
912
2018
            Some(font)
913
2465
        }
914

            
915
        /// Shared implementation of `from_bytes` / `from_bytes_shared`.
916
        ///
917
        /// `defer_loca_glyf = true` skips the `LocaGlyf::load` call
918
        /// here so the caller (`from_bytes_shared`) can install a
919
        /// `LocaGlyfState::Deferred` slot that re-parses on first
920
        /// glyph decode. Saves the load-then-drop cycle the previous
921
        /// arrangement paid (`from_bytes_shared` used to call
922
        /// `from_bytes` and immediately replace the loaded `LocaGlyf`
923
        /// with a Deferred slot, throwing away ~hundreds of KiB of
924
        /// loca+glyf bytes per face for fonts in the chain that get
925
        /// loaded but never rasterized).
926
20293
        fn from_bytes_internal(
927
20293
            font_bytes: &[u8],
928
20293
            font_index: usize,
929
20293
            warnings: &mut Vec<FontParseWarning>,
930
20293
            defer_loca_glyf: bool,
931
20293
        ) -> Option<Self> {
932
            use allsorts::{binary::read::ReadScope, font_data::FontData};
933
            fn provider_err(font_index: usize, e: impl fmt::Display) -> FontParseWarning {
934
                FontParseWarning::error(format!(
935
                    "Failed to get table provider for font index {font_index}: {e}"
936
                ))
937
            }
938

            
939
20293
            let scope = ReadScope::new(font_bytes);
940
20293
            let font_file = match scope.read::<FontData<'_>>() {
941
19842
                Ok(ff) => ff,
942
451
                Err(e) => {
943
451
                    warnings.push(FontParseWarning::error(format!(
944
451
                        "Failed to read font data: {e}"
945
                    )));
946
451
                    return None;
947
                }
948
            };
949
            // FIX (2026-06-02): route OpenType fonts through the CONCRETE provider
950
            // (`OffsetTableFontProvider`) instead of `FontData::table_provider`'s
951
            // `Box<dyn FontTableProvider>`. On the lifted/web backend the trait-object
952
            // VTABLE dispatch (allsorts font_data.rs:45 `self.provider.table_data(tag)`)
953
            // mis-lifts: the vtable's fn-pointers are untranslated native addresses, so the
954
            // indirect-call dispatcher routes the dyn call to the WRONG `table_data` impl,
955
            // which returns a `Cow::Owned` garbage buffer → `HeadTable::read` errors → font
956
            // parse returns None → text measures height 0. A concrete provider makes every
957
            // `table_data` a DIRECT (monomorphized) call, which lifts correctly. Woff/Woff2
958
            // keep the dyn path (they're not used on the web backend's embedded TTF).
959
19842
            match font_file {
960
19842
                FontData::OpenType(otf) => {
961
                    // Prefer the hand-rolled provider (reads font_bytes directly) over
962
                    // allsorts' OffsetTableFontProvider, whose lifted table reads are garbage
963
                    // on the web backend. Fall back to allsorts only if the manual layout
964
                    // parse can't recognise the sfnt (e.g. an unusual TTC).
965
19842
                    if let Some(mp) = ManualTableProvider::new(font_bytes, font_index) {
966
19842
                        Self::from_provider(mp, font_bytes, font_index, warnings, defer_loca_glyf)
967
                    } else {
968
                        match otf.table_provider(font_index) {
969
                            Ok(p) => Self::from_provider(
970
                                p,
971
                                font_bytes,
972
                                font_index,
973
                                warnings,
974
                                defer_loca_glyf,
975
                            ),
976
                            Err(e) => {
977
                                warnings.push(provider_err(font_index, e));
978
                                None
979
                            }
980
                        }
981
                    }
982
                }
983
                other => match other.table_provider(font_index) {
984
                    Ok(p) => {
985
                        Self::from_provider(p, font_bytes, font_index, warnings, defer_loca_glyf)
986
                    }
987
                    Err(e) => {
988
                        warnings.push(provider_err(font_index, e));
989
                        None
990
                    }
991
                },
992
            }
993
20293
        }
994

            
995
        /// Build a `ParsedFont` from a concrete [`FontTableProvider`]. Split out of
996
        /// `from_bytes_internal` (2026-06-02) so OpenType fonts use the concrete
997
        /// `OffsetTableFontProvider` (direct `table_data` calls that lift correctly on
998
        /// the web backend) rather than `FontData::table_provider`'s `Box<dyn>`, whose
999
        /// trait-object vtable dispatch mis-lifts (wrong impl → Owned garbage → parse fail).
        #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
        #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
19842
        fn from_provider<P: FontTableProvider>(
19842
            provider: P,
19842
            font_bytes: &[u8],
19842
            font_index: usize,
19842
            warnings: &mut Vec<FontParseWarning>,
19842
            defer_loca_glyf: bool,
19842
        ) -> Option<Self> {
            use std::{
                collections::hash_map::DefaultHasher,
                hash::{Hash, Hasher},
            };
            use allsorts::{
                binary::read::ReadScope,
                tables::{
                    cmap::{owned::CmapSubtable as OwnedCmapSubtable, CmapSubtable},
                    FontTableProvider, HeadTable, HheaTable, MaxpTable,
                },
                tag,
            };
            // Extract font name from NAME table early (before provider is moved).
            // WEB-LIFT FIX (2026-06-02): NameTable::string_for_id decodes the NAME strings via
            // `encoding_rs` (Mac Roman / UTF-16 charset state machines), whose jump-tables
            // are NOT devirt'd by the remill lift → MISSING_BLOCK trap (proven: trap in
            // encoding_rs::Decoder::decode_to_utf8). font_name is OPTIONAL metadata (NOT used
            // for layout/metrics/shaping — those are binary head/hhea/maxp/cmap/glyf), so skip
            // the NAME-string decode on the web backend to avoid encoding_rs entirely.
            #[cfg(feature = "web_lift")]
            let font_name: Option<String> = None;
            #[cfg(not(feature = "web_lift"))]
19842
            let font_name = provider.table_data(tag::NAME).ok().and_then(|name_data| {
19842
                ReadScope::new(&name_data?)
19840
                    .read::<allsorts::tables::NameTable<'_>>()
19840
                    .ok()
19840
                    .and_then(|name_table| {
19840
                        name_table.string_for_id(allsorts::tables::NameTable::POSTSCRIPT_NAME)
19840
                    })
19842
            });
            // DIAG (2026-06-02, REVERT): pinpoint the web font-parse-fails root — does HEAD
            // fail because table_data can't find/return the table (directory mis-lift) or
            // because HeadTable::read errors (table-read mis-lift)? Surfaced via warnings.
19842
            let head_table = match provider.table_data(tag::HEAD) {
19840
                Ok(Some(head_cow)) => {
                    // DIAG: is the HEAD table data CORRECT (magicNumber 0x5F0F3CF5 @ off 12 →
                    // HeadTable::read mis-lifts) or WRONG bytes (directory offset mis-lift)?
19840
                    let bb = head_cow.as_ref();
19840
                    let magic = if bb.len() >= 16 {
19840
                        (u32::from(bb[12]) << 24) | (u32::from(bb[13]) << 16)
19840
                            | (u32::from(bb[14]) << 8) | u32::from(bb[15])
                    } else { 0 };
19840
                    if let Ok(h) = ReadScope::new(&head_cow).read::<HeadTable>() { h } else {
                        // DIAG: surface the sliced offset (how wrong) as hex — "HO" + 8 hex
                        // of (head_cow.ptr - font_bytes.ptr). garbage→offset-read mis-lift;
                        // 00000000→base; plausible-but-wrong→record mapping. "RF"=bytes-OK.
                        let m = if magic == 0x5F0F_3CF5 {
                            "RF000000".to_string()
                        } else {
                            let off = (head_cow.as_ref().as_ptr() as usize)
                                .wrapping_sub(font_bytes.as_ptr() as usize);
                            let mut msg = String::new();
                            // B=Borrowed(slice of font_bytes, ptr-arith/base mis-lift) vs
                            // O=Owned(decompressed/copied Vec — wrong path for plain TTF).
                            msg.push(if matches!(head_cow, std::borrow::Cow::Borrowed(_)) { 'B' } else { 'O' });
                            msg.push_str("HO");
                            let mut sh: i32 = 28;
                            while sh >= 0 {
                                let d = ((off >> sh) & 0xf) as u8;
                                msg.push((if d < 10 { b'0' + d } else { b'a' + d - 10 }) as char);
                                sh -= 4;
                            }
                            msg
                        };
                        warnings.push(FontParseWarning::error(m));
                        return None;
                    }
                }
                Ok(None) => {
                    // DIAG (REVERT): bytes+len+read_item-count+dir all proved OK (N0fr0fc0fg1)
                    // yet find_table_record(HEAD)=None though 'head' is rec[7] on disk. So
                    // either read_item's table_tag FIELD is garbage, or tag::HEAD mis-lifts, or
                    // the u32 == mis-lifts. t7 = tags[7] (should be 0x68656164 'head' low16
                    // =6164); H = tag::HEAD low16 (should be 6164); f = ANY tag==HEAD via an
                    // indexed compare loop (NOT .iter().any). "T<4h t7>H<4h HEAD>f<0|1>".
                    //   T6164 H6164 f1 → values+compare OK (won't reach here — HEAD found)
                    //   T6164 H6164 f0 → the u32 == comparison mis-lifts
                    //   T!=6164        → read_item table_tag FIELD garbage (tuple read mis-lift)
                    //   H!=6164        → tag::HEAD const mis-lifts
                    #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
4
                    fn hx(m: &mut String, val: u32, nibbles: i32) {
4
                        let mut sh = (nibbles - 1) * 4;
20
                        while sh >= 0 {
16
                            let d = ((val >> sh) & 0xf) as u8;
16
                            m.push((if d < 10 { b'0' + d } else { b'a' + d - 10 }) as char);
16
                            sh -= 4;
                        }
4
                    }
                    // DECISIVE: tags[8] (head, file off 124) reads 0 but tags[2] (off 28) is OK.
                    // Read the SAME offsets from from_provider's LOCAL font_bytes param (proven
                    // correct at off 4/12). If local@124 = 0x6865 'he' but provider tags[8]=0 ⇒
                    // STORED-SLICE issue (provider self.data fat-ptr mis-lifts) → read locally.
                    // If local@124 = 0 ⇒ the font CONST is only PARTIALLY MIRRORED into the wasm
                    // (deep data-mirror gap) → table data is simply absent. local@93596 (=0x16f9c,
                    // head TABLE data start) further maps the mirror: 'he'/nonzero vs 0.
2
                    let loc124 = if font_bytes.len() >= 126 {
2
                        (u32::from(font_bytes[124]) << 8) | u32::from(font_bytes[125])
                    } else {
                        0xEEEE
                    };
2
                    let loc_head = if font_bytes.len() >= 93598 {
                        (u32::from(font_bytes[93596]) << 8) | u32::from(font_bytes[93597])
                    } else {
2
                        0xEEEE
                    };
2
                    let mut m = String::from("L"); // local font_bytes[124..126] (head dir record):
2
                    hx(&mut m, loc124 & 0xffff, 4); // 6865 'he' = mirrored; 0000 = not
2
                    m.push('H'); // local font_bytes[93596..] (head TABLE data, deep):
2
                    hx(&mut m, loc_head & 0xffff, 4);
2
                    warnings.push(FontParseWarning::error(m));
2
                    return None;
                }
                Err(_) => {
                    warnings.push(FontParseWarning::error("HEAD_DATAERR".to_string()));
                    return None;
                }
            };
19840
            let maxp_table = provider
19840
                .table_data(tag::MAXP)
19840
                .ok()
19840
                .and_then(|maxp_data| ReadScope::new(&maxp_data?).read::<MaxpTable>().ok())
19840
                .unwrap_or(MaxpTable {
19840
                    num_glyphs: 0,
19840
                    version1_sub_table: None,
19840
                });
19840
            let num_glyphs = maxp_table.num_glyphs as usize;
            // Compute byte offset+length into font_bytes for hmtx/vmtx
            // instead of copying the table data. The provider returns a
            // borrowed slice for OpenType fonts, so we can derive the
            // offset via pointer arithmetic.
19840
            let hmtx_range = provider
19840
                .table_data(tag::HMTX)
19840
                .ok()
19840
                .and_then(|cow_opt| {
19840
                    let cow = cow_opt?;
19840
                    match cow {
19840
                        std::borrow::Cow::Borrowed(slice) => {
19840
                            let base = font_bytes.as_ptr() as usize;
19840
                            let ptr = slice.as_ptr() as usize;
19840
                            let offset = ptr.checked_sub(base)?;
19840
                            if offset + slice.len() <= font_bytes.len() {
19840
                                Some((offset, slice.len()))
                            } else {
                                None
                            }
                        }
                        std::borrow::Cow::Owned(_) => None,
                    }
19840
                })
19840
                .unwrap_or((0, 0));
19840
            let vmtx_range = provider
19840
                .table_data(tag::VMTX)
19840
                .ok()
19840
                .and_then(|s| {
19840
                    let slice = s?;
9
                    let base = font_bytes.as_ptr() as usize;
9
                    let ptr = slice.as_ptr() as usize;
9
                    let offset = ptr.checked_sub(base)?;
9
                    if offset + slice.len() <= font_bytes.len() {
9
                        Some((offset, slice.len()))
                    } else {
                        None
                    }
19840
                })
19840
                .unwrap_or((0, 0));
            // Parse vhea table (same format as hhea, used for vertical metrics)
19840
            let vhea_table = provider
19840
                .table_data(tag::VHEA)
19840
                .ok()
19840
                .and_then(|vhea_data| ReadScope::new(&vhea_data?).read::<HheaTable>().ok());
            // hhea is required per the OpenType spec; return None if missing
19840
            let hhea_table = provider
19840
                .table_data(tag::HHEA)
19840
                .ok()
19840
                .and_then(|hhea_data| ReadScope::new(&hhea_data?).read::<HheaTable>().ok())?;
            // Build layout-specific font metrics
19840
            let font_metrics = LayoutFontMetrics {
19840
                units_per_em: if head_table.units_per_em == 0 {
                    1000
                } else {
19840
                    head_table.units_per_em
                },
19840
                ascent: f32::from(hhea_table.ascender),
19840
                descent: f32::from(hhea_table.descender),
19840
                line_gap: f32::from(hhea_table.line_gap),
19840
                x_height: None, // will be populated from OS/2 table via from_font_metrics if available
19840
                cap_height: None,
            };
            // Build PDF-specific font metrics
19840
            let pdf_font_metrics =
19840
                Self::parse_pdf_font_metrics(font_bytes, font_index, &head_table, &hhea_table);
            // Use allsorts LocaGlyf for on-demand outline extraction. We
            // *load* LocaGlyf eagerly (it owns ~tens of KiB of loca +
            // ~hundreds of KiB of glyf bytes) but we *don't* decode any
            // glyph outlines up front — that's the big RSS win. Glyphs
            // are decoded by `ParsedFont::get_or_decode_glyph` on first
            // access from the CPU/GPU rasterizer.
            //
            // When `defer_loca_glyf` is set (production lazy path via
            // `from_bytes_shared`), we skip `LocaGlyf::load` here too —
            // the caller will overwrite the slot with
            // `LocaGlyfState::Deferred` carrying the source bytes
            // `Arc<[u8]>`, and the load happens on the first
            // `get_or_decode_glyph` call. This avoids parsing
            // ~hundreds of KiB per face for fonts that get resolved
            // into a chain but never actually rasterized (typical
            // for fallback fonts in CSS chains).
19840
            let has_glyf = provider.has_table(tag::GLYF) && provider.has_table(tag::LOCA);
            // Cache `has_gvar` before `provider` gets moved into
            // `allsorts::font::Font::new(provider)` further down —
            // it's the cheapest way to detect a variable font and
            // avoids the borrow-after-move that a later
            // `provider.has_table(tag::GVAR)` would incur.
19840
            let has_gvar = provider.has_table(tag::GVAR);
19840
            let loca_glyf_opt: Option<Arc<std::sync::Mutex<LocaGlyf>>> = if has_glyf
19840
                && !defer_loca_glyf
            {
2019
                match LocaGlyf::load(&provider) {
2019
                    Ok(lg) => Some(Arc::new(std::sync::Mutex::new(lg))),
                    Err(e) => {
                        warnings.push(FontParseWarning::warning(format!(
                            "Failed to load LocaGlyf: {e} — falling back to hmtx-only"
                        )));
                        None
                    }
                }
            } else {
17821
                None
            };
            // Lazy `glyph_cache` starts empty; the space-glyph stub
            // below pre-inserts gid 0 / space so the shaper's
            // cmap-miss fallback has something to render without
            // racing with a decode.
19840
            let mut font_data_impl = allsorts::font::Font::new(provider).ok()?;
            // Create TrueType hinting instance from font tables.
            // [az-web-lift] Skip on the web build. The lifted layout never grid-fits glyphs to a
            // pixel raster (it measures + ships a display list to JS), so hinting is never used.
            // Building it (HintInstance::new) runs the allsorts bytecode Interpreter
            // (Interpreter::new + ::dispatch — a large un-devirt'd opcode jump table the remill
            // lift can't resolve, plus ~700 op_* fns of closure bloat). This is INDEPENDENT of the
            // lift's jump-table devirt: even with a perfect lift, web has no use for hinting, and
            // hinted advances are lower-quality output than the plain scaled advance. Native keeps
            // real hinting unchanged.
            #[cfg(feature = "web_lift")]
            let hint_instance: Option<std::sync::Mutex<allsorts::hinting::HintInstance>> = None;
            #[cfg(not(feature = "web_lift"))]
19840
            let hint_instance = allsorts::hinting::HintInstance::new(
19840
                &font_data_impl.font_table_provider
19840
            ).ok().flatten().map(std::sync::Mutex::new);
            // Stash raw GSUB/GPOS bytes for lazy parse. Typical fonts
            // have ~tens of KiB of GSUB + a few-to-tens of KiB of GPOS —
            // dwarfed by glyph outlines — so we keep the bytes around
            // and only spend `LayoutTable::read` + `new_layout_cache`
            // cycles when the shaper actually needs them (via
            // `ParsedFont::gsub` / `::gpos`). For an ASCII run where no
            // substitution / kerning is required, we skip both entirely.
19840
            let gsub_bytes = font_data_impl
19840
                .font_table_provider
19840
                .table_data(tag::GSUB)
19840
                .ok()
19840
                .flatten()
19840
                .map(std::borrow::Cow::into_owned);
19840
            let gpos_bytes = font_data_impl
19840
                .font_table_provider
19840
                .table_data(tag::GPOS)
19840
                .ok()
19840
                .flatten()
19840
                .map(std::borrow::Cow::into_owned);
19840
            let opt_gdef_table = font_data_impl.gdef_table().ok().and_then(|o| o);
19840
            let num_glyphs = font_data_impl.num_glyphs();
19840
            let opt_kern_table = font_data_impl
19840
                .kern_table()
19840
                .ok()
19840
                .and_then(|s| s);
19840
            let cmap_data = font_data_impl.cmap_subtable_data();
19840
            let cmap_subtable = ReadScope::new(cmap_data);
19840
            let cmap_subtable = cmap_subtable
19840
                .read::<CmapSubtable<'_>>()
19840
                .ok()
19840
                .and_then(|s| s.to_owned());
            // Font identity hash — used by `PartialEq` for ParsedFont.
            //
            // Previously we did `font_bytes.hash(&mut hasher)` over
            // the full mmap. That touched every page of the file
            // (a 40 MiB `.ttc` walked byte-for-byte) so the "lazy
            // mmap" ended up *fully resident* the moment we built
            // a `ParsedFont`. Cold RSS jumped ~40 MiB from this
            // single line.
            //
            // The hash doesn't need to be cryptographic — it just
            // has to disambiguate two `ParsedFont`s. `(len, first
            // 4 KiB, last 4 KiB, font_index)` is plenty unique and
            // only faults in the two header / trailer pages, which
            // shaping is going to need anyway.
19840
            let mut hasher = DefaultHasher::new();
19840
            (font_bytes.len() as u64).hash(&mut hasher);
19840
            let head_len = font_bytes.len().min(4096);
19840
            font_bytes[..head_len].hash(&mut hasher);
19840
            let tail_start = font_bytes.len().saturating_sub(4096);
19840
            font_bytes[tail_start..].hash(&mut hasher);
19840
            font_index.hash(&mut hasher);
19840
            let hash = hasher.finish();
19840
            let mut font = Self {
19840
                hash,
19840
                font_metrics,
19840
                pdf_font_metrics,
19840
                num_glyphs,
19840
                hhea_table,
19840
                hmtx_range,
19840
                vmtx_range,
19840
                vhea_table,
19840
                maxp_table,
19840
                gsub_bytes,
19840
                gsub_cache_lazy: std::sync::OnceLock::new(),
19840
                gpos_bytes,
19840
                gpos_cache_lazy: std::sync::OnceLock::new(),
19840
                opt_gdef_table,
19840
                opt_kern_table,
19840
                cmap_subtable,
19840
                last_used: Arc::new(std::sync::atomic::AtomicU64::new(0)),
19840
                is_variable_font: has_gvar,
19840
                glyph_cache: Arc::new(rust_fontconfig::StLock::new(BTreeMap::new())),
19840
                // Eager path: `from_bytes` loaded LocaGlyf immediately
19840
                // (or set None if the font has no loca+glyf). Lazy
19840
                // callers use `from_bytes_shared` which replaces this
19840
                // with `LocaGlyfState::Deferred` before returning.
19840
                loca_glyf: LocaGlyfState::Loaded(loca_glyf_opt),
19840
                space_width: None,
19840
                mock: None,
19840
                reverse_glyph_cache: BTreeMap::new(),
19840
                // Don't retain the source bytes by default — layout and
19840
                // raster don't need them. PDF subsetting / `to_bytes`
19840
                // callers opt in via `with_source_bytes`.
19840
                original_bytes: None,
19840
                original_index: font_index,
19840
                index_to_cid: BTreeMap::new(), // Will be filled for CFF fonts
19840
                font_type: FontType::TrueType, // Default, will be updated if CFF
19840
                font_name,
19840
                hint_instance,
19840
            };
            // Calculate space width
19840
            let space_width = font.get_space_width_internal();
            // Pre-decode the space glyph straight into the lazy
            // `glyph_cache`. Space typically has no outline, so the
            // decoder's outline visitor returns nothing useful and
            // we'd spin re-decoding it every shape — short-circuit
            // here with a hand-rolled record carrying the hmtx
            // advance.
19840
            let _ = (|| {
19840
                let space_gid = font.lookup_glyph_index(' ' as u32)?;
                {
                    // StLock::read() is infallible (Result<_, Infallible>);
                    // kept in a tight block so the guard drops at scope end.
19822
                    let Ok(cache) = font.glyph_cache.read();
19822
                    if cache.contains_key(&space_gid) {
                        return None;
19822
                    }
                }
19822
                let space_width_val = space_width?;
                // Only pre-cache when we actually know a non-zero advance. During
                // `from_bytes_internal` the source bytes are not attached yet, so
                // `hmtx` is unreadable and `get_space_width_internal` reads back 0;
                // caching that would pin every space to a 0 advance for the life of
                // the face. Skip it and let the space decode lazily once bytes are
                // attached (mock fonts that carry a real space width still cache).
19822
                if space_width_val == 0 {
19822
                    return None;
                }
                let space_record = OwnedGlyph {
                    bounding_box: OwnedGlyphBoundingBox {
                        max_x: 0,
                        max_y: 0,
                        min_x: 0,
                        min_y: 0,
                    },
                    horz_advance: space_width_val as u16,
                    outline: Vec::new(),
                    phantom_points: None,
                    raw_points: None,
                    raw_on_curve: None,
                    raw_contour_ends: None,
                    instructions: None,
                };
                {
                    // StLock::write() is infallible (Result<_, Infallible>).
                    let Ok(mut cache) = font.glyph_cache.write();
                    cache.insert(space_gid, Arc::new(space_record));
                }
                Some(())
            })();
19840
            font.space_width = space_width;
19840
            Some(font)
19842
        }
        /// Attach the source font bytes to this `ParsedFont`, enabling
        /// [`ParsedFont::to_bytes`] and [`ParsedFont::subset`] (both of
        /// which the layout / shaping path never calls).
        ///
        /// Takes an `Arc<FontBytes>` so the same file's bytes can be
        /// shared across every face of a `.ttc` at zero extra cost —
        /// pair with [`rust_fontconfig::FcFontCache::get_font_bytes`].
        /// For ad-hoc PDF callers that have raw heap bytes, wrap them
        /// via `Arc::new(FontBytes::Owned(Arc::from(vec)))`.
        #[must_use]
1868
        pub fn with_source_bytes(mut self, bytes: Arc<rust_fontconfig::FontBytes>) -> Self {
1868
            self.original_bytes = Some(bytes);
1868
            self
1868
        }
        /// Lazy-friendly constructor — identical to
        /// [`ParsedFont::from_bytes`] except that `LocaGlyf` is
        /// **not** loaded during the call. Instead, the supplied
        /// `Arc<[u8]>` is retained and `LocaGlyf::load` runs the first
        /// time [`get_or_decode_glyph`] needs glyph outlines for this
        /// face.
        ///
        /// Fonts that get resolved into a CSS fallback chain but are
        /// never actually rasterized (common on desktop — e.g. every
        /// face of HelveticaNeue.ttc loads, but only one or two are
        /// shaped) then pay zero loca/glyf cost.
        ///
        /// Production callers (the reftest harness, `LayoutWindow`,
        /// `cpurender`) should prefer this constructor. Tests that
        /// inspect `glyph_records_decoded` directly and don't want
        /// a lazy path keep using `from_bytes`.
17826
        pub fn from_bytes_shared(
17826
            bytes: Arc<rust_fontconfig::FontBytes>,
17826
            font_index: usize,
17826
            warnings: &mut Vec<FontParseWarning>,
17826
        ) -> Option<Self> {
            // Skip the eager LocaGlyf::load via `defer_loca_glyf=true`
            // — saves the load-then-drop cycle the prior arrangement
            // paid (when this called `from_bytes`, allocated
            // ~hundreds of KiB of loca+glyf bytes, then immediately
            // replaced the slot with `Deferred` and dropped them).
            // `bytes.as_ref()` derefs FontBytes → &[u8] (mmap or owned
            // — same code path).
17826
            let mut font = Self::from_bytes_internal(bytes.as_ref(), font_index, warnings, true)?;
17820
            font.original_bytes = Some(bytes.clone());
17820
            font.loca_glyf = LocaGlyfState::Deferred {
17820
                bytes,
17820
                font_index,
17820
                loaded: Arc::new(std::sync::Mutex::new(None)),
17820
            };
17820
            Some(font)
17826
        }
        /// Resolve the current face's `LocaGlyf`, loading it lazily
        /// on first call when `loca_glyf` is `Deferred`. Returns
        /// `None` when the font has no usable loca+glyf (CFF fonts
        /// or parse failures).
4830
        fn resolve_loca_glyf(&self) -> Option<Arc<std::sync::Mutex<LocaGlyf>>> {
            use allsorts::{
                binary::read::ReadScope,
                font_data::FontData,
                tables::FontTableProvider,
            };
4830
            match &self.loca_glyf {
597
                LocaGlyfState::Loaded(inner) => inner.clone(),
4233
                LocaGlyfState::Deferred { bytes, font_index, loaded } => {
                    // Fast path: cached LocaGlyf is present.
4233
                    if let Ok(guard) = loaded.lock() {
4233
                        if let Some(arc) = guard.as_ref() {
3840
                            return Some(Arc::clone(arc));
393
                        }
                    }
393
                    let _p = crate::probe::Probe::span("resolve_loca_glyf");
                    // Slow path: parse provider + load LocaGlyf without
                    // holding the slot's lock (allsorts can take a
                    // millisecond or two on a fresh load). Re-check
                    // after acquiring the write lock so a parallel
                    // decoder doesn't double-load.
393
                    let scope = ReadScope::new(bytes.as_slice());
393
                    let font_data = scope.read::<FontData<'_>>().ok()?;
393
                    let provider = font_data.table_provider(*font_index).ok()?;
                    // Gate on table presence to match the `from_bytes`
                    // has_glyf check; avoids a spurious warning on
                    // CFF fonts that sneak into the Deferred path.
393
                    if !provider.has_table(tag::GLYF) || !provider.has_table(tag::LOCA) {
                        return None;
393
                    }
                    // Zero-copy: keep `glyf` as a view into the already-resident
                    // (mmap'd) font bytes instead of copying the whole table
                    // (~20 MB for a large font) onto the heap. `bytes` is the
                    // exact buffer `provider` reads from, so load_shared can
                    // anchor the glyf range inside it (falling back to an owned
                    // copy if it ever can't). Audit §3.3a.
393
                    let owner: Arc<dyn AsRef<[u8]> + Send + Sync> = bytes.clone();
393
                    let new_arc = LocaGlyf::load_shared(&provider, owner)
393
                        .ok()
393
                        .map(|lg| Arc::new(std::sync::Mutex::new(lg)))?;
393
                    if let Ok(mut guard) = loaded.lock() {
393
                        if let Some(existing) = guard.as_ref() {
                            return Some(Arc::clone(existing));
393
                        }
393
                        *guard = Some(Arc::clone(&new_arc));
                    }
393
                    Some(new_arc)
                }
            }
4830
        }
        /// Source bytes for PDF subsetting / table extraction.
        ///
        /// Looks in two places:
        /// - `original_bytes` (set by [`ParsedFont::with_source_bytes`]
        ///   for legacy PDF-first construction).
        /// - `LocaGlyfState::Deferred.bytes` (set by
        ///   [`ParsedFont::from_bytes_shared`] — the production lazy
        ///   path, which already retains an `Arc<[u8]>` for the lazy
        ///   loca/glyf loader).
        ///
        /// Returns `None` only for `ParsedFont`s built via the eager
        /// `from_bytes` path without an explicit `with_source_bytes`
        /// call — i.e. unit tests that load a font and don't touch
        /// PDF.
41
        pub fn source_bytes_for_subset(&self) -> Option<Arc<rust_fontconfig::FontBytes>> {
41
            if let Some(bytes) = &self.original_bytes {
38
                return Some(Arc::clone(bytes));
3
            }
3
            if let LocaGlyfState::Deferred { bytes, .. } = &self.loca_glyf {
                return Some(Arc::clone(bytes));
3
            }
3
            None
41
        }
        /// Read the monotonic-clock nanos timestamp of the most
        /// recent [`get_or_decode_glyph`] call on this face, or `0`
        /// if it's never been touched.
12
        pub fn last_used_nanos(&self) -> u64 {
12
            self.last_used.load(std::sync::atomic::Ordering::Relaxed)
12
        }
        /// Drop the cached `LocaGlyf` for this face if it's
        /// `Deferred`-with-bytes-retained — so the next
        /// [`get_or_decode_glyph`] re-parses from `bytes`. No-op for
        /// `Loaded` faces (no source bytes to fall back to).
        ///
        /// Used by [`crate::text3::cache::FontManager::evict_unused`]
        /// and exposed publicly so embedders can free memory under
        /// pressure on fonts they no longer need to render.
11
        pub fn evict_loca_glyf(&self) -> bool {
11
            match &self.loca_glyf {
6
                LocaGlyfState::Deferred { loaded, .. } => {
6
                    if let Ok(mut guard) = loaded.lock() {
6
                        if guard.is_some() {
2
                            *guard = None;
2
                            return true;
4
                        }
                    }
4
                    false
                }
5
                LocaGlyfState::Loaded(_) => false,
            }
11
        }
        /// Fetch the parsed GSUB cache if this font has one, parsing
        /// it from the retained `gsub_bytes` on first access.
        ///
        /// Moved out of the eager `from_bytes` path because most text
        /// runs never trigger GSUB — plain ASCII without ligatures is
        /// handled entirely by the cmap + hmtx fast path. Building
        /// `LayoutCacheData<GSUB>` up front reserved ~0.5–2 MiB per
        /// face just to throw it away on pages that don't shape
        /// complex scripts.
49894
        pub fn gsub(&self) -> Option<&GsubCache> {
49894
            self.gsub_cache_lazy
49894
                .get_or_init(|| {
                    use allsorts::{
                        binary::read::ReadScope,
                        layout::{new_layout_cache, LayoutTable, GSUB},
                    };
6022
                    let bytes = self.gsub_bytes.as_ref()?;
4401
                    ReadScope::new(bytes)
4401
                        .read::<LayoutTable<GSUB>>()
4401
                        .ok()
4401
                        .map(new_layout_cache)
6022
                })
49894
                .as_ref()
49894
        }
        /// Fetch the parsed GPOS cache if this font has one, parsing
        /// it from the retained `gpos_bytes` on first access. See
        /// [`ParsedFont::gsub`] for the motivation.
49894
        pub fn gpos(&self) -> Option<&GposCache> {
49894
            self.gpos_cache_lazy
49894
                .get_or_init(|| {
                    use allsorts::{
                        binary::read::ReadScope,
                        layout::{new_layout_cache, LayoutTable, GPOS},
                    };
6022
                    let bytes = self.gpos_bytes.as_ref()?;
4329
                    ReadScope::new(bytes)
4329
                        .read::<LayoutTable<GPOS>>()
4329
                        .ok()
4329
                        .map(new_layout_cache)
6022
                })
49894
                .as_ref()
49894
        }
        /// Fetch an `OwnedGlyph` for `gid`, decoding it on first access.
        ///
        /// Cached in the `Arc<RwLock<…>>` `glyph_cache` so subsequent
        /// calls (including across clones of this `ParsedFont`) hit the
        /// cache. Returns `None` when `gid >= num_glyphs` or the font
        /// has no loca+glyf and no hmtx entry for the glyph. For CFF
        /// fonts the returned record has an empty outline and an advance
        /// pulled from hmtx — matching the pre-lazy behaviour.
        ///
        /// Called on the rasterizer hot path; performance budget is a
        /// few µs per unique glyph (first hit) and an Arc bump + `BTreeMap`
        /// lookup (cache hits). The write lock is held only across the
        /// decode, not across the caller's use of the returned Arc.
8284251
        pub fn get_or_decode_glyph(&self, gid: u16) -> Option<Arc<OwnedGlyph>> {
            use std::sync::Arc;
8284251
            if usize::from(gid) >= self.num_glyphs as usize {
12
                return None;
8284239
            }
            // Bump the LRU timestamp so `FontManager::evict_unused`
            // can tell this face is still in use. Cheap atomic store
            // (Relaxed — eviction reads the same atomic and tolerates
            // a slightly stale value, which only causes "evict, then
            // re-load on next access" — never an incorrect render).
8284239
            self.last_used
8284239
                .store(monotonic_now_nanos(), std::sync::atomic::Ordering::Relaxed);
            // Fast path: cache hit.
            {
                // StLock::read() is infallible; tight block drops the read
                // guard before the write lock below (deadlock avoidance).
8284239
                let Ok(cache) = self.glyph_cache.read();
8284239
                if let Some(existing) = cache.get(&gid) {
8279413
                    return Some(Arc::clone(existing));
4826
                }
            }
            // Miss: decode. We drop the read lock before taking the
            // write lock to avoid deadlock, and we re-check on the way
            // in because another thread may have decoded the same glyph
            // in between.
4826
            let record = self.decode_glyph_inner(gid);
4826
            let arc = Arc::new(record);
            {
                // StLock::write() is infallible (Result<_, Infallible>).
4826
                let Ok(mut cache) = self.glyph_cache.write();
4826
                cache
4826
                    .entry(gid)
4826
                    .or_insert_with(|| Arc::clone(&arc));
                // If another thread beat us to the insert, return theirs
                // so all callers observe the same Arc.
4826
                if let Some(winner) = cache.get(&gid) {
4826
                    return Some(Arc::clone(winner));
                }
            }
            Some(arc)
8284251
        }
        /// Eagerly decode every glyph into the lazy `glyph_cache`,
        /// restoring the pre-lazy "every glyph is materialised at
        /// construction time" behaviour. Used by tests that iterate
        /// or compare against reference tooling, and by embedders
        /// that want a walkable view without driving every shape
        /// through `get_or_decode_glyph`.
        ///
        /// After `prime_glyph_cache`, callers can use
        /// [`ParsedFont::for_each_decoded_glyph`] or
        /// [`ParsedFont::glyph_cache_snapshot`] to observe the
        /// populated cache.
        #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
2
        pub fn prime_glyph_cache(&mut self) {
2
            let n = self.num_glyphs as usize;
192
            for glyph_index in 0..n {
192
                let gid = glyph_index as u16;
192
                drop(self.get_or_decode_glyph(gid));
192
            }
2
        }
        /// Walk every entry currently in the lazy `glyph_cache`,
        /// invoking `f(gid, &OwnedGlyph)` for each. Holds a read
        /// lock for the duration; do not call back into the font
        /// from `f`. The cache is populated on demand by
        /// [`ParsedFont::get_or_decode_glyph`] (and bulk-prefilled
        /// by [`ParsedFont::prime_glyph_cache`]).
2
        pub fn for_each_decoded_glyph<F: FnMut(u16, &OwnedGlyph)>(&self, mut f: F) {
            {
                // StLock::read() is infallible (Result<_, Infallible>).
2
                let Ok(cache) = self.glyph_cache.read();
96
                for (gid, glyph) in cache.iter() {
96
                    f(*gid, glyph.as_ref());
96
                }
            }
2
        }
        /// Snapshot of the currently-decoded glyphs as a
        /// `BTreeMap<u16, Arc<OwnedGlyph>>`. Cheap (clones the
        /// Arcs, not the records). Used by callers that want to
        /// hand the map off across an API boundary; for in-place
        /// iteration prefer [`ParsedFont::for_each_decoded_glyph`].
7
        pub fn glyph_cache_snapshot(&self) -> BTreeMap<u16, Arc<OwnedGlyph>> {
7
            self.glyph_cache
7
                .read()
7
                .map(|c| c.clone())
7
                .unwrap_or_default()
7
        }
        /// Core decode routine: produces one `OwnedGlyph` for `gid` by
        /// locking `loca_glyf` and running allsorts' outline visitor +
        /// raw-simple-glyph extraction. Factored out so both
        /// [`get_or_decode_glyph`] and [`prime_glyph_cache`] share it.
        ///
        /// Always returns an `OwnedGlyph` — if anything in the decode
        /// chain fails, falls back to an empty-outline record with the
        /// `hmtx` advance. This mirrors the pre-lazy behaviour where
        /// every gid ended up in `glyph_records_decoded`.
886563
        fn hmtx_bytes(&self) -> &[u8] {
886563
            let (off, len) = self.hmtx_range;
886563
            if len == 0 { return &[]; }
886558
            self.original_bytes.as_ref()
886558
                .map_or(&[], |b| &b.as_ref()[off..off+len])
886563
        }
111
        fn vmtx_bytes(&self) -> &[u8] {
111
            let (off, len) = self.vmtx_range;
111
            if len == 0 { return &[]; }
109
            self.original_bytes.as_ref()
109
                .map_or(&[], |b| &b.as_ref()[off..off+len])
111
        }
        #[allow(clippy::cast_possible_wrap)] // bounded graphics/coord/font/fixed-point/debug-marker cast
4828
        fn decode_glyph_inner(&self, gid: u16) -> OwnedGlyph {
4828
            let _p = crate::probe::Probe::span("decode_glyph");
            // [az-web-lift] use get_horizontal_advance (reads hmtx directly on the web build)
            // instead of allsorts::glyph_info::advance, whose lifted ReadArray parse has an
            // un-devirt'd jump table → MISSING_BLOCK → OOB during measure.
4828
            let horz_advance = self.get_horizontal_advance(gid);
4828
            let mut record = OwnedGlyph {
4828
                horz_advance,
4828
                bounding_box: OwnedGlyphBoundingBox {
4828
                    min_x: 0,
4828
                    min_y: 0,
4828
                    max_x: horz_advance as i16,
4828
                    max_y: 0,
4828
                },
4828
                outline: Vec::new(),
4828
                phantom_points: None,
4828
                raw_points: None,
4828
                raw_on_curve: None,
4828
                raw_contour_ends: None,
4828
                instructions: None,
4828
            };
            // Resolve the `LocaGlyf` for this face. For `Loaded` that's
            // a cheap `Arc::clone`; for `Deferred` this is where the
            // actual `LocaGlyf::load` happens on first access, paid once
            // per face that ever decodes a glyph.
4828
            let Some(loca_glyf_arc) = self.resolve_loca_glyf() else {
                // No usable loca+glyf → CFF / OpenType-PostScript font
                // (Noto Sans/Serif CJK and most .otf). Decode the glyph
                // from the `CFF ` table instead; the TrueType-only glyf
                // path below can't see these, which left every CFF glyph
                // blank on the cpurender/headless path (CJK rendered as
                // empty space with the hmtx advance still reserved).
2
                self.decode_cff_glyph_into(gid, &mut record);
2
                return record;
            };
4826
            let Ok(mut loca_glyf) = loca_glyf_arc.lock() else {
                return record;
            };
            // Visit the outline. If this is a variable font (gvar
            // table present) AND we still have source bytes (only
            // the `LocaGlyfState::Deferred` path retains them), we
            // re-derive a `VariableGlyfContext` here so default-
            // instance vs designed-instance differences land in
            // the decoded outline. The chained `if let` pattern
            // keeps `provider` and `store` in scope for the
            // visit, which the borrow checker requires (the
            // store's `Cow::Borrowed(&[u8])` tables tie its
            // lifetime to the provider).
            //
            // Eager-`from_bytes` faces (no retained bytes) and
            // non-variable fonts skip the var-context machinery
            // and decode the default instance — same behaviour as
            // before R4.
            // [az-web-lift] The lifted web layout NEVER rasterizes (it measures + positions, then
            // ships a display list to JS) — so glyph OUTLINES + TrueType hinting raw-points are
            // never needed in wasm. Decoding them (allsorts GlyfVisitorContext::visit +
            // GlyphOutlineCollector::into_outlines, whose GlyphOutlineOperation match is a 5-arm
            // jump table the remill lift doesn't devirtualize → MISSING_BLOCK → OOB) crashes the
            // measure pass. Skip BOTH decode passes on the web build; the record keeps its hmtx
            // advance/metrics (set above) which is all text measurement needs.
4826
            if !cfg!(feature = "web_lift") {
4826
            let mut outline_done = false;
4826
            if self.is_variable_font {
                if let LocaGlyfState::Deferred { bytes, .. } = &self.loca_glyf {
                    let scope = ReadScope::new(bytes);
                    if let Ok(font_data) =
                        scope.read::<FontData<'_>>()
                    {
                        if let Ok(provider) = font_data.table_provider(self.original_index) {
                            if let Ok(store) = VariableGlyfContextStore::read(&provider) {
                                if let Ok(var_ctx) = VariableGlyfContext::new(&store) {
                                    let mut visitor = GlyfVisitorContext::new(
                                        &mut loca_glyf,
                                        Some(var_ctx),
                                    );
                                    let mut collector = GlyphOutlineCollector::new();
                                    if visitor.visit(gid, None, &mut collector).is_ok() {
                                        record.outline = collector.into_outlines();
                                        let (min_x, min_y, max_x, max_y) =
                                            compute_outline_bbox(&record.outline);
                                        record.bounding_box = OwnedGlyphBoundingBox {
                                            min_x,
                                            min_y,
                                            max_x,
                                            max_y,
                                        };
                                        outline_done = true;
                                    }
                                }
                            }
                        }
                    }
                }
4826
            }
4826
            if !outline_done {
4826
                let mut visitor =
4826
                    GlyfVisitorContext::new(&mut loca_glyf, None);
4826
                let mut collector = GlyphOutlineCollector::new();
4826
                if visitor.visit(gid, None, &mut collector).is_ok() {
4826
                    record.outline = collector.into_outlines();
4826
                    let (min_x, min_y, max_x, max_y) =
4826
                        compute_outline_bbox(&record.outline);
4826
                    record.bounding_box = OwnedGlyphBoundingBox {
4826
                        min_x,
4826
                        min_y,
4826
                        max_x,
4826
                        max_y,
4826
                    };
4826
                }
            }
            // Second pass: pull raw SimpleGlyph data for TrueType
            // bytecode hinting. LocaGlyf caches the `Arc<Glyph>`
            // internally so this lookup is cheap after the first call.
4826
            if let Ok(glyph_arc) = loca_glyf.glyph(gid) {
                // `is_on_curve` moved onto the `SimpleGlyphFlagExt` trait in
                // allsorts 0.17 (SimpleGlyphFlags is now a BitFlags alias).
                use allsorts::tables::glyf::SimpleGlyphFlagExt;
4826
                if let allsorts::tables::glyf::Glyph::Simple(sg) = glyph_arc.as_ref() {
4579
                    record.raw_points = Some(
102304
                        sg.coordinates.iter().map(|(_, pt)| (pt.0, pt.1)).collect(),
                    );
4579
                    record.raw_on_curve = Some(
102304
                        sg.coordinates.iter().map(|(f, _)| f.is_on_curve()).collect(),
                    );
4579
                    record.raw_contour_ends = Some(sg.end_pts_of_contours.clone());
4579
                    record.instructions = Some(sg.instructions.to_vec());
247
                }
            }
            } // [az-web-lift] end skip glyph outline/hinting decode on web
4826
            record
4828
        }
        /// Decode a single glyph outline from the `CFF ` (OpenType
        /// PostScript) table into `record`. Used for fonts with no `glyf`
        /// table — `decode_glyph_inner`'s TrueType path returns an empty
        /// outline for them, so without this every CFF glyph rasterised as
        /// blank on the CPU renderer. Notably this hit ALL CJK text: the
        /// installed Noto Sans/Serif CJK fonts are CID-keyed CFF. allsorts'
        /// `CFFOutlines` feeds the same `GlyphOutlineCollector` the glyf
        /// path uses and resolves CID-keyed local subrs internally.
2
        fn decode_cff_glyph_into(&self, gid: u16, record: &mut OwnedGlyph) {
            use allsorts::cff::{outline::CFFOutlines, CFF};
2
            let Some(ref original) = self.original_bytes else {
2
                return;
            };
            let bytes: &[u8] = original.as_slice();
            let Ok(font_data) = ReadScope::new(bytes).read::<FontData<'_>>() else {
                return;
            };
            let Ok(provider) = font_data.table_provider(self.original_index) else {
                return;
            };
            let Ok(Some(cff_data)) = provider.table_data(tag::CFF) else {
                return;
            };
            let Ok(cff) = ReadScope::new(&cff_data).read::<CFF<'_>>() else {
                return;
            };
            let mut outlines = CFFOutlines { table: &cff };
            let mut collector = GlyphOutlineCollector::new();
            if outlines.visit(gid, None, &mut collector).is_ok() {
                record.outline = collector.into_outlines();
                let (min_x, min_y, max_x, max_y) = compute_outline_bbox(&record.outline);
                record.bounding_box = OwnedGlyphBoundingBox {
                    min_x,
                    min_y,
                    max_x,
                    max_y,
                };
            }
2
        }
        /// Parse PDF-specific font metrics from HEAD, HHEA, and OS/2 tables
19840
        fn parse_pdf_font_metrics(
19840
            font_bytes: &[u8],
19840
            font_index: usize,
19840
            head_table: &allsorts::tables::HeadTable,
19840
            hhea_table: &HheaTable,
19840
        ) -> PdfFontMetrics {
            use allsorts::{
                binary::read::ReadScope,
                font_data::FontData,
                tables::{os2::Os2, FontTableProvider},
                tag,
            };
19840
            let scope = ReadScope::new(font_bytes);
19840
            let font_file = scope.read::<FontData<'_>>().ok();
19840
            let provider = font_file
19840
                .as_ref()
19840
                .and_then(|ff| ff.table_provider(font_index).ok());
19840
            let os2_table = provider
19840
                .as_ref()
19840
                .and_then(|p| p.table_data(tag::OS_2).ok())
19840
                .and_then(|os2_data| {
19840
                    let data = os2_data?;
19839
                    let scope = ReadScope::new(&data);
19839
                    scope.read_dep::<Os2>(data.len()).ok()
19840
                });
            // Base metrics from HEAD and HHEA (always present)
19840
            let base = PdfFontMetrics {
19840
                units_per_em: head_table.units_per_em,
19840
                font_flags: head_table.flags,
19840
                x_min: head_table.x_min,
19840
                y_min: head_table.y_min,
19840
                x_max: head_table.x_max,
19840
                y_max: head_table.y_max,
19840
                ascender: hhea_table.ascender,
19840
                descender: hhea_table.descender,
19840
                line_gap: hhea_table.line_gap,
19840
                advance_width_max: hhea_table.advance_width_max,
19840
                caret_slope_rise: hhea_table.caret_slope_rise,
19840
                caret_slope_run: hhea_table.caret_slope_run,
19840
                ..PdfFontMetrics::zero()
19840
            };
            // Add OS/2 metrics if available
19840
            os2_table
19840
                .map_or(base, |os2| PdfFontMetrics {
19839
                    x_avg_char_width: os2.x_avg_char_width,
19839
                    us_weight_class: os2.us_weight_class,
19839
                    us_width_class: os2.us_width_class,
19839
                    y_strikeout_size: os2.y_strikeout_size,
19839
                    y_strikeout_position: os2.y_strikeout_position,
                    ..base
19839
                })
19840
        }
        /// Returns the width of the space character in font units.
        ///
        /// This is used internally for text layout calculations.
        /// Returns `None` if the font has no space glyph or its width cannot be determined.
19842
        fn get_space_width_internal(&self) -> Option<usize> {
19842
            if let Some(mock) = self.mock.as_ref() {
1
                return mock.space_width;
19841
            }
19841
            let glyph_index = self.lookup_glyph_index(' ' as u32)?;
            // [az-web-lift] use get_horizontal_advance (direct hmtx on web) instead of
            // allsorts::glyph_info::advance (un-devirt'd jump table → OOB).
19822
            Some(self.get_horizontal_advance(glyph_index) as usize)
19842
        }
        /// Look up the glyph index for a Unicode codepoint
950596
        pub fn lookup_glyph_index(&self, codepoint: u32) -> Option<u16> {
950596
            let cmap = self.cmap_subtable.as_ref()?;
950592
            cmap.map_glyph(codepoint).ok().flatten()
950596
        }
        /// Get the horizontal advance width for a glyph in font units.
        ///
        /// Pulled straight from the `hmtx` table — no glyph-outline
        /// decode. Called once per shaped glyph per layout pass, so
        /// avoiding the lazy decode here is a meaningful win over
        /// routing through `get_or_decode_glyph`.
886560
        pub fn get_horizontal_advance(&self, glyph_index: u16) -> u16 {
886560
            if let Some(mock) = self.mock.as_ref() {
4
                return mock.glyph_advances.get(&glyph_index).copied().unwrap_or(0);
886556
            }
            // [az-web-lift] Read the hmtx advance DIRECTLY (a plain longHorMetric table lookup)
            // instead of allsorts::glyph_info::advance, whose lifted binary `ReadArray` parse has
            // an un-devirt'd jump table → MISSING_BLOCK → OOB during text measure. Identical result
            // for non-variable fonts (the web fallback font is non-variable); native keeps the
            // allsorts path (variable-font deltas etc.).
            #[cfg(feature = "web_lift")]
            {
                let hmtx = self.hmtx_bytes();
                let num = usize::from(self.hhea_table.num_h_metrics);
                if num == 0 {
                    return 0;
                }
                let idx = (glyph_index as usize).min(num - 1);
                let off = idx * 4;
                return if off + 2 <= hmtx.len() {
                    ((hmtx[off] as u16) << 8) | (hmtx[off + 1] as u16)
                } else {
                    0
                };
            }
            #[cfg(not(feature = "web_lift"))]
            {
886556
                allsorts::glyph_info::advance(
886556
                    &self.maxp_table,
886556
                    &self.hhea_table,
886556
                    self.hmtx_bytes(),
886556
                    glyph_index,
                )
886556
                .unwrap_or_default()
            }
886560
        }
        /// Get the hinted advance width in pixels for a glyph at the given ppem.
        ///
        /// For glyphs with outlines, runs TrueType bytecode hinting to get the
        /// grid-fitted advance from phantom points. For glyphs without outlines
        /// (e.g. space), rounds the scaled advance to the pixel grid, matching
        /// `FreeType`'s behavior.
        ///
        /// Returns `None` if hinting is not available or fails.
        #[allow(clippy::cast_precision_loss)] // bounded graphics/coord/font/fixed-point/debug-marker cast
9
        pub fn get_hinted_advance_px(&self, glyph_index: u16, ppem: u16) -> Option<f32> {
            // [az-web-lift] No pixel grid-fitting on the web (measure-only): return None so the
            // caller falls back to the plain scaled advance. Hard-cfg (not a runtime `if cfg!`)
            // so the whole hinting body — get_or_decode_glyph's outline path AND set_ppem →
            // allsorts Interpreter::dispatch (opcode jump table → OOB) — is removed from the lift
            // closure entirely. SEPARATE concern from the transpiler's jump-table devirt: web has
            // no use for hinted advances regardless of lift quality. Native is unchanged.
            #[cfg(feature = "web_lift")]
            {
                let _ = (glyph_index, ppem);
                None
            }
            #[cfg(not(feature = "web_lift"))]
            {
            use allsorts::hinting::f26dot6::{compute_scale, F26Dot6};
9
            let glyph = self.get_or_decode_glyph(glyph_index)?;
6
            let upem = self.font_metrics.units_per_em;
6
            if upem == 0 || ppem == 0 {
1
                return None;
5
            }
            // Check if we even have a hint instance
5
            let hint_mutex = self.hint_instance.as_ref()?;
5
            let scale = compute_scale(ppem, upem);
            // Round the LIVE hmtx advance, not the decoded glyph's cached
            // `horz_advance`. The space glyph is eagerly pre-cached during
            // `from_bytes_internal` before `original_bytes` is attached, so its
            // cached advance can be a stale 0; and this function only ever rounds
            // the scaled hmtx advance to the pixel grid anyway (see below), never
            // the hinted phantom point. For every correctly-decoded glyph the two
            // are identical, so this is a no-op except for the stale-space case.
5
            let hmtx_advance = self.get_horizontal_advance(glyph_index);
5
            let adv_f26dot6 = F26Dot6::from_funits(i32::from(hmtx_advance), scale);
            // For glyphs with outline data, run bytecode hinting
5
            if let (Some(raw_points), Some(raw_on_curve), Some(raw_contour_ends)) = (
5
                glyph.raw_points.as_ref(),
5
                glyph.raw_on_curve.as_ref(),
5
                glyph.raw_contour_ends.as_ref(),
            ) {
5
                let instructions = glyph.instructions.as_deref().unwrap_or(&[]);
5
                let mut hint = hint_mutex.lock().ok()?;
5
                hint.set_ppem(ppem, f64::from(ppem)).ok()?;
5
                drop(hint);
5
                let points_f26dot6: Vec<(i32, i32)> = raw_points
5
                    .iter()
140
                    .map(|&(x, y)| {
140
                        let sx = F26Dot6::from_funits(i32::from(x), scale);
140
                        let sy = F26Dot6::from_funits(i32::from(y), scale);
140
                        (sx.to_bits(), sy.to_bits())
140
                    })
5
                    .collect();
            }
            // Use the scaled advance rounded to pixel grid, NOT the hinted
            // phantom point.  Some glyph programs apply ClearType-specific SHPIX
            // adjustments to the advance phantom point that are wrong for
            // non-ClearType rendering.  The rounded scaled advance matches
            // FreeType's DEFAULT mode advance output (and, for glyphs without an
            // outline such as space, FreeType's phantom-point pre-rounding).
5
            let rounded = (adv_f26dot6.to_bits() + 32) & !63;
5
            Some(rounded as f32 / 64.0)
            } // [az-web-lift] end #[cfg(not(web_lift))] hinting body
9
        }
        /// Get the number of glyphs in this font
47665
        pub const fn num_glyphs(&self) -> u16 {
47665
            self.num_glyphs
47665
        }
        /// Check if this font has a glyph for the given codepoint
68
        pub fn has_glyph(&self, codepoint: u32) -> bool {
68
            self.lookup_glyph_index(codepoint).is_some()
68
        }
        /// Get vertical metrics for a glyph (for vertical text layout).
        ///
        /// Uses vhea+vmtx tables (same binary format as hhea+hmtx).
        /// Returns None if font has no vertical metrics tables.
        #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
861592
        pub fn get_vertical_metrics(
861592
            &self,
861592
            glyph_id: u16,
861592
        ) -> Option<crate::text3::cache::VerticalMetrics> {
861592
            let vhea = self.vhea_table.as_ref()?;
109
            if self.vmtx_range.1 == 0 {
1
                return None;
108
            }
108
            let vert_advance = f32::from(allsorts::glyph_info::advance(
108
                &self.maxp_table, vhea, self.vmtx_bytes(), glyph_id,
108
            ).ok()?);
108
            let units_per_em = f32::from(self.font_metrics.units_per_em);
108
            let scale = if units_per_em > 0.0 { 1.0 / units_per_em } else { 0.001 };
            // Vertical bearing: approximate from glyph bbox if available
108
            let (bearing_x, bearing_y) = self.get_or_decode_glyph(glyph_id)
108
                .map_or((0.0, 0.0), |g| {
108
                    let bbox = &g.bounding_box;
                    // tsb (top side bearing): origin_y - max_y
                    // lsb for vertical: center the glyph horizontally
108
                    let width = f32::from(bbox.max_x - bbox.min_x);
108
                    (-(width / 2.0) * scale, (vert_advance * scale) - (f32::from(bbox.max_y) * scale))
108
                });
108
            Some(crate::text3::cache::VerticalMetrics {
108
                advance: vert_advance * scale,
108
                bearing_x,
108
                bearing_y,
108
                origin_y: self.font_metrics.ascent * scale,
108
            })
861592
        }
        /// Get layout-specific font metrics
        #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
7
        pub fn get_font_metrics(&self) -> LayoutFontMetrics {
            // Ensure descent is positive (OpenType may have negative descent)
7
            let descent = if self.font_metrics.descent > 0.0 {
1
                self.font_metrics.descent
            } else {
6
                -self.font_metrics.descent
            };
7
            LayoutFontMetrics {
7
                ascent: self.font_metrics.ascent,
7
                descent,
7
                line_gap: self.font_metrics.line_gap,
7
                units_per_em: self.font_metrics.units_per_em,
7
                x_height: self.font_metrics.x_height,
7
                cap_height: self.font_metrics.cap_height,
7
            }
7
        }
        /// Convert the `ParsedFont` back to bytes using `allsorts::whole_font`
        /// This reconstructs the entire font from the parsed data
        ///
        /// Source bytes come from either the explicit
        /// [`ParsedFont::with_source_bytes`] handle (PDF-first
        /// construction) *or* the `LocaGlyfState::Deferred` slot
        /// installed by [`ParsedFont::from_bytes_shared`]. The
        /// production lazy path retains bytes for the lazy `LocaGlyf`
        /// loader, so PDF subsetting Just Works without an extra
        /// `with_source_bytes` call.
        ///
        /// # Arguments
        /// * `tags` - Optional list of specific table tags to include (None = all tables)
        /// # Errors
        ///
        /// Returns an error string if serializing the font fails.
5
        pub fn to_bytes(&self, tags: Option<&[u32]>) -> Result<Vec<u8>, String> {
5
            let source = self.source_bytes_for_subset().ok_or_else(|| {
1
                "ParsedFont::to_bytes requires source bytes; construct via \
1
                 ParsedFont::from_bytes_shared (production lazy path) or \
1
                 attach via ParsedFont::with_source_bytes"
1
                    .to_string()
1
            })?;
4
            let scope = ReadScope::new(source.as_slice());
4
            let font_file = scope.read::<FontData<'_>>().map_err(|e| e.to_string())?;
4
            let provider = font_file
4
                .table_provider(self.original_index)
4
                .map_err(|e| e.to_string())?;
4
            let tags_to_use = tags.unwrap_or(&[
4
                tag::CMAP,
4
                tag::HEAD,
4
                tag::HHEA,
4
                tag::HMTX,
4
                tag::MAXP,
4
                tag::NAME,
4
                tag::OS_2,
4
                tag::POST,
4
                tag::GLYF,
4
                tag::LOCA,
4
            ]);
4
            whole_font(&provider, tags_to_use).map_err(|e| e.to_string())
5
        }
        /// Create a subset font containing only the specified glyph IDs
        /// Returns the subset font bytes and a mapping from old to new glyph IDs
        ///
        /// # Arguments
        /// * `glyph_ids` - The glyph IDs to include in the subset (glyph 0/.notdef is always
        ///   included)
        /// * `cmap_target` - Target cmap format (Unicode for web, `MacRoman` for compatibility)
        ///
        /// # Returns
        /// A tuple of (`subset_font_bytes`, `glyph_mapping`) where `glyph_mapping` maps
        /// `original_glyph_id` -> (`new_glyph_id`, `original_char`)
        #[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
        /// # Errors
        ///
        /// Returns an error string if subsetting the font fails.
5
        pub fn subset(
5
            &self,
5
            glyph_ids: &[(u16, char)],
5
            cmap_target: CmapTarget,
5
        ) -> Result<(Vec<u8>, BTreeMap<u16, (u16, char)>), String> {
5
            let source = self.source_bytes_for_subset().ok_or_else(|| {
1
                "ParsedFont::subset requires source bytes; construct via \
1
                 ParsedFont::from_bytes_shared (production lazy path) or \
1
                 attach via ParsedFont::with_source_bytes"
1
                    .to_string()
1
            })?;
4
            let scope = ReadScope::new(source.as_slice());
4
            let font_file = scope.read::<FontData<'_>>().map_err(|e| e.to_string())?;
4
            let provider = font_file
4
                .table_provider(self.original_index)
4
                .map_err(|e| e.to_string())?;
            // Build glyph mapping: original_id -> (new_id, char)
4
            let glyph_mapping: BTreeMap<u16, (u16, char)> = glyph_ids
4
                .iter()
4
                .enumerate()
8
                .map(|(new_id, &(original_id, ch))| (original_id, (new_id as u16, ch)))
4
                .collect();
            // Extract just the glyph IDs for subsetting
4
            let ids: Vec<u16> = glyph_ids.iter().map(|(id, _)| *id).collect();
            // Use PDF profile for embedding fonts in PDFs
4
            let font_bytes = allsorts_subset(&provider, &ids, &SubsetProfile::Pdf, cmap_target)
4
                .map_err(|e| format!("Subset error: {e:?}"))?;
3
            Ok((font_bytes, glyph_mapping))
5
        }
        /// Get the width of a glyph in font units (internal, unscaled)
4
        pub fn get_glyph_width_internal(&self, glyph_index: u16) -> Option<usize> {
4
            allsorts::glyph_info::advance(
4
                &self.maxp_table,
4
                &self.hhea_table,
4
                self.hmtx_bytes(),
4
                glyph_index,
            )
4
            .ok()
4
            .map(|s| s as usize)
4
        }
        /// Get the width of the space character (unscaled font units)
        #[inline]
7
        pub const fn get_space_width(&self) -> Option<usize> {
7
            self.space_width
7
        }
        /// Add glyph-to-text mapping to reverse cache
        /// This should be called during text shaping when we know both the source text and
        /// resulting glyphs
4
        pub fn cache_glyph_mapping(&mut self, glyph_id: u16, cluster_text: &str) {
4
            self.reverse_glyph_cache
4
                .insert(glyph_id, cluster_text.to_string());
4
        }
        /// Get the cluster text that produced a specific glyph ID
        /// Returns the original text that was shaped into this glyph (handles ligatures correctly)
7
        pub fn get_glyph_cluster_text(&self, glyph_id: u16) -> Option<&str> {
7
            self.reverse_glyph_cache.get(&glyph_id).map(String::as_str)
7
        }
        /// Get the first character from the cluster text for a glyph ID
        /// This is useful for PDF `ToUnicode` `CMap` generation which requires single character
        /// mappings
5
        pub fn get_glyph_primary_char(&self, glyph_id: u16) -> Option<char> {
5
            self.reverse_glyph_cache
5
                .get(&glyph_id)
5
                .and_then(|text| text.chars().next())
5
        }
        /// Clear the reverse glyph cache (useful for memory management)
2
        pub fn clear_glyph_cache(&mut self) {
2
            self.reverse_glyph_cache.clear();
2
        }
        /// Get the bounding box size of a glyph (unscaled units) - for PDF
        /// Returns (width, height) in font units
5
        pub fn get_glyph_bbox_size(&self, glyph_index: u16) -> Option<(i32, i32)> {
5
            let g = self.get_or_decode_glyph(glyph_index)?;
2
            let glyph_width = i32::from(g.horz_advance);
2
            let glyph_height = i32::from(g.bounding_box.max_y) - i32::from(g.bounding_box.min_y);
2
            Some((glyph_width, glyph_height))
5
        }
    }
    /// Compute the bounding box from collected glyph outlines.
4830
    fn compute_outline_bbox(outlines: &[GlyphOutline]) -> (i16, i16, i16, i16) {
4830
        let mut min_x = i16::MAX;
4830
        let mut min_y = i16::MAX;
4830
        let mut max_x = i16::MIN;
4830
        let mut max_y = i16::MIN;
4830
        let mut has_points = false;
17083
        for outline in outlines {
101949
            for op in outline.operations.as_slice() {
101949
                let points: &[(i16, i16)] = match op {
12251
                    GlyphOutlineOperation::MoveTo(m) => &[(m.x, m.y)],
44476
                    GlyphOutlineOperation::LineTo(l) => &[(l.x, l.y)],
32970
                    GlyphOutlineOperation::QuadraticCurveTo(q) => {
                        // Check both control and end point for bbox
32970
                        min_x = min_x.min(q.ctrl_1_x).min(q.end_x);
32970
                        min_y = min_y.min(q.ctrl_1_y).min(q.end_y);
32970
                        max_x = max_x.max(q.ctrl_1_x).max(q.end_x);
32970
                        max_y = max_y.max(q.ctrl_1_y).max(q.end_y);
32970
                        has_points = true;
32970
                        continue;
                    }
1
                    GlyphOutlineOperation::CubicCurveTo(c) => {
1
                        min_x = min_x.min(c.ctrl_1_x).min(c.ctrl_2_x).min(c.end_x);
1
                        min_y = min_y.min(c.ctrl_1_y).min(c.ctrl_2_y).min(c.end_y);
1
                        max_x = max_x.max(c.ctrl_1_x).max(c.ctrl_2_x).max(c.end_x);
1
                        max_y = max_y.max(c.ctrl_1_y).max(c.ctrl_2_y).max(c.end_y);
1
                        has_points = true;
1
                        continue;
                    }
12251
                    GlyphOutlineOperation::ClosePath => continue,
                };
113454
                for &(x, y) in points {
56727
                    min_x = min_x.min(x);
56727
                    min_y = min_y.min(y);
56727
                    max_x = max_x.max(x);
56727
                    max_y = max_y.max(y);
56727
                    has_points = true;
56727
                }
            }
        }
4830
        if has_points {
4582
            (min_x, min_y, max_x, max_y)
        } else {
248
            (0, 0, 0, 0)
        }
4830
    }
    #[derive(Debug, Clone)]
    pub struct OwnedGlyph {
        pub bounding_box: OwnedGlyphBoundingBox,
        pub horz_advance: u16,
        pub outline: Vec<GlyphOutline>,
        pub phantom_points: Option<[Point; 4]>,
        /// Raw TrueType points in font units (for hinting). None for composite/CFF glyphs.
        pub raw_points: Option<Vec<(i16, i16)>>,
        /// On-curve flags for each raw point.
        pub raw_on_curve: Option<Vec<bool>>,
        /// Contour end-point indices (TrueType).
        pub raw_contour_ends: Option<Vec<u16>>,
        /// Per-glyph TrueType hinting instructions.
        pub instructions: Option<Vec<u8>>,
    }
    // --- ParsedFontTrait Implementation for ParsedFont ---
    impl crate::text3::cache::ShallowClone for ParsedFont {
        fn shallow_clone(&self) -> Self {
            self.clone() // ParsedFont::clone uses Arc internally, so it's shallow
        }
    }
    impl crate::text3::cache::ParsedFontTrait for ParsedFont {
        fn shape_text(
            &self,
            text: &str,
            script: crate::font_traits::Script,
            language: crate::font_traits::Language,
            direction: crate::font_traits::BidiDirection,
            style: &crate::font_traits::StyleProperties,
        ) -> Result<Vec<crate::font_traits::Glyph>, crate::font_traits::LayoutError> {
            // Call the existing shape_text_for_parsed_font method (defined in default.rs)
            crate::text3::default::shape_text_for_parsed_font(
                self, text, script, language, direction, style,
            )
        }
        fn get_hash(&self) -> u64 {
            self.hash
        }
11
        fn get_glyph_size(
11
            &self,
11
            glyph_id: u16,
11
            font_size_px: f32,
11
        ) -> Option<azul_core::geom::LogicalSize> {
11
            self.get_or_decode_glyph(glyph_id).map(|record| {
11
                let units_per_em = f32::from(self.font_metrics.units_per_em);
11
                let scale_factor = if units_per_em > 0.0 {
11
                    font_size_px / units_per_em
                } else {
                    0.01
                };
11
                let bbox = &record.bounding_box;
11
                azul_core::geom::LogicalSize {
11
                    width: f32::from(bbox.max_x - bbox.min_x) * scale_factor,
11
                    height: f32::from(bbox.max_y - bbox.min_y) * scale_factor,
11
                }
11
            })
11
        }
        fn get_hyphen_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
            let glyph_id = self.lookup_glyph_index('-' as u32)?;
            let advance_units = self.get_horizontal_advance(glyph_id);
            let scale_factor = if self.font_metrics.units_per_em > 0 {
                font_size / f32::from(self.font_metrics.units_per_em)
            } else {
                return None;
            };
            let scaled_advance = f32::from(advance_units) * scale_factor;
            Some((glyph_id, scaled_advance))
        }
        fn get_kashida_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
            let glyph_id = self.lookup_glyph_index('\u{0640}' as u32)?;
            let advance_units = self.get_horizontal_advance(glyph_id);
            let scale_factor = if self.font_metrics.units_per_em > 0 {
                font_size / f32::from(self.font_metrics.units_per_em)
            } else {
                return None;
            };
            let scaled_advance = f32::from(advance_units) * scale_factor;
            Some((glyph_id, scaled_advance))
        }
        fn has_glyph(&self, codepoint: u32) -> bool {
            self.lookup_glyph_index(codepoint).is_some()
        }
        fn get_vertical_metrics(
            &self,
            glyph_id: u16,
        ) -> Option<crate::text3::cache::VerticalMetrics> {
            self.get_vertical_metrics(glyph_id)
        }
        fn get_font_metrics(&self) -> LayoutFontMetrics {
            self.font_metrics
        }
        fn num_glyphs(&self) -> u16 {
            self.num_glyphs
        }
        fn get_space_width(&self) -> Option<usize> {
            self.space_width
        }
    }
    /// Build an agg-rust `PathStorage` from an `OwnedGlyph` outline (in font units, Y-up → Y-down).
    ///
    /// Returns `None` if the glyph has no outline operations (e.g. space).
    /// The caller is responsible for applying scale and translation transforms.
    #[cfg(feature = "cpurender")]
8564
    #[must_use] pub fn build_glyph_path(glyph: &OwnedGlyph) -> Option<agg_rust::path_storage::PathStorage> {
        use agg_rust::{basics::PATH_FLAGS_NONE, path_storage::PathStorage};
8564
        let mut path = PathStorage::new();
8564
        let mut has_ops = false;
8717
        for outline in &glyph.outline {
1825
            for op in outline.operations.as_slice() {
1825
                has_ops = true;
1825
                match op {
152
                    GlyphOutlineOperation::MoveTo(OutlineMoveTo { x, y }) => {
152
                        path.move_to(f64::from(*x), -f64::from(*y));
152
                    }
631
                    GlyphOutlineOperation::LineTo(OutlineLineTo { x, y }) => {
631
                        path.line_to(f64::from(*x), -f64::from(*y));
631
                    }
                    GlyphOutlineOperation::QuadraticCurveTo(OutlineQuadTo {
889
                        ctrl_1_x, ctrl_1_y, end_x, end_y,
889
                    }) => {
889
                        path.curve3(
889
                            f64::from(*ctrl_1_x), -f64::from(*ctrl_1_y),
889
                            f64::from(*end_x), -f64::from(*end_y),
889
                        );
889
                    }
                    GlyphOutlineOperation::CubicCurveTo(OutlineCubicTo {
1
                        ctrl_1_x, ctrl_1_y, ctrl_2_x, ctrl_2_y, end_x, end_y,
1
                    }) => {
1
                        path.curve4(
1
                            f64::from(*ctrl_1_x), -f64::from(*ctrl_1_y),
1
                            f64::from(*ctrl_2_x), -f64::from(*ctrl_2_y),
1
                            f64::from(*end_x), -f64::from(*end_y),
1
                        );
1
                    }
152
                    GlyphOutlineOperation::ClosePath => {
152
                        path.close_polygon(PATH_FLAGS_NONE);
152
                    }
                }
            }
        }
8564
        if !has_ops {
8465
            return None;
99
        }
99
        Some(path)
8564
    }
    #[cfg(test)]
    mod autotest_generated {
        //! Adversarial unit tests generated by the autotest fleet.
        //!
        //! Lives inside `mod parsed` (not at file scope) so it can reach the
        //! private sfnt scanner (`manual_be16` / `manual_be32` /
        //! `ManualTableProvider`), the outline collector, and the private
        //! `ParsedFont` getters.
        use allsorts::tables::SfntVersion;
        use super::*;
        /// Positive control: the built-in `Azul Mock Mono` TrueType font.
        /// 13 tables, `glyf` outlines (no CFF), no `vhea`/`vmtx`, upem 1000,
        /// 96 glyphs, GSUB + GPOS + GDEF present (empty lists, presence-only).
        const MOCK_MONO: &[u8] = crate::text3::mock_fonts::MOCK_MONO_TTF;
        fn parse_mock() -> ParsedFont {
            let mut warnings = Vec::new();
            ParsedFont::from_bytes(MOCK_MONO, 0, &mut warnings)
                .expect("Azul Mock Mono must parse (positive control)")
        }
        fn mock_shared() -> ParsedFont {
            let bytes = Arc::new(rust_fontconfig::FontBytes::Owned(Arc::from(MOCK_MONO.to_vec())));
            let mut warnings = Vec::new();
            ParsedFont::from_bytes_shared(bytes, 0, &mut warnings)
                .expect("from_bytes_shared must parse the positive control")
        }
        fn plain_metrics() -> LayoutFontMetrics {
            LayoutFontMetrics {
                ascent: 800.0,
                descent: -200.0,
                line_gap: 0.0,
                units_per_em: 1000,
                x_height: None,
                cap_height: None,
            }
        }
        fn plain_hhea() -> HheaTable {
            HheaTable {
                ascender: 800,
                descender: -200,
                line_gap: 0,
                advance_width_max: 1000,
                min_left_side_bearing: 0,
                min_right_side_bearing: 0,
                x_max_extent: 0,
                caret_slope_rise: 1,
                caret_slope_run: 0,
                caret_offset: 0,
                num_h_metrics: 0,
            }
        }
        /// A hand-built `ParsedFont` with no tables, no cmap and no source
        /// bytes — the "default / empty / extreme instance" every getter has
        /// to survive.
        fn synthetic_font(num_glyphs: u16, mock: Option<Box<MockFont>>) -> ParsedFont {
            ParsedFont {
                hash: 0,
                font_metrics: plain_metrics(),
                pdf_font_metrics: PdfFontMetrics::zero(),
                num_glyphs,
                hhea_table: plain_hhea(),
                hmtx_range: (0, 0),
                vmtx_range: (0, 0),
                vhea_table: None,
                maxp_table: MaxpTable {
                    num_glyphs,
                    version1_sub_table: None,
                },
                gsub_bytes: None,
                gsub_cache_lazy: std::sync::OnceLock::new(),
                gpos_bytes: None,
                gpos_cache_lazy: std::sync::OnceLock::new(),
                opt_gdef_table: None,
                opt_kern_table: None,
                last_used: Arc::new(std::sync::atomic::AtomicU64::new(0)),
                is_variable_font: false,
                glyph_cache: Arc::new(rust_fontconfig::StLock::new(BTreeMap::new())),
                loca_glyf: LocaGlyfState::Loaded(None),
                space_width: None,
                cmap_subtable: None,
                mock,
                reverse_glyph_cache: BTreeMap::new(),
                original_bytes: None,
                original_index: 0,
                index_to_cid: BTreeMap::new(),
                font_type: FontType::TrueType,
                font_name: None,
                hint_instance: None,
            }
        }
        // ---------------------------------------------------------------
        // manual_be16 / manual_be32 (numeric)
        // ---------------------------------------------------------------
        #[test]
        fn manual_be16_zero_max_and_offset() {
            assert_eq!(manual_be16(&[0x00, 0x00], 0), 0);
            assert_eq!(manual_be16(&[0xFF, 0xFF], 0), 0xFFFF);
            assert_eq!(manual_be16(&[0x12, 0x34], 0), 0x1234);
            // the widest 16-bit value still fits the u32 return: no truncation
            assert_eq!(manual_be16(&[0xAA, 0xBB, 0xFF, 0xFF], 2), u32::from(u16::MAX));
            // offsets address the right bytes, not the first ones
            assert_eq!(manual_be16(&[0xAA, 0xBB, 0x00, 0x01], 2), 1);
        }
        #[test]
        fn manual_be32_zero_max_and_known_tags() {
            assert_eq!(manual_be32(&[0, 0, 0, 0], 0), 0);
            // saturating the whole word must not overflow the u32 accumulator
            assert_eq!(manual_be32(&[0xFF, 0xFF, 0xFF, 0xFF], 0), u32::MAX);
            assert_eq!(manual_be32(b"ttcf", 0), 0x7474_6366);
            assert_eq!(manual_be32(&[0x00, 0x01, 0x00, 0x00], 0), 0x0001_0000);
            assert_eq!(manual_be32(&[0xEE, 0x00, 0x01, 0x00, 0x00], 1), 0x0001_0000);
            // high bit set: the shift must stay unsigned (no sign extension)
            assert_eq!(manual_be32(&[0x80, 0x00, 0x00, 0x00], 0), 0x8000_0000);
        }
        // ---------------------------------------------------------------
        // ManualTableProvider (parser)
        // ---------------------------------------------------------------
        #[test]
        fn manual_table_provider_rejects_short_input() {
            assert!(ManualTableProvider::new(&[], 0).is_none()); // empty
            assert!(ManualTableProvider::new(b"   ", 0).is_none()); // whitespace-only
            assert!(ManualTableProvider::new(b"  \t\n", 0).is_none());
            assert!(ManualTableProvider::new(&[0xFF, 0xFE, 0x00], 0).is_none()); // invalid utf8
            assert!(ManualTableProvider::new(&[0u8; 11], 0).is_none()); // one byte short
            assert!(ManualTableProvider::new(&[0u8; 12], 0).is_some()); // exact minimum
        }
        #[test]
        fn manual_table_provider_garbage_header_terminates() {
            // numTables reads back 0xFFFF but every record is past the end of the
            // buffer: the scan must break immediately instead of walking off it.
            let data = [0xFFu8; 12];
            let p = ManualTableProvider::new(&data, 0).expect("12 bytes form an offset table");
            assert_eq!(p.num, 0xFFFF);
            assert!(p.table_data(tag::HEAD).unwrap().is_none());
            assert!(!p.has_table(tag::GLYF));
            // table_tags always leads with the 0xFADE sentinel, then stops at the end
            assert_eq!(p.table_tags().unwrap(), vec![0x0000_FADE]);
        }
        #[test]
        fn manual_table_provider_ttc_index_out_of_range_is_none() {
            let mut data = b"ttcf".to_vec();
            data.extend_from_slice(&[0x00, 0x01, 0x00, 0x00]); // version 1.0
            data.extend_from_slice(&1u32.to_be_bytes()); // numFonts = 1
            data.extend_from_slice(&0u32.to_be_bytes()); // offset[0]
            assert!(ManualTableProvider::new(&data, 0).is_some());
            // index >= numFonts short-circuits *before* the `12 + font_index * 4`
            // arithmetic, so even usize::MAX cannot overflow it
            assert!(ManualTableProvider::new(&data, 1).is_none());
            assert!(ManualTableProvider::new(&data, 999_999).is_none());
            assert!(ManualTableProvider::new(&data, usize::MAX).is_none());
        }
        #[test]
        fn manual_table_provider_ttc_offset_past_end_is_none() {
            let mut data = b"ttcf".to_vec();
            data.extend_from_slice(&[0x00, 0x01, 0x00, 0x00]);
            data.extend_from_slice(&1u32.to_be_bytes());
            data.extend_from_slice(&u32::MAX.to_be_bytes()); // offset[0] = 4 GiB
            assert!(ManualTableProvider::new(&data, 0).is_none());
        }
        #[test]
        fn manual_table_provider_table_record_past_end_yields_none() {
            // One record whose (offset, length) points past the buffer: the
            // checked_add + bounds filter must turn it into None, not an OOB slice.
            let mut data = vec![0u8; 12 + 16];
            data[0..4].copy_from_slice(&0x0001_0000u32.to_be_bytes()); // sfnt version
            data[4..6].copy_from_slice(&1u16.to_be_bytes()); // numTables = 1
            data[12..16].copy_from_slice(&tag::HEAD.to_be_bytes()); // tag
            data[20..24].copy_from_slice(&u32::MAX.to_be_bytes()); // offset = 4 GiB
            data[24..28].copy_from_slice(&u32::MAX.to_be_bytes()); // length = 4 GiB
            let p = ManualTableProvider::new(&data, 0).unwrap();
            assert!(p.table_data(tag::HEAD).unwrap().is_none());
            assert!(!p.has_table(tag::HEAD));
        }
        #[test]
        fn manual_table_provider_one_megabyte_of_zeros_terminates() {
            let data = vec![0u8; 1_000_000];
            let p = ManualTableProvider::new(&data, 0).expect("zeros form a degenerate header");
            assert_eq!(p.num, 0); // numTables = 0: nothing to scan
            assert!(p.table_data(tag::HEAD).unwrap().is_none());
            assert_eq!(p.sfnt_version(), 0);
        }
        #[test]
        fn manual_table_provider_reads_a_real_font() {
            let p = ManualTableProvider::new(MOCK_MONO, 0).expect("a real TTF must produce a provider");
            assert_eq!(p.sfnt_version(), 0x0001_0000);
            assert_eq!(p.num, 13);
            assert!(p.has_table(tag::HEAD));
            assert!(p.has_table(tag::GLYF) && p.has_table(tag::LOCA));
            assert!(!p.has_table(tag::CFF)); // Azul Mock Mono is TrueType, not OpenType-PostScript
            let head = p.table_data(tag::HEAD).unwrap().expect("head must be present");
            // head.magicNumber sits at offset 12 and is fixed by the spec
            assert_eq!(manual_be32(head.as_ref(), 12), 0x5F0F_3CF5);
            let tags = p.table_tags().unwrap();
            assert_eq!(tags[0], 0x0000_FADE); // diagnostic sentinel
            assert_eq!(tags.len(), 14); // sentinel + 13 records
            assert!(tags.contains(&tag::GLYF));
        }
        // ---------------------------------------------------------------
        // monotonic_now_nanos
        // ---------------------------------------------------------------
        #[test]
        fn monotonic_now_nanos_never_goes_backwards() {
            let a = monotonic_now_nanos();
            let b = monotonic_now_nanos();
            assert!(b >= a, "clock went backwards: {a} -> {b}");
            // the `as u64` truncation cannot wrap in any realistic process lifetime
            assert!(b < 60 * 60 * 1_000_000_000);
        }
        // ---------------------------------------------------------------
        // GlyphOutlineCollector
        // ---------------------------------------------------------------
        #[test]
        fn glyph_outline_collector_new_is_empty() {
            assert!(GlyphOutlineCollector::new().into_outlines().is_empty());
        }
        #[test]
        fn glyph_outline_collector_flushes_an_unclosed_contour() {
            let mut c = GlyphOutlineCollector::new();
            c.move_to(Vector2F::new(1.0, 2.0));
            c.line_to(Vector2F::new(3.0, 4.0));
            // no close(): into_outlines must still flush the pending contour
            let outlines = c.into_outlines();
            assert_eq!(outlines.len(), 1);
            assert_eq!(outlines[0].operations.as_slice().len(), 2);
        }
        #[test]
        fn glyph_outline_collector_splits_contours_on_move_to() {
            let mut c = GlyphOutlineCollector::new();
            c.move_to(Vector2F::new(0.0, 0.0));
            c.line_to(Vector2F::new(10.0, 0.0));
            c.close();
            // close() already flushed, so this move_to must not emit an empty contour
            c.move_to(Vector2F::new(0.0, 0.0));
            c.quadratic_curve_to(Vector2F::new(1.0, 1.0), Vector2F::new(2.0, 2.0));
            c.cubic_curve_to(
                LineSegment2F::new(Vector2F::new(1.0, 1.0), Vector2F::new(2.0, 2.0)),
                Vector2F::new(3.0, 3.0),
            );
            let outlines = c.into_outlines();
            assert_eq!(outlines.len(), 2);
            assert_eq!(outlines[0].operations.as_slice().len(), 3); // move, line, close
            assert_eq!(outlines[1].operations.as_slice().len(), 3); // move, quad, cubic
        }
        #[test]
        fn glyph_outline_collector_saturates_nan_and_infinite_coordinates() {
            // allsorts hands us f32s; the `as i16` casts in the sink saturate
            // (NaN -> 0, ±inf -> i16::MAX/MIN) rather than wrapping or trapping.
            let mut c = GlyphOutlineCollector::new();
            c.move_to(Vector2F::new(f32::NAN, f32::INFINITY));
            c.line_to(Vector2F::new(f32::NEG_INFINITY, 1e30));
            let outlines = c.into_outlines();
            let ops = outlines[0].operations.as_slice();
            if let GlyphOutlineOperation::MoveTo(m) = &ops[0] {
                assert_eq!(m.x, 0); // NaN -> 0
                assert_eq!(m.y, i16::MAX); // +inf saturates
            } else {
                panic!("first op must be a MoveTo");
            }
            if let GlyphOutlineOperation::LineTo(l) = &ops[1] {
                assert_eq!(l.x, i16::MIN); // -inf saturates
                assert_eq!(l.y, i16::MAX); // 1e30 saturates
            } else {
                panic!("second op must be a LineTo");
            }
        }
        // ---------------------------------------------------------------
        // compute_outline_bbox
        // ---------------------------------------------------------------
        #[test]
        fn compute_outline_bbox_without_points_is_zero_not_the_sentinel_seed() {
            assert_eq!(compute_outline_bbox(&[]), (0, 0, 0, 0));
            let only_close = GlyphOutline {
                operations: vec![GlyphOutlineOperation::ClosePath].into(),
            };
            // ClosePath contributes no points: must not leak the
            // (i16::MAX, i16::MAX, i16::MIN, i16::MIN) accumulator seed
            assert_eq!(
                compute_outline_bbox(std::slice::from_ref(&only_close)),
                (0, 0, 0, 0)
            );
        }
        #[test]
        fn compute_outline_bbox_covers_control_points_and_i16_extremes() {
            let outline = GlyphOutline {
                operations: vec![
                    GlyphOutlineOperation::MoveTo(OutlineMoveTo {
                        x: i16::MIN,
                        y: i16::MAX,
                    }),
                    GlyphOutlineOperation::LineTo(OutlineLineTo { x: 0, y: 0 }),
                    GlyphOutlineOperation::QuadraticCurveTo(OutlineQuadTo {
                        ctrl_1_x: 5,
                        ctrl_1_y: -5,
                        end_x: 6,
                        end_y: -6,
                    }),
                    GlyphOutlineOperation::CubicCurveTo(OutlineCubicTo {
                        ctrl_1_x: i16::MAX,
                        ctrl_1_y: i16::MIN,
                        ctrl_2_x: 0,
                        ctrl_2_y: 0,
                        end_x: 1,
                        end_y: 1,
                    }),
                    GlyphOutlineOperation::ClosePath,
                ]
                .into(),
            };
            // control points participate in the bbox, and the i16 extremes must not wrap
            assert_eq!(
                compute_outline_bbox(std::slice::from_ref(&outline)),
                (i16::MIN, i16::MIN, i16::MAX, i16::MAX)
            );
        }
        #[test]
        fn compute_outline_bbox_spans_every_contour() {
            let a = GlyphOutline {
                operations: vec![GlyphOutlineOperation::MoveTo(OutlineMoveTo { x: -10, y: -10 })]
                    .into(),
            };
            let b = GlyphOutline {
                operations: vec![GlyphOutlineOperation::LineTo(OutlineLineTo { x: 20, y: 30 })]
                    .into(),
            };
            assert_eq!(compute_outline_bbox(&[a, b]), (-10, -10, 20, 30));
        }
        // ---------------------------------------------------------------
        // PdfFontMetrics
        // ---------------------------------------------------------------
        #[test]
        fn pdf_font_metrics_zero_never_divides_by_zero() {
            let z = PdfFontMetrics::zero();
            assert_eq!(z.units_per_em, 1000); // callers divide by this: never 0
            assert_eq!(z.ascender, 0);
            assert_eq!(z.descender, 0);
            assert_eq!(z.line_gap, 0);
            assert_eq!(z.advance_width_max, 0);
            assert_eq!(z.us_weight_class, 0);
            assert_eq!(z.y_strikeout_position, 0);
            assert_eq!(PdfFontMetrics::default(), z); // Default is the neutral element
            let copied = z; // Copy: the zero value is trivially duplicable
            assert_eq!(copied, z);
        }
        // ---------------------------------------------------------------
        // SubsetFont::subset_text
        // ---------------------------------------------------------------
        #[test]
        fn subset_text_with_an_empty_mapping_drops_everything() {
            let f = SubsetFont {
                bytes: Vec::new(),
                glyph_mapping: BTreeMap::new(),
            };
            assert_eq!(f.subset_text(""), "");
            assert_eq!(f.subset_text("hello"), "");
            // emoji + combining mark: multibyte input must not panic or slice mid-char
            assert_eq!(f.subset_text("\u{1F600}e\u{0301}"), "");
        }
        #[test]
        fn subset_text_remaps_chars_to_their_new_gids() {
            let mut m = BTreeMap::new();
            m.insert(40u16, (65u16, 'A')); // old gid 40 -> new gid 65 -> U+0041
            m.insert(41u16, (66u16, 'B'));
            let f = SubsetFont {
                bytes: Vec::new(),
                glyph_mapping: m,
            };
            assert_eq!(f.subset_text("AB"), "AB");
            assert_eq!(f.subset_text("BA"), "BA");
            assert_eq!(f.subset_text("A?B"), "AB"); // unmapped chars are dropped
        }
        #[test]
        fn subset_text_gid_boundaries() {
            let mut m = BTreeMap::new();
            m.insert(1u16, (0u16, 'x')); // new gid 0 -> U+0000
            m.insert(2u16, (0xD800u16, 'y')); // surrogate: char::from_u32 -> None
            m.insert(3u16, (u16::MAX, 'z')); // U+FFFF is a valid scalar value
            let f = SubsetFont {
                bytes: Vec::new(),
                glyph_mapping: m,
            };
            assert_eq!(f.subset_text("x"), "\u{0}");
            assert_eq!(f.subset_text("y"), ""); // a surrogate gid is silently dropped
            assert_eq!(f.subset_text("z"), "\u{FFFF}");
            assert_eq!(f.subset_text("xyz"), "\u{0}\u{FFFF}");
        }
        #[test]
        fn subset_text_long_input_terminates() {
            let mut m = BTreeMap::new();
            m.insert(7u16, (97u16, 'a'));
            let f = SubsetFont {
                bytes: Vec::new(),
                glyph_mapping: m,
            };
            assert_eq!(f.subset_text(&"a".repeat(100_000)).len(), 100_000);
        }
        // ---------------------------------------------------------------
        // FontParseWarning
        // ---------------------------------------------------------------
        #[test]
        fn font_parse_warning_constructors_preserve_severity_and_message() {
            let empty = FontParseWarning::info(String::new());
            assert_eq!(empty.severity, FontParseWarningSeverity::Info);
            assert!(empty.message.is_empty());
            let unicode = FontParseWarning::warning("\u{1F4A5} e\u{0301}\u{202E}".to_string());
            assert_eq!(unicode.severity, FontParseWarningSeverity::Warning);
            assert_eq!(unicode.message, "\u{1F4A5} e\u{0301}\u{202E}");
            let huge = FontParseWarning::error("x".repeat(1_000_000));
            assert_eq!(huge.severity, FontParseWarningSeverity::Error);
            assert_eq!(huge.message.len(), 1_000_000);
            // severity is part of the identity: same message, different level
            assert_ne!(
                FontParseWarning::error("boom".to_string()),
                FontParseWarning::warning("boom".to_string())
            );
        }
        // ---------------------------------------------------------------
        // MockFont (constructors)
        // ---------------------------------------------------------------
        #[test]
        fn mock_font_new_defaults_and_extreme_metrics() {
            let m = MockFont::new(plain_metrics());
            assert_eq!(m.space_width, Some(10)); // documented default
            assert!(m.glyph_advances.is_empty());
            assert!(m.glyph_sizes.is_empty());
            assert!(m.glyph_indices.is_empty());
            // metrics are stored verbatim: no normalisation, no panic on NaN/inf/0-upem
            let extreme = MockFont::new(LayoutFontMetrics {
                ascent: f32::INFINITY,
                descent: f32::NAN,
                line_gap: f32::MIN,
                units_per_em: 0,
                x_height: Some(f32::MAX),
                cap_height: None,
            });
            assert!(extreme.font_metrics.ascent.is_infinite());
            assert!(extreme.font_metrics.descent.is_nan());
            assert_eq!(extreme.font_metrics.units_per_em, 0);
            assert_eq!(extreme.space_width, Some(10));
        }
        #[test]
        fn mock_font_builders_store_boundary_values() {
            let m = MockFont::new(plain_metrics())
                .with_space_width(usize::MAX)
                .with_glyph_advance(0, 0)
                .with_glyph_advance(u16::MAX, u16::MAX)
                .with_glyph_size(u16::MAX, (i32::MIN, i32::MAX))
                .with_glyph_index(0, 0)
                .with_glyph_index(u32::MAX, u16::MAX); // not a scalar value: stored anyway
            assert_eq!(m.space_width, Some(usize::MAX));
            assert_eq!(m.glyph_advances.len(), 2);
            assert_eq!(m.glyph_advances.get(&u16::MAX), Some(&u16::MAX));
            assert_eq!(m.glyph_sizes.get(&u16::MAX), Some(&(i32::MIN, i32::MAX)));
            assert_eq!(m.glyph_indices.len(), 2);
            assert_eq!(m.glyph_indices.get(&u32::MAX), Some(&u16::MAX));
            // last write wins, and an overwrite must not grow the map
            let m = m.with_glyph_advance(u16::MAX, 7).with_space_width(0);
            assert_eq!(m.glyph_advances.get(&u16::MAX), Some(&7));
            assert_eq!(m.glyph_advances.len(), 2);
            assert_eq!(m.space_width, Some(0));
        }
        // ---------------------------------------------------------------
        // ParsedFont::from_bytes (parser)
        // ---------------------------------------------------------------
        #[test]
        fn from_bytes_rejects_malformed_input() {
            let cases: Vec<(&str, Vec<u8>)> = vec![
                ("empty", Vec::new()),
                ("whitespace_only", b"   \t\n".to_vec()),
                ("garbage", (0u8..=255).cycle().take(4096).collect()),
                ("invalid_utf8", vec![0xFF, 0xFE, 0x00]),
                ("header_only", MOCK_MONO[..12].to_vec()),
                ("truncated_font", MOCK_MONO[..64].to_vec()),
                ("half_a_font", MOCK_MONO[..MOCK_MONO.len() / 2].to_vec()),
                ("one_megabyte_of_nuls", vec![0u8; 1_000_000]),
                ("ttcf_junk", {
                    let mut v = b"ttcf".to_vec();
                    v.extend_from_slice(&[0xABu8; 1024].repeat(1000));
                    v
                }),
            ];
            for (name, bytes) in cases {
                let mut warnings = Vec::new();
                assert!(
                    ParsedFont::from_bytes(&bytes, 0, &mut warnings).is_none(),
                    "{name} must not parse into a font"
                );
            }
        }
        #[test]
        fn from_bytes_appends_a_warning_on_failure() {
            let mut warnings = Vec::new();
            assert!(ParsedFont::from_bytes(&[], 0, &mut warnings).is_none());
            assert!(!warnings.is_empty(), "a failed parse must explain itself");
            assert!(warnings
                .iter()
                .any(|w| w.severity == FontParseWarningSeverity::Error));
            // the caller's vec is appended to, never cleared
            let before = warnings.len();
            assert!(ParsedFont::from_bytes(&[0xFF; 3], 0, &mut warnings).is_none());
            assert!(warnings.len() > before);
        }
        #[test]
        fn from_bytes_parses_the_positive_control() {
            let font = parse_mock();
            assert_eq!(font.num_glyphs(), 96);
            assert_eq!(font.num_glyphs(), font.maxp_table.num_glyphs);
            assert_eq!(font.font_metrics.units_per_em, 1000);
            assert!(font.font_metrics.ascent > 0.0);
            assert_eq!(font.font_type, FontType::TrueType);
            assert_eq!(font.original_index, 0);
            assert_eq!(font.pdf_font_metrics.units_per_em, 1000);
            assert!(font.pdf_font_metrics.x_max > font.pdf_font_metrics.x_min);
            assert!(font.cmap_subtable.is_some());
            assert!(font.gsub_bytes.is_some() && font.gpos_bytes.is_some());
            assert!(font.hmtx_range.1 > 0, "hmtx must be located in the source");
            assert_eq!(font.vmtx_range, (0, 0), "Azul Mock Mono has no vertical metrics");
            assert!(!font.is_variable_font);
        }
        #[test]
        fn from_bytes_with_an_out_of_range_font_index_is_deterministic() {
            let baseline = parse_mock();
            let mut warnings = Vec::new();
            // Azul Mock Mono is a single face, not a .ttc: the manual provider ignores the index
            // rather than rejecting it. What must NOT happen is a panic or a
            // `12 + font_index * 4` overflow.
            if let Some(font) = ParsedFont::from_bytes(MOCK_MONO, usize::MAX, &mut warnings) {
                assert_eq!(font.num_glyphs(), baseline.num_glyphs());
                assert_eq!(font.original_index, usize::MAX);
                assert_ne!(font.hash, baseline.hash, "font_index feeds the identity hash");
            }
        }
        #[test]
        fn from_bytes_internal_deferred_flag_skips_the_eager_loca_glyf_load() {
            let mut warnings = Vec::new();
            let eager = ParsedFont::from_bytes_internal(MOCK_MONO, 0, &mut warnings, false)
                .expect("eager parse");
            assert!(matches!(eager.loca_glyf, LocaGlyfState::Loaded(Some(_))));
            let deferred = ParsedFont::from_bytes_internal(MOCK_MONO, 0, &mut warnings, true)
                .expect("deferred parse");
            // deferring leaves the slot empty for from_bytes_shared to overwrite
            assert!(matches!(deferred.loca_glyf, LocaGlyfState::Loaded(None)));
            assert_eq!(eager.num_glyphs(), deferred.num_glyphs());
            assert_eq!(eager.hash, deferred.hash);
        }
        // ---------------------------------------------------------------
        // cmap lookups (numeric / predicate)
        // ---------------------------------------------------------------
        #[test]
        fn lookup_glyph_index_handles_codepoint_extremes() {
            let font = parse_mock();
            assert!(font.lookup_glyph_index('A' as u32).is_some());
            // 0, the last valid scalar value, and values beyond the Unicode range must
            // all resolve deterministically without panicking
            for cp in [0u32, 0x0010_FFFF, 0x0011_0000, u32::MAX / 2, u32::MAX] {
                let first = font.lookup_glyph_index(cp);
                assert_eq!(first, font.lookup_glyph_index(cp), "cp {cp} must be stable");
                // has_glyph is defined as lookup_glyph_index().is_some()
                assert_eq!(first.is_some(), font.has_glyph(cp));
            }
            assert!(!font.has_glyph(0x0010_FFFF));
            assert!(!font.has_glyph(u32::MAX));
        }
        // ---------------------------------------------------------------
        // advances (numeric)
        // ---------------------------------------------------------------
        #[test]
        fn get_horizontal_advance_saturates_out_of_range_gids() {
            let font = parse_mock();
            let gid_a = font.lookup_glyph_index('A' as u32).expect("'A' is in Azul Mock Mono");
            assert!(font.get_horizontal_advance(gid_a) > 0);
            // out-of-range gid: allsorts short-circuits to 0 rather than erroring
            assert!(font.num_glyphs() < u16::MAX);
            assert_eq!(font.get_horizontal_advance(font.num_glyphs()), 0);
            assert_eq!(font.get_horizontal_advance(u16::MAX), 0);
        }
        #[test]
        fn get_glyph_width_internal_matches_hmtx_and_never_panics() {
            let font = parse_mock();
            let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
            assert_eq!(
                font.get_glyph_width_internal(gid_a),
                Some(usize::from(font.get_horizontal_advance(gid_a)))
            );
            // an out-of-range gid yields Some(0) (allsorts returns Ok(0)), never None/panic
            assert_eq!(font.get_glyph_width_internal(u16::MAX), Some(0));
            assert_eq!(font.get_glyph_width_internal(font.num_glyphs()), Some(0));
        }
        #[test]
        fn space_width_is_cached_at_parse_time() {
            let font = parse_mock();
            let space_gid = font
                .lookup_glyph_index(' ' as u32)
                .expect("Azul Mock Mono has a space glyph");
            let live = usize::from(font.get_horizontal_advance(space_gid));
            assert!(live > 0, "the live hmtx advance for space must be non-zero");
            let cached = font
                .get_space_width()
                .expect("space_width is populated at parse time");
            // NOTE: `space_width` is computed inside `from_bytes_internal`, *before* the
            // source bytes are attached, so hmtx is unreadable at that point and the
            // cached value can legitimately read back 0 (see the comment there).
            assert!(
                cached == 0 || cached == live,
                "space_width must be 0 (stale) or the hmtx advance; got {cached} vs {live}"
            );
            assert_eq!(font.get_space_width(), font.space_width);
        }
        #[test]
        fn get_hinted_advance_px_rejects_degenerate_inputs() {
            let font = parse_mock();
            let gid = font.lookup_glyph_index('A' as u32).unwrap();
            // ppem 0 would divide by zero when computing the scale
            assert!(font.get_hinted_advance_px(gid, 0).is_none());
            // out-of-range gid is gated by get_or_decode_glyph
            assert!(font.get_hinted_advance_px(u16::MAX, 16).is_none());
            assert!(font.get_hinted_advance_px(font.num_glyphs(), 16).is_none());
            // extreme ppem must not overflow the F26Dot6 fixed-point math; whatever
            // comes back is a finite, non-negative, whole-pixel value
            for ppem in [1u16, 16, 255, 4096, u16::MAX] {
                if let Some(px) = font.get_hinted_advance_px(gid, ppem) {
                    assert!(px.is_finite(), "ppem {ppem} produced {px}");
                    assert!(px >= 0.0, "ppem {ppem} produced {px}");
                    assert!(
                        (px - px.trunc()).abs() < f32::EPSILON,
                        "the advance is rounded to the whole-pixel grid, got {px}"
                    );
                }
            }
        }
        // ---------------------------------------------------------------
        // glyph decode + lazy cache
        // ---------------------------------------------------------------
        #[test]
        fn get_or_decode_glyph_bounds_and_cache_identity() {
            let font = parse_mock();
            assert!(font.num_glyphs() > 1);
            // gid >= num_glyphs is refused before any decode is attempted
            assert!(font.get_or_decode_glyph(font.num_glyphs()).is_none());
            assert!(font.get_or_decode_glyph(u16::MAX).is_none());
            let a = font.get_or_decode_glyph(0).expect(".notdef must decode");
            let b = font.get_or_decode_glyph(0).expect("the cache must hand it back");
            assert!(Arc::ptr_eq(&a, &b), "a second call must hit the cache");
            let snap = font.glyph_cache_snapshot();
            assert!(Arc::ptr_eq(snap.get(&0).expect("gid 0 is cached"), &a));
            assert!(!snap.contains_key(&font.num_glyphs()));
        }
        #[test]
        fn get_or_decode_glyph_stamps_the_lru_clock() {
            let font = parse_mock();
            assert_eq!(font.last_used_nanos(), 0, "an untouched face reports 0");
            let _ = font.get_or_decode_glyph(0);
            let t = font.last_used_nanos();
            assert!(t > 0, "decoding must stamp last_used");
            let _ = font.get_or_decode_glyph(1);
            assert!(font.last_used_nanos() >= t, "the stamp must not go backwards");
        }
        #[test]
        fn prime_glyph_cache_decodes_every_glyph_and_is_idempotent() {
            let mut font = parse_mock();
            // the lazy cache starts empty (the space stub is skipped while the source
            // bytes are still unattached)
            assert!(font.glyph_cache_snapshot().is_empty());
            font.prime_glyph_cache();
            let snap = font.glyph_cache_snapshot();
            assert_eq!(snap.len(), usize::from(font.num_glyphs()));
            assert!(snap.contains_key(&0));
            assert!(!snap.contains_key(&font.num_glyphs()), "never decodes past the end");
            let mut seen = 0usize;
            let mut max_gid = 0u16;
            font.for_each_decoded_glyph(|gid, _| {
                seen += 1;
                max_gid = max_gid.max(gid);
            });
            assert_eq!(seen, snap.len());
            assert_eq!(max_gid, font.num_glyphs() - 1);
            font.prime_glyph_cache(); // priming twice must not duplicate or grow
            assert_eq!(font.glyph_cache_snapshot().len(), snap.len());
        }
        #[test]
        fn decode_glyph_inner_seeds_the_bbox_from_the_advance() {
            let font = parse_mock();
            let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
            let g = font.decode_glyph_inner(gid_a);
            assert_eq!(g.horz_advance, font.get_horizontal_advance(gid_a));
            assert!(!g.outline.is_empty(), "'A' has a glyf outline");
            assert!(g.bounding_box.max_x > g.bounding_box.min_x);
            assert!(g.bounding_box.max_y > g.bounding_box.min_y);
            assert!(g.raw_points.is_some() && g.raw_on_curve.is_some());
            assert_eq!(
                g.raw_points.as_ref().map(Vec::len),
                g.raw_on_curve.as_ref().map(Vec::len),
                "one on-curve flag per raw point"
            );
            // gid 0 (.notdef) decodes too, and the bbox stays inside i16
            let notdef = font.decode_glyph_inner(0);
            assert!(notdef.bounding_box.max_x >= notdef.bounding_box.min_x);
        }
        #[test]
        fn get_glyph_bbox_size_bounds() {
            let font = parse_mock();
            let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
            let (w, h) = font.get_glyph_bbox_size(gid_a).expect("'A' has a bbox");
            assert!(w > 0 && h > 0);
            assert_eq!(w, i32::from(font.get_horizontal_advance(gid_a)));
            // out-of-range gid -> None (not a zero-sized box)
            assert!(font.get_glyph_bbox_size(u16::MAX).is_none());
            assert!(font.get_glyph_bbox_size(font.num_glyphs()).is_none());
        }
        #[test]
        fn get_vertical_metrics_without_vmtx_is_none() {
            let font = parse_mock();
            // Azul Mock Mono has neither vhea nor vmtx
            assert!(font.get_vertical_metrics(0).is_none());
            assert!(font.get_vertical_metrics(u16::MAX).is_none());
            // vhea present but a zero-length vmtx range must still bail out
            let mut synthetic = synthetic_font(4, None);
            synthetic.vhea_table = Some(plain_hhea());
            assert_eq!(synthetic.vmtx_range.1, 0);
            assert!(synthetic.get_vertical_metrics(0).is_none());
        }
        // ---------------------------------------------------------------
        // lazy loca/glyf: from_bytes_shared, eviction
        // ---------------------------------------------------------------
        #[test]
        fn from_bytes_shared_defers_loca_glyf_and_can_evict() {
            let font = mock_shared();
            assert!(matches!(font.loca_glyf, LocaGlyfState::Deferred { .. }));
            assert!(font.source_bytes_for_subset().is_some());
            // nothing is loaded until the first decode, so there is nothing to evict yet
            assert!(!font.evict_loca_glyf());
            let g1 = font.get_or_decode_glyph(1).expect("gid 1 must decode");
            assert!(font.evict_loca_glyf(), "a loaded Deferred slot is evictable");
            assert!(!font.evict_loca_glyf(), "evicting twice is a no-op");
            // after eviction the face still decodes: it re-parses from the retained bytes
            let g2 = font.get_or_decode_glyph(2).expect("gid 2 decodes after eviction");
            assert_eq!(g2.horz_advance, font.get_horizontal_advance(2));
            // and already-decoded glyphs still come from the glyph cache
            assert!(Arc::ptr_eq(&g1, &font.get_or_decode_glyph(1).unwrap()));
        }
        #[test]
        fn eager_faces_are_not_evictable() {
            let font = parse_mock();
            assert!(matches!(font.loca_glyf, LocaGlyfState::Loaded(Some(_))));
            let _ = font.get_or_decode_glyph(0);
            // Loaded faces have no retained source bytes to re-parse from
            assert!(!font.evict_loca_glyf());
            assert!(font.resolve_loca_glyf().is_some());
        }
        #[test]
        fn eager_and_deferred_paths_decode_identical_glyphs() {
            let eager = parse_mock();
            let lazy = mock_shared();
            assert_eq!(eager.num_glyphs(), lazy.num_glyphs());
            assert_eq!(eager.hash, lazy.hash); // same bytes + index -> same identity
            assert_eq!(eager, lazy); // PartialEq is hash-based
            let gid = eager.lookup_glyph_index('A' as u32).unwrap();
            assert_eq!(lazy.lookup_glyph_index('A' as u32), Some(gid));
            let a = eager.get_or_decode_glyph(gid).unwrap();
            let b = lazy.get_or_decode_glyph(gid).unwrap();
            assert_eq!(a.horz_advance, b.horz_advance);
            assert_eq!(a.outline.len(), b.outline.len());
            assert_eq!(a.bounding_box.min_x, b.bounding_box.min_x);
            assert_eq!(a.bounding_box.min_y, b.bounding_box.min_y);
            assert_eq!(a.bounding_box.max_x, b.bounding_box.max_x);
            assert_eq!(a.bounding_box.max_y, b.bounding_box.max_y);
        }
        #[test]
        fn with_source_bytes_shares_the_arc() {
            let font = parse_mock();
            // from_bytes retains an owned copy, so subsetting works without an
            // explicit with_source_bytes call
            let auto = font
                .source_bytes_for_subset()
                .expect("from_bytes retains the source bytes");
            assert_eq!(auto.as_slice(), MOCK_MONO);
            let arc = Arc::new(rust_fontconfig::FontBytes::Owned(Arc::from(MOCK_MONO.to_vec())));
            let font = font.with_source_bytes(Arc::clone(&arc));
            let got = font.source_bytes_for_subset().unwrap();
            assert!(Arc::ptr_eq(&got, &arc), "attached bytes are shared, not copied");
        }
        #[test]
        fn clone_shares_the_glyph_cache_and_drops_hinting() {
            let font = parse_mock();
            let g = font.get_or_decode_glyph(0).unwrap();
            let clone = font.clone();
            assert_eq!(clone, font);
            // the decode cache is Arc-shared, so the clone sees the decoded glyph...
            assert!(Arc::ptr_eq(&clone.get_or_decode_glyph(0).unwrap(), &g));
            // ...and decodes through the clone are visible from the original
            let _ = clone.get_or_decode_glyph(1);
            assert!(font.glyph_cache_snapshot().contains_key(&1));
            // HintInstance is not Clone: it is deliberately dropped
            assert!(clone.hint_instance.is_none());
        }
        #[test]
        fn gsub_and_gpos_are_memoised() {
            let font = parse_mock();
            assert!(font.gsub_bytes.is_some(), "Azul Mock Mono ships a GSUB table");
            assert!(font.gpos_bytes.is_some(), "Azul Mock Mono ships a GPOS table");
            match (font.gsub(), font.gsub()) {
                (Some(a), Some(b)) => assert!(Arc::ptr_eq(a, b), "gsub() must be memoised"),
                (None, None) => {}
                _ => panic!("gsub() must be deterministic across calls"),
            }
            match (font.gpos(), font.gpos()) {
                (Some(a), Some(b)) => assert!(Arc::ptr_eq(a, b), "gpos() must be memoised"),
                (None, None) => {}
                _ => panic!("gpos() must be deterministic across calls"),
            }
        }
        // ---------------------------------------------------------------
        // to_bytes / subset (round-trip)
        // ---------------------------------------------------------------
        #[test]
        fn to_bytes_round_trips_through_from_bytes() {
            let font = parse_mock();
            let rebuilt = font
                .to_bytes(None)
                .expect("from_bytes retains source bytes, so to_bytes must succeed");
            assert!(rebuilt.len() > 12);
            let mut warnings = Vec::new();
            let re = ParsedFont::from_bytes(&rebuilt, 0, &mut warnings)
                .expect("a font emitted by to_bytes must parse back");
            assert_eq!(re.num_glyphs(), font.num_glyphs());
            assert_eq!(re.font_metrics.units_per_em, font.font_metrics.units_per_em);
            assert_eq!(re.pdf_font_metrics.x_min, font.pdf_font_metrics.x_min);
            assert_eq!(re.pdf_font_metrics.y_max, font.pdf_font_metrics.y_max);
            let gid = font.lookup_glyph_index('A' as u32).unwrap();
            assert_eq!(
                re.lookup_glyph_index('A' as u32),
                Some(gid),
                "the cmap must survive the round-trip"
            );
            assert_eq!(
                re.get_horizontal_advance(gid),
                font.get_horizontal_advance(gid),
                "hmtx must survive the round-trip"
            );
        }
        #[test]
        fn to_bytes_with_an_absent_tag_errors_instead_of_panicking() {
            let font = parse_mock();
            // Azul Mock Mono has no CFF table: asking for it must surface an Err string
            assert!(font.to_bytes(Some(&[tag::CFF])).is_err());
            // an empty tag list still reads head+maxp internally: it must return, not panic
            drop(font.to_bytes(Some(&[])));
            // duplicate tags must not double-insert into the builder and blow up
            drop(font.to_bytes(Some(&[tag::HEAD, tag::HEAD, tag::MAXP])));
        }
        #[test]
        fn subset_maps_glyph_ids_and_produces_a_parseable_font() {
            let font = parse_mock();
            let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
            let gid_b = font.lookup_glyph_index('B' as u32).unwrap();
            let (bytes, mapping) = font
                .subset(&[(0, '\0'), (gid_a, 'A'), (gid_b, 'B')], CmapTarget::Unrestricted)
                .expect("subsetting a TrueType font must succeed");
            // the mapping is positional: original gid -> (index in the request, char)
            assert_eq!(mapping.len(), 3);
            assert_eq!(mapping.get(&0), Some(&(0, '\0')));
            assert_eq!(mapping.get(&gid_a), Some(&(1, 'A')));
            assert_eq!(mapping.get(&gid_b), Some(&(2, 'B')));
            let mut warnings = Vec::new();
            let sub =
                ParsedFont::from_bytes(&bytes, 0, &mut warnings).expect("the subset must re-parse");
            assert!(sub.num_glyphs() >= 3);
            assert!(sub.num_glyphs() <= font.num_glyphs());
            assert_eq!(
                sub.get_horizontal_advance(1),
                font.get_horizontal_advance(gid_a),
                "the remapped 'A' keeps its advance"
            );
        }
        #[test]
        fn subset_edge_inputs_do_not_panic() {
            let font = parse_mock();
            // an empty glyph list may be accepted or rejected; it must not panic
            if let Ok((_, mapping)) = font.subset(&[], CmapTarget::Unrestricted) {
                assert!(mapping.is_empty());
            }
            // an out-of-range gid must come back as a Result, never an OOB read
            drop(font.subset(&[(0, '\0'), (u16::MAX, 'x')], CmapTarget::Unrestricted));
            // duplicate gids collapse in the returned map: the later entry wins
            let gid_a = font.lookup_glyph_index('A' as u32).unwrap();
            if let Ok((_, mapping)) = font.subset(
                &[(0, '\0'), (gid_a, 'a'), (gid_a, 'b')],
                CmapTarget::Unrestricted,
            ) {
                assert_eq!(mapping.len(), 2);
                assert_eq!(mapping.get(&gid_a), Some(&(2, 'b')));
            }
        }
        // ---------------------------------------------------------------
        // empty / extreme instances (getters, predicates)
        // ---------------------------------------------------------------
        #[test]
        fn every_getter_survives_an_empty_font() {
            let font = synthetic_font(0, None);
            assert_eq!(font.num_glyphs(), 0);
            assert!(font.get_or_decode_glyph(0).is_none()); // 0 >= num_glyphs
            assert!(font.get_or_decode_glyph(u16::MAX).is_none());
            assert!(font.get_glyph_bbox_size(0).is_none());
            assert!(font.lookup_glyph_index('A' as u32).is_none()); // no cmap
            assert!(!font.has_glyph('A' as u32));
            assert!(!font.has_glyph(0));
            assert_eq!(font.get_horizontal_advance(0), 0);
            assert_eq!(font.get_horizontal_advance(u16::MAX), 0);
            assert_eq!(font.get_glyph_width_internal(0), Some(0));
            assert!(font.get_vertical_metrics(0).is_none());
            assert!(font.get_space_width().is_none());
            assert!(font.get_space_width_internal().is_none());
            assert!(font.glyph_cache_snapshot().is_empty());
            assert!(font.gsub().is_none() && font.gpos().is_none());
            assert!(font.resolve_loca_glyf().is_none());
            assert!(font.source_bytes_for_subset().is_none());
            assert_eq!(font.last_used_nanos(), 0);
            assert!(!font.evict_loca_glyf());
            assert!(font.hmtx_bytes().is_empty());
            assert!(font.vmtx_bytes().is_empty());
            assert!(font.get_hinted_advance_px(0, 16).is_none());
            font.for_each_decoded_glyph(|_, _| panic!("nothing has been decoded"));
            // without source bytes, the PDF paths must report an error, not panic
            assert!(font.to_bytes(None).is_err());
            assert!(font.subset(&[], CmapTarget::Unrestricted).is_err());
        }
        #[test]
        fn hmtx_bytes_without_source_bytes_is_empty_not_a_panic() {
            let mut font = synthetic_font(4, None);
            // ranges pointing into bytes we never retained must degrade to an empty
            // slice rather than unwrapping a None
            font.hmtx_range = (16, 32);
            font.vmtx_range = (48, 64);
            assert!(font.hmtx_bytes().is_empty());
            assert!(font.vmtx_bytes().is_empty());
            assert_eq!(font.get_horizontal_advance(0), 0);
        }
        #[test]
        fn hmtx_bytes_slices_the_retained_source() {
            let mut font = synthetic_font(2, None);
            let raw: Vec<u8> = (0u8..100).collect();
            font.original_bytes = Some(Arc::new(rust_fontconfig::FontBytes::Owned(Arc::from(raw))));
            font.hmtx_range = (10, 4);
            font.vmtx_range = (0, 0);
            assert_eq!(font.hmtx_bytes(), [10u8, 11, 12, 13].as_slice());
            assert!(font.vmtx_bytes().is_empty()); // a zero-length range short-circuits
        }
        #[test]
        fn mock_backed_font_overrides_advances_and_space_width() {
            let mock = MockFont::new(plain_metrics())
                .with_space_width(42)
                .with_glyph_advance(1, 500);
            let font = synthetic_font(4, Some(Box::new(mock)));
            assert_eq!(font.get_horizontal_advance(1), 500); // the mock wins over hmtx
            assert_eq!(font.get_horizontal_advance(3), 0); // unmapped gid -> 0, no panic
            assert_eq!(font.get_horizontal_advance(u16::MAX), 0);
            assert_eq!(font.get_space_width_internal(), Some(42));
            // the decoded record inherits the mock advance and, with no outline,
            // seeds its bbox from it
            let g = font.get_or_decode_glyph(1).expect("gid 1 < num_glyphs");
            assert_eq!(g.horz_advance, 500);
            assert_eq!(g.bounding_box.max_x, 500);
            assert!(g.outline.is_empty());
            assert_eq!(font.get_glyph_bbox_size(1), Some((500, 0)));
        }
        #[test]
        fn get_font_metrics_normalises_the_descent_sign() {
            let mut font = synthetic_font(1, None);
            font.font_metrics.descent = -200.0;
            assert_eq!(font.get_font_metrics().descent, 200.0);
            font.font_metrics.descent = 200.0;
            assert_eq!(font.get_font_metrics().descent, 200.0);
            // -0.0 is not > 0.0, so it takes the negation branch and comes out +0.0
            font.font_metrics.descent = -0.0;
            assert!(font.get_font_metrics().descent.is_sign_positive());
            font.font_metrics.descent = f32::NEG_INFINITY;
            assert_eq!(font.get_font_metrics().descent, f32::INFINITY);
            // NaN compares false against 0.0, so it is negated — and stays NaN
            font.font_metrics.descent = f32::NAN;
            assert!(font.get_font_metrics().descent.is_nan());
            // every other field passes through untouched
            font.font_metrics.descent = -10.0;
            font.font_metrics.ascent = f32::MAX;
            font.font_metrics.line_gap = -1.0;
            let m = font.get_font_metrics();
            assert_eq!(m.ascent, f32::MAX);
            assert_eq!(m.line_gap, -1.0);
            assert_eq!(m.units_per_em, font.font_metrics.units_per_em);
        }
        #[test]
        fn real_font_metrics_have_a_non_negative_descent() {
            let font = parse_mock();
            let m = font.get_font_metrics();
            assert!(m.descent >= 0.0, "get_font_metrics flips the descent sign");
            assert_eq!(m.descent, font.font_metrics.descent.abs());
            assert_eq!(m.ascent, font.font_metrics.ascent);
            assert_eq!(m.units_per_em, 1000);
        }
        // ---------------------------------------------------------------
        // reverse glyph cache
        // ---------------------------------------------------------------
        #[test]
        fn reverse_glyph_cache_round_trip_and_boundaries() {
            let mut font = synthetic_font(2, None);
            assert!(font.get_glyph_cluster_text(0).is_none());
            assert!(font.get_glyph_primary_char(0).is_none());
            font.cache_glyph_mapping(0, ""); // empty cluster
            font.cache_glyph_mapping(u16::MAX, "fi"); // ligature at the gid boundary
            font.cache_glyph_mapping(7, "\u{1F468}\u{200D}\u{1F469}"); // ZWJ cluster
            assert_eq!(font.get_glyph_cluster_text(0), Some(""));
            assert_eq!(font.get_glyph_primary_char(0), None); // no first char in ""
            assert_eq!(font.get_glyph_cluster_text(u16::MAX), Some("fi"));
            assert_eq!(font.get_glyph_primary_char(u16::MAX), Some('f'));
            assert_eq!(font.get_glyph_primary_char(7), Some('\u{1F468}'));
            assert!(font.get_glyph_cluster_text(1).is_none()); // never written
            font.cache_glyph_mapping(u16::MAX, "ffi"); // last write wins
            assert_eq!(font.get_glyph_cluster_text(u16::MAX), Some("ffi"));
            // clear_glyph_cache drops ONLY the reverse map, not the decoded outlines
            let decoded = font.get_or_decode_glyph(0).expect("gid 0 decodes");
            font.clear_glyph_cache();
            assert!(font.get_glyph_cluster_text(0).is_none());
            assert!(font.get_glyph_cluster_text(u16::MAX).is_none());
            assert!(font.get_glyph_primary_char(7).is_none());
            assert!(Arc::ptr_eq(
                font.glyph_cache_snapshot().get(&0).expect("outline cache is untouched"),
                &decoded
            ));
            font.clear_glyph_cache(); // idempotent
        }
        // ---------------------------------------------------------------
        // loading / cpurender
        // ---------------------------------------------------------------
        #[test]
        fn build_font_cache_does_not_panic() {
            // Smoke: the system font scan must complete. An empty cache is legitimate
            // (a headless image may ship no fonts), so only the call itself is asserted.
            let _cache = crate::font::loading::build_font_cache();
        }
        #[cfg(feature = "cpurender")]
        #[test]
        fn build_glyph_path_needs_at_least_one_operation() {
            let empty = OwnedGlyph {
                bounding_box: OwnedGlyphBoundingBox {
                    max_x: 0,
                    max_y: 0,
                    min_x: 0,
                    min_y: 0,
                },
                horz_advance: 500,
                outline: Vec::new(),
                phantom_points: None,
                raw_points: None,
                raw_on_curve: None,
                raw_contour_ends: None,
                instructions: None,
            };
            // a space-like glyph has no ops -> None (the caller must skip it)
            assert!(build_glyph_path(&empty).is_none());
            // an outline whose only contour is empty is still "no ops"
            let hollow = OwnedGlyph {
                outline: vec![GlyphOutline {
                    operations: Vec::<GlyphOutlineOperation>::new().into(),
                }],
                ..empty.clone()
            };
            assert!(build_glyph_path(&hollow).is_none());
            // every op kind, at the i16 extremes, must survive the f64 conversion
            let full = OwnedGlyph {
                outline: vec![GlyphOutline {
                    operations: vec![
                        GlyphOutlineOperation::MoveTo(OutlineMoveTo {
                            x: i16::MIN,
                            y: i16::MAX,
                        }),
                        GlyphOutlineOperation::LineTo(OutlineLineTo {
                            x: i16::MAX,
                            y: i16::MIN,
                        }),
                        GlyphOutlineOperation::QuadraticCurveTo(OutlineQuadTo {
                            ctrl_1_x: 0,
                            ctrl_1_y: 0,
                            end_x: 1,
                            end_y: 1,
                        }),
                        GlyphOutlineOperation::CubicCurveTo(OutlineCubicTo {
                            ctrl_1_x: 0,
                            ctrl_1_y: 0,
                            ctrl_2_x: 0,
                            ctrl_2_y: 0,
                            end_x: 2,
                            end_y: 2,
                        }),
                        GlyphOutlineOperation::ClosePath,
                    ]
                    .into(),
                }],
                ..empty
            };
            assert!(build_glyph_path(&full).is_some());
        }
    }
}