1
//! Default / concrete implementations of the text3 trait abstractions.
2
//!
3
//! This module bridges the generic text3 layout engine and the concrete
4
//! `FontRef` / `ParsedFont` types.  It provides:
5
//!
6
//! - `ParsedFontTrait` implementation for `FontRef`
7
//! - Font loading via `PathLoader`
8
//! - The core `shape_text_internal` shaping function
9

            
10
use std::{path::Path, sync::Arc};
11

            
12
use allsorts::{
13
    gpos,
14
    gsub::{self, Feature, FeatureInfo, FeatureMask, FeatureMaskExt},
15
};
16
use azul_core::geom::LogicalSize;
17
use azul_css::props::basic::FontRef;
18

            
19
use crate::{
20
    font::parsed::ParsedFont,
21
    text3::{
22
        cache::{
23
            BidiDirection, BidiLevel, FontManager, FontSelector, FontVariantCaps,
24
            FontVariantLigatures, FontVariantNumeric, Glyph, GlyphOrientation, GlyphSource,
25
            LayoutError, LayoutFontMetrics, ParsedFontTrait, Point, ShallowClone, StyleProperties,
26
            TextCombineUpright, TextDecoration, TextOrientation, VerticalMetrics, WritingMode,
27
        },
28
        script::Script,
29
    },
30
};
31

            
32
/// Creates a `FontRef` from font bytes by parsing them into a `ParsedFont`.
33
///
34
/// This is a bridge function that:
35
///
36
/// 1. Parses the bytes into a `ParsedFont`
37
/// 2. Wraps it in a `FontRef` with proper reference counting
38
///
39
/// # Arguments
40
///
41
/// - `font_bytes` - The raw font file data
42
/// - `font_index` - Index of the font in a font collection (0 for single fonts)
43
/// - `parse_outlines` - Whether to parse glyph outlines (expensive, usually false for layout)
44
#[must_use]
45
23
pub fn font_ref_from_bytes(
46
23
    font_bytes: &[u8],
47
23
    font_index: usize,
48
23
    parse_outlines: bool,
49
23
) -> Option<FontRef> {
50
    // Parse the font bytes into ParsedFont
51
23
    let mut warnings = Vec::new();
52
23
    let parsed_font = ParsedFont::from_bytes(font_bytes, font_index, &mut warnings)?;
53

            
54
8
    Some(crate::parsed_font_to_font_ref(parsed_font))
55
23
}
56

            
57
/// A `FontLoader` that parses font data from a byte slice.
58
///
59
/// It is designed to be used in conjunction with a mechanism that reads font files
60
/// from paths into memory. This loader simply handles the parsing aspect.
61
#[derive(Copy, Debug, Default, Clone)]
62
pub struct PathLoader;
63

            
64
impl PathLoader {
65
    /// Creates a new `PathLoader`.
66
    #[must_use]
67
15540
    pub const fn new() -> Self {
68
15540
        Self
69
15540
    }
70

            
71
    /// Read a font from disk and parse via the lazy-LocaGlyf path.
72
    /// Convenience wrapper for callers that have a path but no
73
    /// `Arc<FontBytes>` yet — uses a heap read (`Owned`) since a
74
    /// loose path won't go through the fontconfig dedup cache.
75
10
    pub(crate) fn load_from_path(
76
10
        self,
77
10
        path: &Path,
78
10
        font_index: usize,
79
10
    ) -> Result<FontRef, LayoutError> {
80
10
        let font_bytes = std::fs::read(path).map_err(|_| {
81
5
            LayoutError::FontNotFound(FontSelector {
82
5
                family: path.to_string_lossy().into_owned(),
83
5
                weight: rust_fontconfig::FcWeight::Normal,
84
5
                style: crate::text3::cache::FontStyle::Normal,
85
5
                unicode_ranges: Vec::new(),
86
5
            })
87
5
        })?;
88
5
        let arc_owned = Arc::<[u8]>::from(font_bytes);
89
5
        let bytes = Arc::new(rust_fontconfig::FontBytes::Owned(arc_owned));
90
5
        self.load_font_shared(bytes, font_index)
91
10
    }
92

            
93
    /// Lazy-friendly loader: takes an `Arc<FontBytes>` (typically
94
    /// from [`rust_fontconfig::FcFontCache::get_font_bytes`]) and
95
    /// uses the [`ParsedFont::from_bytes_shared`] constructor so
96
    /// `LocaGlyf::load` is deferred until the first glyph decode.
97
    ///
98
    /// This is the only loader on the production path —
99
    /// `load_fonts_from_disk` calls this via the closure passed
100
    /// into `FontManager::load_missing_for_chains`. Fonts that
101
    /// never get rasterized (common — every face of a `.ttc` gets a
102
    /// `FontId`, but pages only hit a couple of them) skip their
103
    /// per-face loca+glyf materialisation entirely; with
104
    /// `FontBytes::Mmapped` the unread pages also never count
105
    /// toward RSS.
106
    /// # Errors
107
    ///
108
    /// Returns a `LayoutError` if the font cannot be loaded.
109
21514
    pub fn load_font_shared(
110
21514
        &self,
111
21514
        font_bytes: Arc<rust_fontconfig::FontBytes>,
112
21514
        font_index: usize,
113
21514
    ) -> Result<FontRef, LayoutError> {
114
21514
        let mut warnings = Vec::new();
115
21514
        let parsed_font = ParsedFont::from_bytes_shared(font_bytes, font_index, &mut warnings)
116
21514
            .ok_or_else(|| {
117
6
                LayoutError::ShapingError("Failed to parse font with allsorts".to_string())
118
6
            })?;
119
21508
        Ok(crate::parsed_font_to_font_ref(parsed_font))
120
21514
    }
121
}
122

            
123
impl FontManager<FontRef> {
124
    /// Evict the cached `LocaGlyf` for every face that hasn't had a
125
    /// `get_or_decode_glyph` call within the last `idle` duration.
126
    /// Only `LocaGlyfState::Deferred` faces (the production lazy
127
    /// path) can be evicted — they keep their source `Arc<[u8]>` so
128
    /// the next glyph access re-parses cheaply. `LocaGlyfState::Loaded`
129
    /// faces from the eager path stay put.
130
    ///
131
    /// Returns the number of faces evicted. Embedders can call this
132
    /// from a memory-pressure hook or on a timer; servo-shot
133
    /// exposes it via `--azul-evict-after-each` for measurement.
134
    #[allow(clippy::cast_possible_truncation)] // bounded layout/render numeric cast
135
    #[must_use]
136
8
    pub fn evict_unused(&self, idle: std::time::Duration) -> usize {
137
        use crate::font::parsed::ParsedFont;
138
8
        let Ok(parsed) = self.parsed_fonts.lock() else {
139
            return 0;
140
        };
141
        // We compare against the same monotonic clock the font's
142
        // `last_used` is sampled from. `last_used == 0` means
143
        // "never touched" -> eligible. Otherwise we only evict if
144
        // `now_nanos - last_used >= idle.as_nanos()`.
145
8
        let cutoff = idle.as_nanos() as u64;
146
8
        let now_nanos = crate::font::parsed::monotonic_now_nanos();
147
8
        let mut evicted = 0usize;
148
8
        for font_ref in parsed.values() {
149
8
            let font: &ParsedFont = crate::font_ref_to_parsed_font(font_ref);
150
8
            let last = font.last_used_nanos();
151
            // Untouched faces are eligible immediately. Touched
152
            // faces need to be `idle` past their last use.
153
8
            let stale = last == 0 || now_nanos.saturating_sub(last) >= cutoff;
154
8
            if stale && font.evict_loca_glyf() {
155
1
                evicted += 1;
156
7
            }
157
        }
158
8
        evicted
159
8
    }
160
}
161

            
162
// ParsedFontTrait Implementation for FontRef
163

            
164
// Implement ShallowClone for FontRef
165
impl ShallowClone for FontRef {
166
1087983
    fn shallow_clone(&self) -> Self {
167
        // FontRef::clone increments the reference count
168
1087983
        self.clone()
169
1087983
    }
170
}
171

            
172
// Use crate::font_ref_to_parsed_font instead of a local duplicate
173

            
174
impl ParsedFontTrait for FontRef {
175
    // +spec:block-formatting-context:21ec9a - bidi direction handled during text shaping for
176
    // vertical writing modes
177
59641
    fn shape_text(
178
59641
        &self,
179
59641
        text: &str,
180
59641
        script: Script,
181
59641
        language: crate::text3::script::Language,
182
59641
        direction: BidiDirection,
183
59641
        style: &StyleProperties,
184
59641
    ) -> Result<Vec<Glyph>, LayoutError> {
185
        // Delegate to the inner ParsedFont's shape_text, passing self as font_ref
186
59641
        let parsed = crate::font_ref_to_parsed_font(self);
187
59641
        parsed.shape_text_for_font_ref(self, text, script, language, direction, style)
188
59641
    }
189

            
190
2191284
    fn get_hash(&self) -> u64 {
191
2191284
        crate::font_ref_to_parsed_font(self).hash
192
2191284
    }
193

            
194
1
    fn get_glyph_size(&self, glyph_id: u16, font_size: f32) -> Option<LogicalSize> {
195
1
        crate::font_ref_to_parsed_font(self).get_glyph_size(glyph_id, font_size)
196
1
    }
197

            
198
1
    fn get_hyphen_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
199
1
        crate::font_ref_to_parsed_font(self).get_hyphen_glyph_and_advance(font_size)
200
1
    }
201

            
202
1
    fn get_kashida_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
203
1
        crate::font_ref_to_parsed_font(self).get_kashida_glyph_and_advance(font_size)
204
1
    }
205

            
206
163
    fn has_glyph(&self, codepoint: u32) -> bool {
207
163
        crate::font_ref_to_parsed_font(self).has_glyph(codepoint)
208
163
    }
209

            
210
    fn get_vertical_metrics(&self, glyph_id: u16) -> Option<VerticalMetrics> {
211
        crate::font_ref_to_parsed_font(self).get_vertical_metrics(glyph_id)
212
    }
213

            
214
1
    fn get_font_metrics(&self) -> LayoutFontMetrics {
215
1
        crate::font_ref_to_parsed_font(self).font_metrics
216
1
    }
217

            
218
6
    fn num_glyphs(&self) -> u16 {
219
6
        crate::font_ref_to_parsed_font(self).num_glyphs
220
6
    }
221

            
222
3
    fn get_space_width(&self) -> Option<usize> {
223
3
        crate::font_ref_to_parsed_font(self).get_space_width()
224
3
    }
225
}
226

            
227
/// Extension trait for `FontRef` to provide access to font bytes and metrics
228
///
229
/// This trait provides methods that require access to the inner `ParsedFont` data.
230
pub trait FontRefExt {
231
    /// Get the original font bytes. Returns an empty slice when the
232
    /// underlying `ParsedFont` was created without retaining its
233
    /// source bytes (the default since the lazy-font-loading refactor).
234
    /// Callers that need the bytes for PDF embedding must construct
235
    /// the `ParsedFont` via `ParsedFont::with_source_bytes`.
236
    fn get_bytes(&self) -> &[u8];
237
    /// Get the full font metrics (PDF-style metrics from HEAD, HHEA, OS/2 tables)
238
    fn get_full_font_metrics(&self) -> azul_css::props::basic::FontMetrics;
239
}
240

            
241
impl FontRefExt for FontRef {
242
    fn get_bytes(&self) -> &[u8] {
243
        crate::font_ref_to_parsed_font(self)
244
            .original_bytes
245
            .as_ref()
246
            .map_or(&[], |b| b.as_slice())
247
    }
248

            
249
    fn get_full_font_metrics(&self) -> azul_css::props::basic::FontMetrics {
250
        use azul_css::{OptionI16, OptionU16, OptionU32};
251

            
252
        let parsed = crate::font_ref_to_parsed_font(self);
253
        let pdf = &parsed.pdf_font_metrics;
254

            
255
        // PdfFontMetrics only has a subset of fields; fill others with defaults
256
        azul_css::props::basic::FontMetrics {
257
            // OS/2 version 1 fields (u32 - align 4, placed first)
258
            ul_code_page_range1: OptionU32::None,
259
            ul_code_page_range2: OptionU32::None,
260

            
261
            // OS/2 table (u32 fields)
262
            ul_unicode_range1: 0, // Not in PdfFontMetrics
263
            ul_unicode_range2: 0, // Not in PdfFontMetrics
264
            ul_unicode_range3: 0, // Not in PdfFontMetrics
265
            ul_unicode_range4: 0, // Not in PdfFontMetrics
266
            ach_vend_id: 0,       // Not in PdfFontMetrics
267

            
268
            // OS/2 version 0 fields (optional)
269
            s_typo_ascender: OptionI16::None,
270
            s_typo_descender: OptionI16::None,
271
            s_typo_line_gap: OptionI16::None,
272
            us_win_ascent: OptionU16::None,
273
            us_win_descent: OptionU16::None,
274

            
275
            // OS/2 version 2 fields (optional)
276
            sx_height: OptionI16::None,
277
            s_cap_height: OptionI16::None,
278
            us_default_char: OptionU16::None,
279
            us_break_char: OptionU16::None,
280
            us_max_context: OptionU16::None,
281

            
282
            // OS/2 version 3 fields (optional)
283
            us_lower_optical_point_size: OptionU16::None,
284
            us_upper_optical_point_size: OptionU16::None,
285

            
286
            // HEAD table fields
287
            units_per_em: pdf.units_per_em,
288
            font_flags: pdf.font_flags,
289
            x_min: pdf.x_min,
290
            y_min: pdf.y_min,
291
            x_max: pdf.x_max,
292
            y_max: pdf.y_max,
293

            
294
            // HHEA table fields
295
            ascender: pdf.ascender,
296
            descender: pdf.descender,
297
            line_gap: pdf.line_gap,
298
            advance_width_max: pdf.advance_width_max,
299
            min_left_side_bearing: 0,  // Not in PdfFontMetrics
300
            min_right_side_bearing: 0, // Not in PdfFontMetrics
301
            x_max_extent: 0,           // Not in PdfFontMetrics
302
            caret_slope_rise: pdf.caret_slope_rise,
303
            caret_slope_run: pdf.caret_slope_run,
304
            caret_offset: 0,  // Not in PdfFontMetrics
305
            num_h_metrics: 0, // Not in PdfFontMetrics
306

            
307
            // OS/2 table fields
308
            x_avg_char_width: pdf.x_avg_char_width,
309
            us_weight_class: pdf.us_weight_class,
310
            us_width_class: pdf.us_width_class,
311
            fs_type: 0,                // Not in PdfFontMetrics
312
            y_subscript_x_size: 0,     // Not in PdfFontMetrics
313
            y_subscript_y_size: 0,     // Not in PdfFontMetrics
314
            y_subscript_x_offset: 0,   // Not in PdfFontMetrics
315
            y_subscript_y_offset: 0,   // Not in PdfFontMetrics
316
            y_superscript_x_size: 0,   // Not in PdfFontMetrics
317
            y_superscript_y_size: 0,   // Not in PdfFontMetrics
318
            y_superscript_x_offset: 0, // Not in PdfFontMetrics
319
            y_superscript_y_offset: 0, // Not in PdfFontMetrics
320
            y_strikeout_size: pdf.y_strikeout_size,
321
            y_strikeout_position: pdf.y_strikeout_position,
322
            s_family_class: 0,      // Not in PdfFontMetrics
323
            fs_selection: 0,        // Not in PdfFontMetrics
324
            us_first_char_index: 0, // Not in PdfFontMetrics
325
            us_last_char_index: 0,  // Not in PdfFontMetrics
326

            
327
            // Panose (align 1 - last)
328
            panose: azul_css::props::basic::Panose::zero(),
329
        }
330
    }
331
}
332

            
333
// ParsedFont helper method for FontRef
334
//
335
// This allows ParsedFont to create glyphs that use FontRef
336
//
337
// FontRef is just a C-style Arc wrapper around ParsedFont, so we delegate to
338
// the common shaping implementation and convert the font reference type.
339

            
340
impl ParsedFont {
341
    /// Internal helper that shapes text and returns Glyph
342
    /// Delegates to `shape_text_internal` and converts the font reference.
343
59642
    fn shape_text_for_font_ref(
344
59642
        &self,
345
59642
        _font_ref: &FontRef,
346
59642
        text: &str,
347
59642
        script: Script,
348
59642
        language: crate::text3::script::Language,
349
59642
        direction: BidiDirection,
350
59642
        style: &StyleProperties,
351
59642
    ) -> Result<Vec<Glyph>, LayoutError> {
352
        // `shape_text_internal` already stamps each glyph with `font_hash`
353
        // and `font_metrics` derived from `self`, which is the same
354
        // `ParsedFont` backing `_font_ref`, so no per-glyph rewrite is needed.
355
59642
        shape_text_internal(self, text, script, language, direction, style)
356
59642
    }
357

            
358
59917
    const fn get_hash(&self) -> u64 {
359
59917
        self.hash
360
59917
    }
361

            
362
16
    fn get_glyph_size(&self, glyph_id: u16, font_size_px: f32) -> Option<LogicalSize> {
363
16
        self.get_or_decode_glyph(glyph_id).map(|record| {
364
14
            let units_per_em = f32::from(self.font_metrics.units_per_em);
365
14
            let scale_factor = if units_per_em > 0.0 {
366
12
                font_size_px / units_per_em
367
            } else {
368
2
                FALLBACK_SCALE
369
            };
370

            
371
            // max_x, max_y, min_x, min_y in font units
372
14
            let bbox = &record.bounding_box;
373

            
374
14
            LogicalSize {
375
14
                width: f32::from(bbox.max_x - bbox.min_x) * scale_factor,
376
14
                height: f32::from(bbox.max_y - bbox.min_y) * scale_factor,
377
14
            }
378
14
        })
379
16
    }
380

            
381
15
    fn get_hyphen_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
382
15
        let glyph_id = self.lookup_glyph_index('-' as u32)?;
383
15
        let advance_units = self.get_horizontal_advance(glyph_id);
384
15
        let scale_factor = if self.font_metrics.units_per_em > 0 {
385
13
            font_size / f32::from(self.font_metrics.units_per_em)
386
        } else {
387
2
            return None;
388
        };
389
13
        let scaled_advance = f32::from(advance_units) * scale_factor;
390
13
        Some((glyph_id, scaled_advance))
391
15
    }
392

            
393
11
    fn get_kashida_glyph_and_advance(&self, font_size: f32) -> Option<(u16, f32)> {
394
        // U+0640 is the Arabic Tatweel character, used for kashida justification.
395
11
        let glyph_id = self.lookup_glyph_index('\u{0640}' as u32)?;
396
        let advance_units = self.get_horizontal_advance(glyph_id);
397
        let scale_factor = if self.font_metrics.units_per_em > 0 {
398
            font_size / f32::from(self.font_metrics.units_per_em)
399
        } else {
400
            return None;
401
        };
402
        let scaled_advance = f32::from(advance_units) * scale_factor;
403
        Some((glyph_id, scaled_advance))
404
11
    }
405
}
406

            
407
/// Fallback scale factor when `units_per_em` is zero (corrupt/broken font).
408
const FALLBACK_SCALE: f32 = 0.01;
409

            
410
// Helper Functions
411

            
412
/// Builds a `FeatureMask` with the appropriate OpenType features for a given script.
413
/// This ensures proper text shaping for complex scripts like Arabic, Devanagari, etc.
414
///
415
/// The function includes:
416
/// - Common features for all scripts (ligatures, contextual alternates, etc.)
417
/// - Script-specific features (positional forms for Arabic, conjuncts for Indic, etc.)
418
///
419
/// This is designed to be stable and explicit - we control exactly which features
420
/// are enabled rather than relying on allsorts' defaults which may change.
421
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
422
                                  // (or cross-type bindings that can't merge)
423
57407
fn build_feature_mask_for_script(script: Script) -> FeatureMask {
424
    use Script::{
425
        Arabic, Bengali, Cyrillic, Devanagari, Ethiopic, Georgian, Greek, Gujarati, Gurmukhi,
426
        Hangul, Hebrew, Hiragana, Kannada, Katakana, Khmer, Latin, Malayalam, Mandarin, Myanmar,
427
        Oriya, Sinhala, Tamil, Telugu, Thai,
428
    };
429

            
430
    // Start with common features that apply to most scripts
431
57407
    let mut mask = FeatureMask::default_mask(); // Includes: CALT, CCMP, CLIG, LIGA, LOCL, RLIG
432

            
433
    // Add script-specific features
434
57407
    match script {
435
        // Arabic and related scripts - require positional forms
436
143
        Arabic => {
437
143
            mask |= Feature::INIT; // Initial forms (at start of word)
438
143
            mask |= Feature::MEDI; // Medial forms (middle of word)
439
143
            mask |= Feature::FINA; // Final forms (end of word)
440
143
            mask |= Feature::ISOL; // Isolated forms (standalone)
441
143
                                   // Note: RLIG (required ligatures) already in default for
442
143
                                   // lam-alef ligatures
443
143
        }
444

            
445
        // Indic scripts - require complex conjunct formation and reordering
446
        Devanagari | Bengali | Gujarati | Gurmukhi | Kannada | Malayalam | Oriya | Tamil
447
27
        | Telugu => {
448
27
            mask |= Feature::NUKT; // Nukta forms
449
27
            mask |= Feature::AKHN; // Akhand ligatures
450
27
            mask |= Feature::RPHF; // Reph form
451
27
            mask |= Feature::RKRF; // Rakar form
452
27
            mask |= Feature::PREF; // Pre-base forms
453
27
            mask |= Feature::BLWF; // Below-base forms
454
27
            mask |= Feature::ABVF; // Above-base forms
455
27
            mask |= Feature::HALF; // Half forms
456
27
            mask |= Feature::PSTF; // Post-base forms
457
27
            mask |= Feature::VATU; // Vattu variants
458
27
            mask |= Feature::CJCT; // Conjunct forms
459
27
        }
460

            
461
        // Myanmar (Burmese) - has complex reordering
462
3
        Myanmar => {
463
3
            mask |= Feature::PREF; // Pre-base forms
464
3
            mask |= Feature::BLWF; // Below-base forms
465
3
            mask |= Feature::PSTF; // Post-base forms
466
3
        }
467

            
468
        // Khmer - has complex reordering and stacking
469
3
        Khmer => {
470
3
            mask |= Feature::PREF; // Pre-base forms
471
3
            mask |= Feature::BLWF; // Below-base forms
472
3
            mask |= Feature::ABVF; // Above-base forms
473
3
            mask |= Feature::PSTF; // Post-base forms
474
3
        }
475

            
476
        // Thai - has tone marks and vowel reordering
477
2
        Thai => {
478
2
            // Thai mostly uses default features, but may have some special marks
479
2
            // The default mask is sufficient for most Thai fonts
480
2
        }
481

            
482
        // Hebrew - may have contextual forms but less complex than Arabic
483
2
        Hebrew => {
484
2
            // Hebrew fonts may use contextual alternates already in default
485
2
            // Some fonts have special features but they're rare
486
2
        }
487

            
488
        // Hangul (Korean) - has complex syllable composition
489
2
        Hangul => {
490
2
            // Note: Hangul jamo features (LJMO, VJMO, TJMO) are not available in allsorts'
491
2
            // FeatureMask Most modern Hangul fonts work correctly with the default
492
2
            // features as syllable composition is usually handled at a lower level
493
2
        }
494

            
495
        // Ethiopic - has syllabic script with some ligatures
496
2
        Ethiopic => {
497
2
            // Default features are usually sufficient
498
2
            // LIGA and CLIG already in default mask
499
2
        }
500

            
501
        // Latin, Greek, Cyrillic - standard features are sufficient
502
57211
        Latin | Greek | Cyrillic => {
503
57211
            // Default mask includes all needed features:
504
57211
            // - LIGA: standard ligatures (fi, fl, etc.)
505
57211
            // - CLIG: contextual ligatures
506
57211
            // - CALT: contextual alternates
507
57211
            // - CCMP: mark composition
508
57211
        }
509

            
510
        // Georgian - uses standard features
511
3
        Georgian => {
512
3
            // Default features sufficient
513
3
        }
514

            
515
        // CJK scripts (Hiragana, Katakana, Mandarin/Hani)
516
6
        Hiragana | Katakana | Mandarin => {
517
6
            // CJK fonts may use vertical alternates, but those are controlled
518
6
            // by writing-mode, not GSUB features in the horizontal direction.
519
6
            // Default features are sufficient.
520
6
        }
521

            
522
        // Sinhala - Indic-derived but simpler
523
3
        Sinhala => {
524
3
            mask |= Feature::AKHN; // Akhand ligatures
525
3
            mask |= Feature::RPHF; // Reph form
526
3
            mask |= Feature::VATU; // Vattu variants
527
3
        }
528
    }
529

            
530
57407
    mask
531
57407
}
532

            
533
/// Maps the layout engine's `Script` enum to an OpenType script tag `u32`.
534
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
535
                                  // (or cross-type bindings that can't merge)
536
59961
const fn to_opentype_script_tag(script: Script) -> u32 {
537
    use Script::{
538
        Arabic, Bengali, Cyrillic, Devanagari, Ethiopic, Georgian, Greek, Gujarati, Gurmukhi,
539
        Hangul, Hebrew, Hiragana, Kannada, Katakana, Khmer, Latin, Malayalam, Mandarin, Myanmar,
540
        Oriya, Sinhala, Tamil, Telugu, Thai,
541
    };
542
    // Tags from https://docs.microsoft.com/en-us/typography/opentype/spec/scripttags
543
59961
    match script {
544
144
        Arabic => u32::from_be_bytes(*b"arab"),
545
3
        Bengali => u32::from_be_bytes(*b"beng"),
546
3
        Cyrillic => u32::from_be_bytes(*b"cyrl"),
547
4
        Devanagari => u32::from_be_bytes(*b"deva"),
548
3
        Ethiopic => u32::from_be_bytes(*b"ethi"),
549
3
        Georgian => u32::from_be_bytes(*b"geor"),
550
23
        Greek => u32::from_be_bytes(*b"grek"),
551
3
        Gujarati => u32::from_be_bytes(*b"gujr"),
552
3
        Gurmukhi => u32::from_be_bytes(*b"guru"),
553
3
        Hangul => u32::from_be_bytes(*b"hang"),
554
233
        Hebrew => u32::from_be_bytes(*b"hebr"),
555
        // OpenType does not define a separate Hiragana script tag;
556
        // both Hiragana and Katakana intentionally use "kana".
557
5
        Hiragana => u32::from_be_bytes(*b"kana"),
558
3
        Kannada => u32::from_be_bytes(*b"knda"),
559
4
        Katakana => u32::from_be_bytes(*b"kana"),
560
3
        Khmer => u32::from_be_bytes(*b"khmr"),
561
59406
        Latin => u32::from_be_bytes(*b"latn"),
562
3
        Malayalam => u32::from_be_bytes(*b"mlym"),
563
94
        Mandarin => u32::from_be_bytes(*b"hani"),
564
3
        Myanmar => u32::from_be_bytes(*b"mymr"),
565
3
        Oriya => u32::from_be_bytes(*b"orya"),
566
3
        Sinhala => u32::from_be_bytes(*b"sinh"),
567
3
        Tamil => u32::from_be_bytes(*b"taml"),
568
3
        Telugu => u32::from_be_bytes(*b"telu"),
569
3
        Thai => u32::from_be_bytes(*b"thai"),
570
    }
571
59961
}
572

            
573
/// Parses a CSS-style font-feature-settings string like `"liga"`, `"liga=0"`, or `"ss01"`.
574
/// Returns an OpenType tag and a value.
575
51
fn parse_font_feature(feature_str: &str) -> Option<(u32, u32)> {
576
51
    let mut parts = feature_str.split('=');
577
51
    let tag_str = parts.next()?.trim();
578
51
    let value_str = parts.next().unwrap_or("1").trim(); // Default to 1 (on) if no value
579

            
580
    // OpenType feature tags must be 4 characters long.
581
51
    if tag_str.len() > 4 {
582
9
        return None;
583
42
    }
584
    // Pad with spaces if necessary
585
42
    let padded_tag_str = format!("{tag_str:<4}");
586

            
587
42
    let tag = u32::from_be_bytes(padded_tag_str.as_bytes().try_into().ok()?);
588
35
    let value = value_str.parse::<u32>().ok()?;
589

            
590
20
    Some((tag, value))
591
51
}
592

            
593
/// A helper to add OpenType features based on CSS `font-variant-*` properties.
594
60540
fn add_variant_features(style: &StyleProperties, features: &mut Vec<FeatureInfo>) {
595
    // Helper to add a feature that is simply "on".
596
61289
    let mut add_on = |tag_str: &[u8; 4]| {
597
1475
        features.push(FeatureInfo {
598
1475
            feature_tag: u32::from_be_bytes(*tag_str),
599
1475
            alternate: None,
600
1475
        });
601
1475
    };
602

            
603
    // Note on disabling features: The CSS properties `font-variant-ligatures: none` or
604
    // `no-common-ligatures` are meant to disable features that may be on by default for a
605
    // given script. The `allsorts` API for applying custom features is additive and does not
606
    // currently support disabling default features. This implementation only handles enabling
607
    // non-default features.
608

            
609
    // Ligatures
610
60540
    match style.font_variant_ligatures {
611
64
        FontVariantLigatures::Discretionary => add_on(b"dlig"),
612
63
        FontVariantLigatures::Historical => add_on(b"hlig"),
613
63
        FontVariantLigatures::Contextual => add_on(b"calt"),
614
60350
        _ => {} // Other cases are either default-on or require disabling.
615
    }
616

            
617
    // Caps
618
60540
    match style.font_variant_caps {
619
91
        FontVariantCaps::SmallCaps => add_on(b"smcp"),
620
91
        FontVariantCaps::AllSmallCaps => {
621
91
            add_on(b"c2sc");
622
91
            add_on(b"smcp");
623
91
        }
624
90
        FontVariantCaps::PetiteCaps => add_on(b"pcap"),
625
90
        FontVariantCaps::AllPetiteCaps => {
626
90
            add_on(b"c2pc");
627
90
            add_on(b"pcap");
628
90
        }
629
90
        FontVariantCaps::Unicase => add_on(b"unic"),
630
91
        FontVariantCaps::TitlingCaps => add_on(b"titl"),
631
59997
        FontVariantCaps::Normal => {}
632
    }
633

            
634
    // Numeric
635
60540
    match style.font_variant_numeric {
636
70
        FontVariantNumeric::LiningNums => add_on(b"lnum"),
637
70
        FontVariantNumeric::OldstyleNums => add_on(b"onum"),
638
70
        FontVariantNumeric::ProportionalNums => add_on(b"pnum"),
639
71
        FontVariantNumeric::TabularNums => add_on(b"tnum"),
640
70
        FontVariantNumeric::DiagonalFractions => add_on(b"frac"),
641
70
        FontVariantNumeric::StackedFractions => add_on(b"afrc"),
642
70
        FontVariantNumeric::Ordinal => add_on(b"ordn"),
643
70
        FontVariantNumeric::SlashedZero => add_on(b"zero"),
644
59979
        FontVariantNumeric::Normal => {}
645
    }
646
60540
}
647

            
648
/// Maps the `hyphenation::Language` enum to an OpenType language tag `u32`.
649
#[cfg(feature = "text_layout_hyphenation")]
650
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
651
                                  // (or cross-type bindings that can't merge)
652
59927
const fn to_opentype_lang_tag(lang: hyphenation::Language) -> u32 {
653
    use hyphenation::Language::{
654
        Afrikaans, Albanian, Armenian, Assamese, Basque, Belarusian, Bengali, Bulgarian, Catalan,
655
        Chinese, Coptic, Croatian, Czech, Danish, Dutch, EnglishGB, EnglishUS, Esperanto, Estonian,
656
        Ethiopic, Finnish, FinnishScholastic, French, Friulan, Galician, Georgian, German1901,
657
        German1996, GermanSwiss, GreekAncient, GreekMono, GreekPoly, Gujarati, Hindi, Hungarian,
658
        Icelandic, Indonesian, Interlingua, Irish, Italian, Kannada, Kurmanji, Latin, LatinClassic,
659
        LatinLiturgical, Latvian, Lithuanian, Macedonian, Malayalam, Marathi, Mongolian,
660
        NorwegianBokmal, NorwegianNynorsk, Occitan, Oriya, Pali, Panjabi, Piedmontese, Polish,
661
        Portuguese, Romanian, Romansh, Russian, Sanskrit, SerbianCyrillic, SerbocroatianCyrillic,
662
        SerbocroatianLatin, SlavonicChurch, Slovak, Slovenian, Spanish, Swedish, Tamil, Telugu,
663
        Thai, Turkish, Turkmen, Ukrainian, Uppersorbian, Welsh,
664
    };
665
    // A complete list of language tags can be found at:
666
    // https://docs.microsoft.com/en-us/typography/opentype/spec/languagetags
667
59927
    let tag_bytes = match lang {
668
        Afrikaans => *b"AFK ",
669
        Albanian => *b"SQI ",
670
        Armenian => *b"HYE ",
671
        Assamese => *b"ASM ",
672
        Basque => *b"EUQ ",
673
        Belarusian => *b"BEL ",
674
        Bengali => *b"BEN ",
675
        Bulgarian => *b"BGR ",
676
        Catalan => *b"CAT ",
677
410
        Chinese => *b"ZHS ",
678
        Coptic => *b"COP ",
679
        Croatian => *b"HRV ",
680
        Czech => *b"CSY ",
681
        Danish => *b"DAN ",
682
        Dutch => *b"NLD ",
683
2
        EnglishGB => *b"ENG ",
684
59448
        EnglishUS => *b"ENU ",
685
        Esperanto => *b"ESP ",
686
        Estonian => *b"ETI ",
687
        Ethiopic => *b"ETH ",
688
2
        Finnish => *b"FIN ",
689
2
        FinnishScholastic => *b"FIN ",
690
2
        French => *b"FRA ",
691
        Friulan => *b"FRL ",
692
        Galician => *b"GLC ",
693
        Georgian => *b"KAT ",
694
2
        German1901 => *b"DEU ",
695
33
        German1996 => *b"DEU ",
696
        GermanSwiss => *b"DES ",
697
        GreekAncient => *b"GRC ",
698
20
        GreekMono => *b"ELL ",
699
        GreekPoly => *b"ELL ",
700
        Gujarati => *b"GUJ ",
701
        Hindi => *b"HIN ",
702
        Hungarian => *b"HUN ",
703
        Icelandic => *b"ISL ",
704
        Indonesian => *b"IND ",
705
        Interlingua => *b"INA ",
706
        Irish => *b"IRI ",
707
        Italian => *b"ITA ",
708
        Kannada => *b"KAN ",
709
        Kurmanji => *b"KUR ",
710
1
        Latin => *b"LAT ",
711
1
        LatinClassic => *b"LAT ",
712
        LatinLiturgical => *b"LAT ",
713
        Latvian => *b"LVI ",
714
        Lithuanian => *b"LTH ",
715
        Macedonian => *b"MKD ",
716
        Malayalam => *b"MAL ",
717
        Marathi => *b"MAR ",
718
        Mongolian => *b"MNG ",
719
        NorwegianBokmal => *b"NOR ",
720
        NorwegianNynorsk => *b"NYN ",
721
        Occitan => *b"OCI ",
722
        Oriya => *b"ORI ",
723
        Pali => *b"PLI ",
724
        Panjabi => *b"PAN ",
725
        Piedmontese => *b"PMS ",
726
        Polish => *b"PLK ",
727
        Portuguese => *b"PTG ",
728
        Romanian => *b"ROM ",
729
        Romansh => *b"RMC ",
730
2
        Russian => *b"RUS ",
731
        Sanskrit => *b"SAN ",
732
        SerbianCyrillic => *b"SRB ",
733
        SerbocroatianCyrillic => *b"SHC ",
734
        SerbocroatianLatin => *b"SHL ",
735
        SlavonicChurch => *b"CSL ",
736
        Slovak => *b"SKY ",
737
        Slovenian => *b"SLV ",
738
        Spanish => *b"ESP ",
739
        Swedish => *b"SVE ",
740
        Tamil => *b"TAM ",
741
        Telugu => *b"TEL ",
742
1
        Thai => *b"THA ",
743
        Turkish => *b"TRK ",
744
        Turkmen => *b"TUK ",
745
        Ukrainian => *b"UKR ",
746
        Uppersorbian => *b"HSB ",
747
1
        Welsh => *b"CYM ",
748
    };
749
59927
    u32::from_be_bytes(tag_bytes)
750
59927
}
751

            
752
/// Internal shaping implementation - the single source of truth for text shaping.
753
/// Both `FontRef` and `ParsedFont` use this function.
754
#[allow(
755
    clippy::cast_possible_truncation,
756
    clippy::cast_precision_loss,
757
    clippy::cast_sign_loss
758
)] // bounded layout/render numeric cast
759
#[allow(clippy::similar_names)] // domain-standard coordinate/geometry/short-lived names
760
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
761
                                 // (one branch per case)
762
59906
fn shape_text_internal(
763
59906
    parsed_font: &ParsedFont,
764
59906
    text: &str,
765
59906
    script: Script,
766
59906
    language: crate::text3::script::Language,
767
59906
    direction: BidiDirection,
768
59906
    style: &StyleProperties,
769
59906
) -> Result<Vec<Glyph>, LayoutError> {
770
59906
    let script_tag = to_opentype_script_tag(script);
771
    #[cfg(feature = "text_layout_hyphenation")]
772
59906
    let lang_tag = to_opentype_lang_tag(language);
773
    #[cfg(not(feature = "text_layout_hyphenation"))]
774
    let lang_tag = 0u32;
775

            
776
    // +spec:text-alignment-spacing:4357e6 - non-zero letter-spacing should disable optional
777
    // ligatures; allsorts API is additive-only so default liga cannot be disabled here
778
    // +spec:text-alignment-spacing:24d624 - cursive script letter-spacing behavior is advisory
779
    // (outside CSS scope per spec note)
780
59906
    let mut user_features: Vec<FeatureInfo> = style
781
59906
        .font_features
782
59906
        .iter()
783
59906
        .filter_map(|s| parse_font_feature(s))
784
59906
        .map(|(tag, value)| FeatureInfo {
785
4
            feature_tag: tag,
786
4
            alternate: if value > 1 {
787
1
                Some(value as usize)
788
            } else {
789
3
                None
790
            },
791
4
        })
792
59906
        .collect();
793
59906
    add_variant_features(style, &mut user_features);
794

            
795
59906
    let opt_gdef = parsed_font.opt_gdef_table.as_deref();
796

            
797
59906
    let mut raw_glyphs: Vec<gsub::RawGlyph<()>> = Vec::new();
798
    {
799
59906
        let mut ci = 0usize;
800
1291251
        while ci < text.len() {
801
1231345
            let Some(ch) = text[ci..].chars().next() else {
802
                break;
803
            };
804
1231345
            let glyph_index = parsed_font.lookup_glyph_index(ch as u32).unwrap_or(0);
805
            // NOTE: `liga_component_pos` MUST be left at allsorts' managed default (0)
806
            // here. It is a GPOS ligature-COMPONENT index, and mark-to-mark /
807
            // mark-to-ligature attachment (gpos::forall_mark_mark_glyph_pairs,
808
            // gpos::markligpos) is gated on equality of this field between glyphs.
809
            // Overloading it with the source byte offset (as an earlier version did)
810
            // made every glyph carry a distinct value, silently disabling mkmk stacking
811
            // and mis-selecting ligature-component anchors. Source byte offsets are
812
            // instead reconstructed after shaping from each glyph's `unicodes` (see the
813
            // read-back loop below), which also removes the old u16 byte-offset cap that
814
            // dropped every glyph past byte 65535.
815
1231345
            raw_glyphs.push(gsub::RawGlyph {
816
1231345
                unicodes: tinyvec::tiny_vec![[char; 1] => ch],
817
1231345
                glyph_index,
818
                liga_component_pos: 0,
819
1231345
                glyph_origin: gsub::GlyphOrigin::Char(ch),
820
1231345
                flags: gsub::RawGlyphFlags::empty(),
821
1231345
                extra_data: (),
822
1231345
                variation: None,
823
            });
824
1231345
            ci += ch.len_utf8();
825
        }
826
    }
827

            
828
59906
    if let Some(gsub) = parsed_font.gsub() {
829
        // Always start from the script's default feature mask (LIGA, CLIG, CALT,
830
        // CCMP, LOCL, RLIG + script-specific shaping features) and additively layer
831
        // any user-supplied features on top. gsub::apply applies the mask AND the
832
        // custom features, so these are NOT mutually exclusive. The previous code
833
        // replaced the mask with `empty()` whenever ANY font-feature/font-variant
834
        // was set, which silently disabled default ligatures/contextual-alternates
835
        // for Latin-family text (ScriptType::Default only re-adds CCMP|RLIG|LOCL).
836
57366
        let feature_mask = build_feature_mask_for_script(script);
837
57366
        let custom_features: &[FeatureInfo] = user_features.as_slice();
838

            
839
57366
        let dotted_circle_index = parsed_font
840
57366
            .lookup_glyph_index(allsorts::DOTTED_CIRCLE as u32)
841
57366
            .unwrap_or(0);
842
57366
        gsub::apply(
843
57366
            dotted_circle_index,
844
57366
            gsub,
845
57366
            opt_gdef,
846
57366
            script_tag,
847
57366
            Some(lang_tag),
848
57366
            feature_mask,
849
57366
            custom_features,
850
57366
            None,
851
57366
            parsed_font.num_glyphs(),
852
57366
            &mut raw_glyphs,
853
        )
854
57366
        .map_err(|e| LayoutError::ShapingError(e.to_string()))?;
855
2540
    }
856

            
857
59906
    let mut infos = gpos::Info::init_from_glyphs(opt_gdef, raw_glyphs);
858

            
859
59906
    if let Some(gpos) = parsed_font.gpos() {
860
57246
        let kern_table = parsed_font
861
57246
            .opt_kern_table
862
57246
            .as_ref()
863
57246
            .map(|kt| kt.as_borrowed());
864
57246
        let apply_kerning = true; // Always enable GPOS kern feature (not just when legacy kern
865
                                  // table exists)
866
57246
        gpos::apply(
867
57246
            gpos,
868
57246
            opt_gdef,
869
57246
            kern_table,
870
57246
            apply_kerning,
871
57246
            FeatureMask::empty(),
872
57246
            &user_features,
873
57246
            None,
874
57246
            script_tag,
875
57246
            Some(lang_tag),
876
57246
            &mut infos,
877
        )
878
57246
        .map_err(|e| LayoutError::ShapingError(e.to_string()))?;
879
    } else {
880
        // No GPOS table: apply the legacy `kern` table (and fallback mark
881
        // positioning) directly, so fonts that ship only a legacy `kern` table
882
        // still kern — matching CoreText/HarfBuzz behavior. Without this,
883
        // GPOS-less fonts got zero kerning.
884
2660
        let kern_table = parsed_font
885
2660
            .opt_kern_table
886
2660
            .as_ref()
887
2660
            .map(|kt| kt.as_borrowed());
888
2660
        gpos::apply_fallback(kern_table, script_tag, &mut infos)
889
2660
            .map_err(|e| LayoutError::ShapingError(e.to_string()))?;
890
    }
891

            
892
59906
    let font_size = style.font_size_px;
893
59906
    let scale_factor = if parsed_font.font_metrics.units_per_em > 0 {
894
59906
        font_size / f32::from(parsed_font.font_metrics.units_per_em)
895
    } else {
896
        FALLBACK_SCALE
897
    };
898

            
899
59906
    let font_hash = parsed_font.get_hash();
900
59906
    let font_metrics = LayoutFontMetrics {
901
59906
        ascent: parsed_font.font_metrics.ascent,
902
59906
        descent: parsed_font.font_metrics.descent,
903
59906
        line_gap: parsed_font.font_metrics.line_gap,
904
59906
        units_per_em: parsed_font.font_metrics.units_per_em,
905
59906
        x_height: parsed_font.font_metrics.x_height,
906
59906
        cap_height: parsed_font.font_metrics.cap_height,
907
59906
    };
908
59906
    let style_arc = Arc::new(style.clone());
909
59906
    let bidi_level = BidiLevel::new(u8::from(direction.is_rtl()));
910

            
911
59906
    let mut shaped_glyphs = Vec::new();
912
    // Reconstruct source byte spans by walking the source text in logical order,
913
    // consuming each glyph's `unicodes`. This replaces the removed liga_component_pos
914
    // byte-offset overload. A ligature glyph carries ALL of its component chars in
915
    // `unicodes`, so its span covers every merged component (fixing the ligature
916
    // logical_byte_len that previously reported only the first component's length).
917
    // Multiple-substitution duplicates (MULTI_SUBST_DUP) and unicode-less inserted
918
    // glyphs share the current cursor position and do not advance it.
919
59906
    let mut byte_cursor = 0usize;
920
1289724
    for info in &infos {
921
1231325
        let uni_len: usize = info.glyph.unicodes.iter().map(|c| c.len_utf8()).sum();
922
1229818
        let (byte_index, byte_len) = if info.glyph.multi_subst_dup() || uni_len == 0 {
923
            (byte_cursor.min(text.len()), 0)
924
        } else {
925
1229818
            let start = byte_cursor.min(text.len());
926
1229818
            byte_cursor = (byte_cursor + uni_len).min(text.len());
927
1229818
            (start, uni_len)
928
        };
929
1229818
        let cluster = byte_index as u32;
930
1229818
        let source_char = info
931
1229818
            .glyph
932
1229818
            .unicodes
933
1229818
            .first()
934
1229818
            .copied()
935
1229818
            .or_else(|| text.get(byte_index..).and_then(|s| s.chars().next()))
936
1229818
            .unwrap_or('\u{FFFD}');
937

            
938
1229818
        let base_advance = parsed_font.get_horizontal_advance(info.glyph.glyph_index);
939
        // Layout uses LINEAR (design-space) advances, like Chrome/Blink and
940
        // CoreText: with sub-pixel text positioning the rasterizer places
941
        // each glyph at a fractional origin, and under light hinting the X
942
        // axis is not grid-fit at all, so integer-quantized hinted advances
943
        // would only ADD error. Measured: hinted advances inflated runs by
944
        // ~0.2px per glyph ('l' at 14px: 4.0 hinted vs 3.612 linear), which
945
        // made every long text run visibly wider than Chrome's (cascade-*
946
        // reftests). Full grid-fit mode (AZ_HINT_LIGHT=0) keeps the hinted
947
        // advance so raster and metrics stay mutually consistent; it is
948
        // rescaled from the integer hinting ppem back to the exact
949
        // fractional font size to stay on the same basis as the GPOS
950
        // offsets and kerning below.
951
        // `hint_light_enabled` lives in glyph_cache, which is `cpurender`-
952
        // gated; text layout itself is not. Without cpurender there is no
953
        // rasterizer to stay consistent WITH, so the light (linear-advance)
954
        // basis — also the default when the module IS present — is the only
955
        // sensible answer. Reading the same env var here keeps a
956
        // cpurender-less build honest about AZ_HINT_LIGHT=0 being a
957
        // raster-side knob it cannot honor.
958
        #[cfg(feature = "cpurender")]
959
1229818
        let hint_light =
960
1229818
            crate::glyph_cache::hint_light_enabled() || !crate::glyph_cache::text_hinting_enabled();
961
        #[cfg(not(feature = "cpurender"))]
962
        let hint_light = true;
963
1229818
        let advance = if hint_light {
964
1229818
            f32::from(base_advance) * scale_factor
965
        } else {
966
            let ppem = font_size.round().max(1.0) as u16;
967
            parsed_font
968
                .get_hinted_advance_px(info.glyph.glyph_index, ppem)
969
                .map_or_else(
970
                    || f32::from(base_advance) * scale_factor,
971
                    |hinted| hinted * font_size / f32::from(ppem),
972
                )
973
        };
974
1229818
        let kerning = f32::from(info.kerning) * scale_factor;
975

            
976
1229818
        let (offset_x_units, offset_y_units) =
977
1229818
            if let gpos::Placement::Distance(x, y) = info.placement {
978
                (x, y)
979
            } else {
980
1229818
                (0, 0)
981
            };
982
1229818
        let offset_x = offset_x_units as f32 * scale_factor;
983
1229818
        let offset_y = offset_y_units as f32 * scale_factor;
984

            
985
1229818
        let vert = parsed_font.get_vertical_metrics(info.glyph.glyph_index);
986
1229818
        let glyph = Glyph {
987
1229818
            glyph_id: info.glyph.glyph_index,
988
1229818
            codepoint: source_char,
989
1229818
            font_hash,
990
1229818
            font_metrics,
991
1229818
            style: Arc::clone(&style_arc),
992
1229818
            source: GlyphSource::Char,
993
1229818
            logical_byte_index: byte_index,
994
1229818
            logical_byte_len: byte_len,
995
            content_index: 0,
996
1229818
            cluster,
997
1229818
            advance,
998
1229818
            kerning,
999
1229818
            offset: Point {
1229818
                x: offset_x,
1229818
                y: offset_y,
1229818
            },
1229818
            vertical_advance: vert.as_ref().map_or(0.0, |v| v.advance * font_size),
1229818
            vertical_origin_y: vert.as_ref().map_or(0.0, |v| v.origin_y * font_size),
1229818
            vertical_bearing: vert.map_or(Point { x: 0.0, y: 0.0 }, |v| Point {
150
                x: v.bearing_x * font_size,
150
                y: v.bearing_y * font_size,
150
            }),
1229818
            orientation: GlyphOrientation::Horizontal,
1229818
            script,
1229818
            bidi_level,
        };
1229818
        shaped_glyphs.push(glyph);
    }
59906
    Ok(shaped_glyphs)
59906
}
/// Public helper function to shape text for `ParsedFont`, returning Glyph
/// This is used by the `ParsedFontTrait` implementation for `ParsedFont`
/// # Errors
///
/// Returns a `LayoutError` if the text cannot be shaped.
212
pub fn shape_text_for_parsed_font(
212
    parsed_font: &ParsedFont,
212
    text: &str,
212
    script: Script,
212
    language: crate::text3::script::Language,
212
    direction: BidiDirection,
212
    style: &StyleProperties,
212
) -> Result<Vec<Glyph>, LayoutError> {
    // Delegate to the single internal implementation
212
    shape_text_internal(parsed_font, text, script, language, direction, style)
212
}
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::cast_lossless, clippy::unreadable_literal)]
mod autotest_generated {
    use std::time::Duration;
    use rust_fontconfig::{FcFontCache, FontBytes, FontId};
    use super::*;
    use crate::text3::script::Language;
    /// Positive control: the built-in `Azul Mock Mono` TrueType face.
    const MOCK_MONO: &[u8] = crate::text3::mock_fonts::MOCK_MONO_TTF;
    /// Every `Script` variant, so the exhaustive mapping tables below can never
    /// silently miss one.
    const ALL_SCRIPTS: [Script; 24] = [
        Script::Arabic,
        Script::Bengali,
        Script::Cyrillic,
        Script::Devanagari,
        Script::Ethiopic,
        Script::Georgian,
        Script::Greek,
        Script::Gujarati,
        Script::Gurmukhi,
        Script::Hangul,
        Script::Hebrew,
        Script::Hiragana,
        Script::Kannada,
        Script::Katakana,
        Script::Khmer,
        Script::Latin,
        Script::Malayalam,
        Script::Mandarin,
        Script::Myanmar,
        Script::Oriya,
        Script::Sinhala,
        Script::Tamil,
        Script::Telugu,
        Script::Thai,
    ];
    /// Eager parse (`LocaGlyfState::Loaded`).
    fn mock() -> ParsedFont {
        let mut warnings = Vec::new();
        ParsedFont::from_bytes(MOCK_MONO, 0, &mut warnings).expect("Azul Mock Mono must parse")
    }
    /// Lazy parse (`LocaGlyfState::Deferred`) — the production path.
    fn mock_deferred() -> ParsedFont {
        let bytes = Arc::new(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 style_at(font_size_px: f32) -> StyleProperties {
        StyleProperties {
            font_size_px,
            ..StyleProperties::default()
        }
    }
    fn shape(font: &ParsedFont, text: &str) -> Result<Vec<Glyph>, LayoutError> {
        shape_text_internal(
            font,
            text,
            Script::Latin,
            Language::EnglishUS,
            BidiDirection::Ltr,
            &style_at(16.0),
        )
    }
    /// Invariants that must hold for *any* shaping result, no matter how hostile
    /// the input: byte spans stay inside the source, land on char boundaries and
    /// never run backwards.
    fn assert_spans_are_sane(glyphs: &[Glyph], text: &str) {
        let mut prev_index = 0usize;
        for g in glyphs {
            assert!(
                g.logical_byte_index <= text.len(),
                "byte index {} escapes the {}-byte source",
                g.logical_byte_index,
                text.len()
            );
            let end = g.logical_byte_index + g.logical_byte_len;
            assert!(
                end <= text.len(),
                "span {}..{end} escapes the {}-byte source",
                g.logical_byte_index,
                text.len()
            );
            assert!(
                text.is_char_boundary(g.logical_byte_index) && text.is_char_boundary(end),
                "span {}..{end} splits a UTF-8 sequence",
                g.logical_byte_index
            );
            assert!(
                g.logical_byte_index >= prev_index,
                "byte cursor ran backwards: {} after {prev_index}",
                g.logical_byte_index
            );
            prev_index = g.logical_byte_index;
            assert_eq!(
                u64::from(g.cluster),
                g.logical_byte_index as u64,
                "cluster must mirror the logical byte index"
            );
        }
    }
    // -----------------------------------------------------------------
    // font_ref_from_bytes (parser)
    // -----------------------------------------------------------------
    #[test]
    fn font_ref_from_bytes_rejects_empty_and_malformed_input() {
        // empty / whitespace-only / invalid-UTF-8 / garbage: None, never a panic
        assert!(font_ref_from_bytes(b"", 0, false).is_none());
        assert!(font_ref_from_bytes(b"   \t\n", 0, false).is_none());
        assert!(font_ref_from_bytes(&[0xFF, 0xFE, 0x00], 0, false).is_none());
        assert!(font_ref_from_bytes(b"not a font at all, just prose", 0, false).is_none());
        // a 4-byte "sfnt-ish" header with nothing behind it
        assert!(font_ref_from_bytes(&[0x00, 0x01, 0x00, 0x00], 0, false).is_none());
        // truncated real font: header only, then a torso
        assert!(font_ref_from_bytes(&MOCK_MONO[..12], 0, false).is_none());
        assert!(font_ref_from_bytes(&MOCK_MONO[..64], 0, false).is_none());
        // leading junk in front of an otherwise valid font must not parse
        let mut prefixed = vec![0xABu8; 32];
        prefixed.extend_from_slice(MOCK_MONO);
        assert!(font_ref_from_bytes(&prefixed, 0, false).is_none());
    }
    #[test]
    fn font_ref_from_bytes_extremely_long_garbage_terminates() {
        // 1 MiB of NULs must be rejected without hanging or allocating wildly
        assert!(font_ref_from_bytes(&vec![0u8; 1_000_000], 0, false).is_none());
        // a "ttcf" collection header followed by a megabyte of noise
        let mut ttc_junk = b"ttcf".to_vec();
        ttc_junk.extend_from_slice(&vec![0xCDu8; 1_000_000]);
        assert!(font_ref_from_bytes(&ttc_junk, 0, false).is_none());
    }
    #[test]
    fn font_ref_from_bytes_valid_minimal_positive_control() {
        let font_ref = font_ref_from_bytes(MOCK_MONO, 0, false)
            .expect("Azul Mock Mono must parse into a FontRef");
        assert!(font_ref.num_glyphs() > 0, "a real font has glyphs");
        assert_eq!(font_ref.get_hash(), mock().get_hash());
        assert!(font_ref.has_glyph('a' as u32));
    }
    #[test]
    fn font_ref_from_bytes_ignores_the_parse_outlines_flag() {
        // NOTE: `parse_outlines` is accepted but never forwarded to
        // `ParsedFont::from_bytes` — both settings must therefore produce
        // an identical face. This pins the current (no-op) behaviour.
        let with = font_ref_from_bytes(MOCK_MONO, 0, true).expect("parse with outlines");
        let without = font_ref_from_bytes(MOCK_MONO, 0, false).expect("parse without outlines");
        assert_eq!(with.get_hash(), without.get_hash());
        assert_eq!(with.num_glyphs(), without.num_glyphs());
        assert_eq!(with.get_space_width(), without.get_space_width());
    }
    #[test]
    fn font_ref_from_bytes_extreme_font_index_does_not_panic() {
        // Out-of-range collection indices must resolve to Some/None, never an
        // out-of-bounds index panic.
        for index in [0usize, 1, 255, usize::MAX / 2, usize::MAX] {
            let _ = font_ref_from_bytes(MOCK_MONO, index, false);
            let _ = font_ref_from_bytes(b"", index, false);
        }
    }
    // -----------------------------------------------------------------
    // PathLoader::new / load_from_path / load_font_shared
    // -----------------------------------------------------------------
    #[test]
    fn path_loader_new_is_a_zero_sized_stateless_handle() {
        assert_eq!(size_of::<PathLoader>(), 0);
        let a = PathLoader::new();
        let b = PathLoader;
        // both handles behave identically: no hidden per-instance state
        assert!(a
            .load_from_path(Path::new("/nonexistent/azul/x.ttf"), 0)
            .is_err());
        assert!(b
            .load_from_path(Path::new("/nonexistent/azul/x.ttf"), 0)
            .is_err());
    }
    #[test]
    fn load_from_path_missing_empty_and_directory_paths_are_font_not_found() {
        let loader = PathLoader::new();
        for path in [
            "",
            "/nonexistent/definitely/not/a/font.ttf",
            "/dev/null",
            env!("CARGO_MANIFEST_DIR"), // a directory, not a file
        ] {
            match loader.load_from_path(Path::new(path), 0) {
                Err(LayoutError::FontNotFound(selector)) => {
                    assert_eq!(selector.family, path, "the failing path is reported back");
                    assert!(selector.unicode_ranges.is_empty());
                }
                // /dev/null reads as zero bytes on Linux -> the parse fails instead
                Err(LayoutError::ShapingError(_)) => {}
                other => panic!("{path:?} must not load a font: {other:?}"),
            }
        }
    }
    #[test]
    fn load_from_path_parses_a_real_font_and_survives_extreme_indices() {
        let loader = PathLoader::new();
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/assets/fonts/test/azul-mock-mono.ttf"
        );
        let font_ref = loader
            .load_from_path(Path::new(path), 0)
            .expect("the positive control must load from disk");
        assert_eq!(font_ref.num_glyphs(), mock().num_glyphs());
        // 0 / MAX face index: either resolves or errors, but never panics
        for index in [0usize, 1, usize::MAX] {
            let _ = loader.load_from_path(Path::new(path), index);
        }
    }
    #[test]
    fn load_font_shared_rejects_empty_and_garbage_byte_blobs() {
        let loader = PathLoader::new();
        let cases: Vec<Vec<u8>> = vec![
            Vec::new(),
            b"   \t\n".to_vec(),
            vec![0xFF, 0xFE, 0x00],
            MOCK_MONO[..32].to_vec(),
            vec![0u8; 1_000_000],
        ];
        for bytes in cases {
            let shared = Arc::new(FontBytes::Owned(Arc::from(bytes)));
            match loader.load_font_shared(shared, 0) {
                Err(LayoutError::ShapingError(msg)) => assert!(!msg.is_empty()),
                other => panic!("garbage must not parse: {other:?}"),
            }
        }
    }
    #[test]
    fn load_font_shared_matches_the_eager_parse_and_tolerates_extreme_indices() {
        let loader = PathLoader::new();
        let shared = Arc::new(FontBytes::Owned(Arc::from(MOCK_MONO.to_vec())));
        let font_ref = loader
            .load_font_shared(Arc::clone(&shared), 0)
            .expect("the positive control must parse");
        let eager = mock();
        assert_eq!(font_ref.num_glyphs(), eager.num_glyphs());
        assert_eq!(font_ref.get_hash(), eager.get_hash());
        // font_index at the numeric extremes must not index out of bounds
        for index in [0usize, 1, usize::MAX] {
            let _ = loader.load_font_shared(Arc::clone(&shared), index);
        }
    }
    // -----------------------------------------------------------------
    // FontManager::evict_unused
    // -----------------------------------------------------------------
    #[test]
    fn evict_unused_on_an_empty_manager_is_zero_for_extreme_durations() {
        let manager: FontManager<FontRef> =
            FontManager::new(FcFontCache::default()).expect("an empty FontManager must build");
        // Duration::MAX truncates when cast to u64 nanos; with no faces cached
        // the result is 0 either way — the point is that it must not panic.
        for idle in [
            Duration::ZERO,
            Duration::from_nanos(1),
            Duration::from_secs(3600),
            Duration::MAX,
        ] {
            assert_eq!(manager.evict_unused(idle), 0);
        }
    }
    #[test]
    fn evict_unused_only_reclaims_stale_deferred_faces() {
        let manager: FontManager<FontRef> =
            FontManager::new(FcFontCache::default()).expect("an empty FontManager must build");
        let deferred = crate::parsed_font_to_font_ref(mock_deferred());
        let eager = crate::parsed_font_to_font_ref(mock());
        {
            let mut fonts = manager.parsed_fonts.lock().unwrap();
            fonts.insert(FontId::new(), deferred.clone());
            fonts.insert(FontId::new(), eager.clone());
        }
        // Nothing has decoded a glyph yet: the deferred face holds no LocaGlyf,
        // so there is nothing to release even though it is "never touched".
        assert_eq!(manager.evict_unused(Duration::ZERO), 0);
        // Touch the deferred face -> it materialises loca+glyf and stamps last_used.
        let parsed = crate::font_ref_to_parsed_font(&deferred);
        assert!(parsed.get_or_decode_glyph(1).is_some(), "gid 1 must decode");
        let _ = crate::font_ref_to_parsed_font(&eager).get_or_decode_glyph(1);
        // A face used microseconds ago is not idle for an hour.
        assert_eq!(manager.evict_unused(Duration::from_secs(3600)), 0);
        // With a zero idle window it is stale immediately. The eager face keeps
        // no source bytes, so it can never be evicted -> exactly one eviction.
        assert_eq!(manager.evict_unused(Duration::ZERO), 1);
        // Evicting twice is a no-op.
        assert_eq!(manager.evict_unused(Duration::ZERO), 0);
        // The evicted face still decodes: it re-parses from its retained bytes.
        assert!(parsed.get_or_decode_glyph(2).is_some());
    }
    // -----------------------------------------------------------------
    // shape_text_internal / shape_text_for_parsed_font / FontRef::shape_text
    // -----------------------------------------------------------------
    #[test]
    fn shape_text_empty_input_yields_no_glyphs() {
        let font = mock();
        let glyphs = shape(&font, "").expect("empty text is not an error");
        assert!(glyphs.is_empty());
        let via_public = shape_text_for_parsed_font(
            &font,
            "",
            Script::Latin,
            Language::EnglishUS,
            BidiDirection::Ltr,
            &style_at(16.0),
        )
        .expect("empty text is not an error");
        assert!(via_public.is_empty());
        let font_ref = crate::parsed_font_to_font_ref(mock());
        let via_ref = font_ref
            .shape_text(
                "",
                Script::Latin,
                Language::EnglishUS,
                BidiDirection::Ltr,
                &style_at(16.0),
            )
            .expect("empty text is not an error");
        assert!(via_ref.is_empty());
    }
    #[test]
    fn shape_text_valid_minimal_input_maps_bytes_one_to_one() {
        let font = mock();
        let glyphs = shape(&font, "abc").expect("plain ASCII must shape");
        assert_eq!(glyphs.len(), 3);
        assert_spans_are_sane(&glyphs, "abc");
        for (i, (g, ch)) in glyphs.iter().zip("abc".chars()).enumerate() {
            assert_eq!(g.codepoint, ch);
            assert_eq!(g.logical_byte_index, i);
            assert_eq!(g.logical_byte_len, 1);
            assert_eq!(g.glyph_id, font.lookup_glyph_index(ch as u32).unwrap_or(0));
            assert!(g.advance > 0.0, "a real glyph has a positive advance");
            assert!(g.advance.is_finite());
            assert_eq!(g.font_hash, font.get_hash());
            assert_eq!(g.script, Script::Latin);
        }
    }
    #[test]
    fn shape_text_whitespace_only_input_is_shaped_not_trimmed() {
        let font = mock();
        let text = " \t\n\r ";
        let glyphs = shape(&font, text).expect("whitespace must shape");
        assert!(!glyphs.is_empty(), "whitespace is not silently dropped");
        assert_spans_are_sane(&glyphs, text);
        for g in &glyphs {
            assert!(g.advance.is_finite());
        }
    }
    #[test]
    fn shape_text_unicode_and_missing_glyphs_keep_multibyte_spans_intact() {
        let font = mock();
        // emoji (almost certainly absent from a text face), combining marks, RTL,
        // CJK and an unassigned plane-15 codepoint
        for text in [
            "\u{1F600}",
            "e\u{0301}\u{0327}",
            "\u{0627}\u{0644}\u{0639}\u{0631}\u{0628}\u{064A}\u{0629}",
            "\u{4E2D}\u{6587}",
            "\u{FFFD}\u{FDD0}\u{F0000}",
            "a\u{200B}b\u{00AD}c",
        ] {
            let glyphs =
                shape(&font, text).unwrap_or_else(|e| panic!("{text:?} must shape: {e:?}"));
            assert!(!glyphs.is_empty(), "{text:?} produced no glyphs");
            assert_spans_are_sane(&glyphs, text);
        }
        // a missing glyph falls back to .notdef but must still carry the full
        // 4-byte span of the source character
        let emoji = "\u{1F600}";
        let glyphs = shape(&font, emoji).expect("emoji must shape");
        assert_eq!(glyphs.len(), 1);
        assert_eq!(glyphs[0].codepoint, '\u{1F600}');
        assert_eq!(glyphs[0].logical_byte_index, 0);
        assert_eq!(
            glyphs[0].logical_byte_len, 4,
            "the whole 4-byte char is covered"
        );
        assert_eq!(
            glyphs[0].glyph_id,
            font.lookup_glyph_index('\u{1F600}' as u32).unwrap_or(0)
        );
    }
    #[test]
    fn shape_text_extremely_long_input_terminates() {
        let font = mock();
        let text = "a".repeat(10_000);
        let glyphs = shape(&font, &text).expect("a long run must shape");
        assert_eq!(glyphs.len(), 10_000);
        assert_spans_are_sane(&glyphs, &text);
        // the cursor must have walked the whole source, not stalled at 0
        assert_eq!(glyphs.last().unwrap().logical_byte_index, 9_999);
    }
    #[test]
    fn shape_text_deeply_nested_brackets_does_not_stack_overflow() {
        let font = mock();
        let text = format!("{}{}", "[".repeat(10_000), "]".repeat(10_000));
        let glyphs = shape(&font, &text).expect("nested brackets are just characters");
        assert_eq!(glyphs.len(), 20_000);
        assert_spans_are_sane(&glyphs, &text);
    }
    #[test]
    fn shape_text_boundary_numeric_text_is_shaped_verbatim() {
        let font = mock();
        let text = "0 -0 9223372036854775807 -9223372036854775808 NaN inf 1e309 0.0000001";
        let glyphs = shape(&font, text).expect("numeric-looking text is still text");
        assert_spans_are_sane(&glyphs, text);
        assert!(!glyphs.is_empty());
        for g in &glyphs {
            assert!(g.advance.is_finite(), "a 16px advance must stay finite");
        }
    }
    #[test]
    fn shape_text_nan_and_infinite_font_sizes_do_not_panic() {
        let font = mock();
        // ppem is `font_size.round().max(1.0) as u16` — an unchecked float->int
        // cast. NaN/inf must saturate, not trap.
        for size in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            let glyphs = shape_text_internal(
                &font,
                "ab",
                Script::Latin,
                Language::EnglishUS,
                BidiDirection::Ltr,
                &style_at(size),
            )
            .unwrap_or_else(|e| panic!("font_size {size} must not fail shaping: {e:?}"));
            assert_eq!(glyphs.len(), 2);
            assert_spans_are_sane(&glyphs, "ab");
            for g in &glyphs {
                assert!(
                    !g.advance.is_finite(),
                    "a non-finite font size must not manufacture a finite advance ({size})"
                );
            }
        }
        // Finite-but-absurd sizes drive the float->u16 ppem cast to its
        // saturation points; they may overflow to ±inf but must not panic and
        // must not turn a non-NaN size into a NaN advance.
        for size in [f32::MAX, -f32::MAX, 1e30f32] {
            let glyphs = shape_text_internal(
                &font,
                "ab",
                Script::Latin,
                Language::EnglishUS,
                BidiDirection::Ltr,
                &style_at(size),
            )
            .unwrap_or_else(|e| panic!("font_size {size} must not fail shaping: {e:?}"));
            assert_eq!(glyphs.len(), 2);
            for g in &glyphs {
                assert!(!g.advance.is_nan(), "size {size} produced a NaN advance");
            }
        }
    }
    #[test]
    fn shape_text_zero_and_tiny_font_sizes_produce_zero_or_finite_advances() {
        let font = mock();
        for (size, expect_zero) in [(0.0f32, true), (-0.0f32, true), (f32::MIN_POSITIVE, false)] {
            let glyphs = shape_text_internal(
                &font,
                "ab",
                Script::Latin,
                Language::EnglishUS,
                BidiDirection::Ltr,
                &style_at(size),
            )
            .expect("degenerate font sizes must still shape");
            assert_eq!(glyphs.len(), 2);
            for g in &glyphs {
                assert!(g.advance.is_finite(), "size {size} produced {}", g.advance);
                if expect_zero {
                    assert_eq!(g.advance, 0.0, "a 0px font has zero-width glyphs");
                    assert_eq!(g.kerning, 0.0);
                }
            }
        }
    }
    #[test]
    fn shape_text_negative_font_size_mirrors_the_advance_sign() {
        let font = mock();
        let positive = shape_text_internal(
            &font,
            "a",
            Script::Latin,
            Language::EnglishUS,
            BidiDirection::Ltr,
            &style_at(16.0),
        )
        .expect("shape at +16px");
        let negative = shape_text_internal(
            &font,
            "a",
            Script::Latin,
            Language::EnglishUS,
            BidiDirection::Ltr,
            &style_at(-16.0),
        )
        .expect("a negative font size must not panic");
        assert_eq!(positive.len(), 1);
        assert_eq!(negative.len(), 1);
        assert_eq!(positive[0].glyph_id, negative[0].glyph_id);
        assert!(negative[0].advance.is_finite());
        assert!(
            negative[0].advance <= 0.0,
            "a negative size cannot yield a positive advance"
        );
    }
    #[test]
    fn shape_text_garbage_font_features_are_skipped_not_fatal() {
        let font = mock();
        let style = StyleProperties {
            font_features: vec![
                String::new(),
                "   ".to_string(),
                "waytoolongtag".to_string(),
                "liga=-1".to_string(),
                "liga=99999999999999999999".to_string(),
                "\u{1F600}".to_string(),
                "liga".to_string(), // one good one, to prove the filter is per-item
                "ss01=2".to_string(),
            ],
            ..StyleProperties::default()
        };
        let glyphs = shape_text_internal(
            &font,
            "abc",
            Script::Latin,
            Language::EnglishUS,
            BidiDirection::Ltr,
            &style,
        )
        .expect("malformed feature strings must be dropped, not fatal");
        assert_eq!(glyphs.len(), 3);
        assert_spans_are_sane(&glyphs, "abc");
    }
    #[test]
    fn shape_text_direction_drives_the_bidi_level() {
        let font = mock();
        for (direction, expected) in [(BidiDirection::Ltr, 0u8), (BidiDirection::Rtl, 1u8)] {
            let glyphs = shape_text_internal(
                &font,
                "abc",
                Script::Latin,
                Language::EnglishUS,
                direction,
                &style_at(16.0),
            )
            .expect("both directions must shape");
            assert!(!glyphs.is_empty());
            for g in &glyphs {
                assert_eq!(g.bidi_level.level(), expected);
                assert_eq!(g.bidi_level.is_rtl(), direction.is_rtl());
            }
        }
    }
    #[test]
    fn shape_text_every_script_and_language_pairing_is_shapeable() {
        let font = mock();
        // A script tag that the font has no coverage for must degrade to
        // .notdef glyphs, never to an Err or a panic.
        for script in ALL_SCRIPTS {
            let glyphs = shape_text_internal(
                &font,
                "Hello \u{0e2a}\u{0e27}\u{0e31}\u{0e2a}\u{0e14}\u{0e35}",
                script,
                Language::EnglishUS,
                BidiDirection::Ltr,
                &style_at(16.0),
            )
            .unwrap_or_else(|e| panic!("{script:?} must shape: {e:?}"));
            assert!(!glyphs.is_empty(), "{script:?} produced no glyphs");
            for g in &glyphs {
                assert_eq!(
                    g.script, script,
                    "the requested script is stamped on the glyph"
                );
            }
        }
    }
    #[test]
    fn shape_text_public_internal_and_font_ref_paths_agree() {
        // Round-trip / consistency: the three entry points are documented as
        // sharing one implementation, so they must produce identical glyphs.
        let font = mock();
        let font_ref = crate::parsed_font_to_font_ref(mock());
        let text = "Wafer fi\u{0301}x \u{1F600}";
        let style = style_at(13.5);
        let internal = shape_text_internal(
            &font,
            text,
            Script::Latin,
            Language::EnglishUS,
            BidiDirection::Ltr,
            &style,
        )
        .expect("internal shaping");
        let public = shape_text_for_parsed_font(
            &font,
            text,
            Script::Latin,
            Language::EnglishUS,
            BidiDirection::Ltr,
            &style,
        )
        .expect("public shaping");
        let via_ref = font_ref
            .shape_text(
                text,
                Script::Latin,
                Language::EnglishUS,
                BidiDirection::Ltr,
                &style,
            )
            .expect("FontRef shaping");
        let via_helper = font
            .shape_text_for_font_ref(
                &font_ref,
                text,
                Script::Latin,
                Language::EnglishUS,
                BidiDirection::Ltr,
                &style,
            )
            .expect("shape_text_for_font_ref");
        assert_eq!(internal.len(), public.len());
        assert_eq!(internal.len(), via_ref.len());
        assert_eq!(internal.len(), via_helper.len());
        for (((a, b), c), d) in internal
            .iter()
            .zip(public.iter())
            .zip(via_ref.iter())
            .zip(via_helper.iter())
        {
            for other in [b, c, d] {
                assert_eq!(a.glyph_id, other.glyph_id);
                assert_eq!(a.codepoint, other.codepoint);
                assert_eq!(a.advance, other.advance);
                assert_eq!(a.kerning, other.kerning);
                assert_eq!(a.logical_byte_index, other.logical_byte_index);
                assert_eq!(a.logical_byte_len, other.logical_byte_len);
                assert_eq!(a.font_hash, other.font_hash);
            }
        }
        assert_spans_are_sane(&internal, text);
    }
    // -----------------------------------------------------------------
    // ParsedFont::get_hash (getter)
    // -----------------------------------------------------------------
    #[test]
    fn get_hash_is_stable_and_shared_with_the_font_ref_view() {
        let a = mock();
        let b = mock();
        assert_eq!(a.get_hash(), b.get_hash(), "parsing is deterministic");
        assert_eq!(a.get_hash(), a.hash, "the getter reads the cached field");
        let font_ref = crate::parsed_font_to_font_ref(mock());
        assert_eq!(font_ref.get_hash(), a.get_hash());
        // the lazy constructor must not change identity
        assert_eq!(mock_deferred().get_hash(), a.get_hash());
    }
    // -----------------------------------------------------------------
    // ParsedFont::get_glyph_size (numeric)
    // -----------------------------------------------------------------
    #[test]
    fn get_glyph_size_out_of_range_glyph_ids_are_none() {
        let font = mock();
        assert!(font.get_glyph_size(u16::MAX, 16.0).is_none());
        assert!(font.get_glyph_size(font.num_glyphs, 16.0).is_none());
        // an in-range gid still decodes (positive control)
        let gid = font
            .lookup_glyph_index('a' as u32)
            .expect("'a' must be mapped");
        assert!(gid < font.num_glyphs);
        assert!(font.get_glyph_size(gid, 16.0).is_some());
    }
    #[test]
    fn get_glyph_size_zero_negative_and_non_finite_font_sizes() {
        let font = mock();
        let gid = font
            .lookup_glyph_index('a' as u32)
            .expect("'a' must be mapped");
        let zero = font.get_glyph_size(gid, 0.0).expect("gid decodes");
        assert_eq!(zero.width, 0.0);
        assert_eq!(zero.height, 0.0);
        let base = font.get_glyph_size(gid, 16.0).expect("gid decodes");
        assert!(base.width > 0.0 && base.height > 0.0);
        // scaling is linear in the font size
        let doubled = font.get_glyph_size(gid, 32.0).expect("gid decodes");
        assert!((doubled.width - 2.0 * base.width).abs() <= 1e-3 * base.width.max(1.0));
        let negative = font.get_glyph_size(gid, -16.0).expect("gid decodes");
        assert!(negative.width <= 0.0 && negative.width.is_finite());
        for size in [
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
            f32::MIN_POSITIVE,
        ] {
            let size_result = font
                .get_glyph_size(gid, size)
                .unwrap_or_else(|| panic!("gid must still decode at {size}"));
            assert!(
                !size_result.width.is_nan() || size.is_nan(),
                "only a NaN input may produce a NaN width"
            );
        }
    }
    #[test]
    fn get_glyph_size_zero_units_per_em_uses_the_constant_fallback_scale() {
        assert_eq!(FALLBACK_SCALE, 0.01);
        let mut font = mock();
        let gid = font
            .lookup_glyph_index('a' as u32)
            .expect("'a' must be mapped");
        font.font_metrics.units_per_em = 0; // corrupt/broken font
        // With upem == 0 the scale is the constant FALLBACK_SCALE, so the size no
        // longer depends on the requested font size at all.
        let small = font.get_glyph_size(gid, 16.0).expect("gid decodes");
        let huge = font.get_glyph_size(gid, 1000.0).expect("gid decodes");
        assert!(
            small.width > 0.0 && small.height > 0.0,
            "no divide-by-zero NaN"
        );
        assert_eq!(small.width, huge.width);
        assert_eq!(small.height, huge.height);
    }
    // -----------------------------------------------------------------
    // ParsedFont::get_hyphen_glyph_and_advance / get_kashida_glyph_and_advance
    // -----------------------------------------------------------------
    #[test]
    fn get_hyphen_glyph_and_advance_follows_the_cmap_and_scales_linearly() {
        let font = mock();
        let expected_gid = font
            .lookup_glyph_index('-' as u32)
            .expect("the positive control has a hyphen");
        let (gid, zero_advance) = font
            .get_hyphen_glyph_and_advance(0.0)
            .expect("hyphen at 0px");
        assert_eq!(gid, expected_gid);
        assert_eq!(zero_advance, 0.0, "a 0px font gives a 0px advance");
        let (_, a16) = font
            .get_hyphen_glyph_and_advance(16.0)
            .expect("hyphen at 16px");
        let (_, a32) = font
            .get_hyphen_glyph_and_advance(32.0)
            .expect("hyphen at 32px");
        assert!(a16 > 0.0 && a16.is_finite());
        assert!(
            (a32 - 2.0 * a16).abs() <= 1e-3 * a16,
            "advance is linear in font size"
        );
        let (_, negative) = font
            .get_hyphen_glyph_and_advance(-16.0)
            .expect("hyphen at -16px");
        assert!(negative.is_finite() && negative <= 0.0);
    }
    #[test]
    fn get_kashida_glyph_and_advance_presence_matches_the_cmap() {
        let font = mock();
        // U+0640 ARABIC TATWEEL: present or not, the two views must agree.
        let has_tatweel = font.has_glyph(0x0640);
        let result = font.get_kashida_glyph_and_advance(16.0);
        assert_eq!(
            result.is_some(),
            has_tatweel,
            "kashida availability must track the cmap"
        );
        if let Some((gid, advance)) = result {
            assert_eq!(Some(gid), font.lookup_glyph_index(0x0640));
            assert!(advance.is_finite() && advance >= 0.0);
            let (_, doubled) = font
                .get_kashida_glyph_and_advance(32.0)
                .expect("still mapped");
            assert!((doubled - 2.0 * advance).abs() <= 1e-3 * advance.max(1.0));
        }
    }
    #[test]
    fn hyphen_and_kashida_survive_nan_inf_and_extreme_font_sizes() {
        let font = mock();
        let hyphen_gid = font
            .lookup_glyph_index('-' as u32)
            .expect("the positive control has a hyphen");
        assert!(
            font.get_horizontal_advance(hyphen_gid) > 0,
            "the hyphen must have a non-zero advance for this test to mean anything"
        );
        // NaN / ±inf in -> non-finite out, and never a panic.
        for size in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            let (gid, advance) = font
                .get_hyphen_glyph_and_advance(size)
                .expect("the glyph id does not depend on the font size");
            assert_eq!(gid, hyphen_gid);
            assert!(!advance.is_finite(), "{size} produced a finite advance");
            let _ = font.get_kashida_glyph_and_advance(size);
        }
        // The numeric extremes may overflow to ±inf, but a non-NaN size must
        // never produce a NaN advance and must never panic.
        for size in [f32::MAX, -f32::MAX, f32::MIN_POSITIVE, -f32::MIN_POSITIVE] {
            let (gid, advance) = font
                .get_hyphen_glyph_and_advance(size)
                .expect("the glyph id does not depend on the font size");
            assert_eq!(gid, hyphen_gid);
            assert!(!advance.is_nan(), "size {size} produced a NaN advance");
            let _ = font.get_kashida_glyph_and_advance(size);
        }
    }
    #[test]
    fn hyphen_and_kashida_return_none_when_units_per_em_is_zero() {
        let mut font = mock();
        font.font_metrics.units_per_em = 0;
        // A zero upem would divide by zero: both getters must bail out instead.
        assert!(font.get_hyphen_glyph_and_advance(16.0).is_none());
        assert!(font.get_kashida_glyph_and_advance(16.0).is_none());
        assert!(font.get_hyphen_glyph_and_advance(f32::NAN).is_none());
    }
    // -----------------------------------------------------------------
    // build_feature_mask_for_script (other)
    // -----------------------------------------------------------------
    #[test]
    fn build_feature_mask_always_contains_the_default_mask() {
        let default_bits = FeatureMask::default_mask().bits();
        for script in ALL_SCRIPTS {
            let mask = build_feature_mask_for_script(script);
            assert_eq!(
                mask.bits() & default_bits,
                default_bits,
                "{script:?} dropped a default feature"
            );
            assert!(
                mask.contains(Feature::LIGA) && mask.contains(Feature::CCMP),
                "{script:?} must keep LIGA/CCMP"
            );
        }
    }
    #[test]
    fn build_feature_mask_adds_the_script_specific_features() {
        // Arabic needs positional forms, or cursive joining silently breaks.
        let arabic = build_feature_mask_for_script(Script::Arabic);
        for feature in [Feature::INIT, Feature::MEDI, Feature::FINA, Feature::ISOL] {
            assert!(
                arabic.contains(feature),
                "Arabic is missing a positional form"
            );
        }
        // Indic needs conjunct formation.
        for script in [
            Script::Devanagari,
            Script::Bengali,
            Script::Gujarati,
            Script::Gurmukhi,
            Script::Kannada,
            Script::Malayalam,
            Script::Oriya,
            Script::Tamil,
            Script::Telugu,
        ] {
            let mask = build_feature_mask_for_script(script);
            for feature in [Feature::CJCT, Feature::HALF, Feature::RPHF, Feature::NUKT] {
                assert!(
                    mask.contains(feature),
                    "{script:?} is missing an Indic feature"
                );
            }
        }
        // Sinhala is Indic-derived but explicitly simpler: no conjunct feature.
        let sinhala = build_feature_mask_for_script(Script::Sinhala);
        assert!(sinhala.contains(Feature::AKHN) && sinhala.contains(Feature::RPHF));
        assert!(!sinhala.contains(Feature::CJCT));
        // Myanmar/Khmer get pre/below/post-base forms.
        assert!(build_feature_mask_for_script(Script::Myanmar).contains(Feature::PSTF));
        assert!(build_feature_mask_for_script(Script::Khmer).contains(Feature::ABVF));
        // Simple scripts must be exactly the default mask — no accidental extras.
        for script in [
            Script::Latin,
            Script::Greek,
            Script::Cyrillic,
            Script::Georgian,
        ] {
            assert_eq!(
                build_feature_mask_for_script(script).bits(),
                FeatureMask::default_mask().bits(),
                "{script:?} must not add script-specific features"
            );
        }
    }
    // -----------------------------------------------------------------
    // to_opentype_script_tag (other)
    // -----------------------------------------------------------------
    #[test]
    fn script_tags_are_four_printable_ascii_bytes() {
        for script in ALL_SCRIPTS {
            let tag = to_opentype_script_tag(script);
            let bytes = tag.to_be_bytes();
            assert_eq!(bytes.len(), 4);
            for b in bytes {
                assert!(
                    b.is_ascii_lowercase() || b.is_ascii_digit(),
                    "{script:?} -> {tag:#010x} is not a lowercase OpenType tag"
                );
            }
            assert_ne!(tag, 0, "{script:?} must not map to the null tag");
        }
    }
    #[test]
    fn script_tags_match_the_opentype_registry_and_alias_kana() {
        assert_eq!(
            to_opentype_script_tag(Script::Latin),
            u32::from_be_bytes(*b"latn")
        );
        assert_eq!(
            to_opentype_script_tag(Script::Arabic),
            u32::from_be_bytes(*b"arab")
        );
        assert_eq!(
            to_opentype_script_tag(Script::Mandarin),
            u32::from_be_bytes(*b"hani")
        );
        assert_eq!(
            to_opentype_script_tag(Script::Devanagari),
            u32::from_be_bytes(*b"deva")
        );
        // Hiragana and Katakana intentionally share "kana" (documented).
        assert_eq!(
            to_opentype_script_tag(Script::Hiragana),
            to_opentype_script_tag(Script::Katakana)
        );
        assert_eq!(
            to_opentype_script_tag(Script::Hiragana),
            u32::from_be_bytes(*b"kana")
        );
        // Every other pair must be distinct: 24 scripts, 23 distinct tags.
        let mut tags: Vec<u32> = ALL_SCRIPTS
            .iter()
            .map(|s| to_opentype_script_tag(*s))
            .collect();
        tags.sort_unstable();
        tags.dedup();
        assert_eq!(tags.len(), 23, "only the kana pair may collide");
    }
    // -----------------------------------------------------------------
    // parse_font_feature (parser)
    // -----------------------------------------------------------------
    #[test]
    fn parse_font_feature_valid_minimal_inputs() {
        assert_eq!(
            parse_font_feature("liga"),
            Some((u32::from_be_bytes(*b"liga"), 1)),
            "a bare tag defaults to value 1"
        );
        assert_eq!(
            parse_font_feature("liga=0"),
            Some((u32::from_be_bytes(*b"liga"), 0))
        );
        assert_eq!(
            parse_font_feature("ss01"),
            Some((u32::from_be_bytes(*b"ss01"), 1))
        );
        assert_eq!(
            parse_font_feature("smcp=2"),
            Some((u32::from_be_bytes(*b"smcp"), 2))
        );
        // u32::MAX is the largest accepted value
        assert_eq!(
            parse_font_feature("ss01=4294967295"),
            Some((u32::from_be_bytes(*b"ss01"), u32::MAX))
        );
    }
    #[test]
    fn parse_font_feature_pads_short_tags_with_spaces() {
        assert_eq!(
            parse_font_feature("aa"),
            Some((u32::from_be_bytes(*b"aa  "), 1))
        );
        assert_eq!(
            parse_font_feature("a"),
            Some((u32::from_be_bytes(*b"a   "), 1))
        );
        assert_eq!(
            parse_font_feature("abc=3"),
            Some((u32::from_be_bytes(*b"abc "), 3))
        );
    }
    #[test]
    fn parse_font_feature_trims_surrounding_whitespace() {
        assert_eq!(
            parse_font_feature("  liga  "),
            Some((u32::from_be_bytes(*b"liga"), 1))
        );
        assert_eq!(
            parse_font_feature("\tliga\n=\t2 "),
            Some((u32::from_be_bytes(*b"liga"), 2))
        );
    }
    #[test]
    fn parse_font_feature_empty_and_whitespace_only_yield_the_all_space_tag() {
        // Documents current behaviour: an empty/blank tag is NOT rejected — it is
        // padded to the four-space tag (0x20202020), which no font can match.
        let space_tag = u32::from_be_bytes(*b"    ");
        assert_eq!(parse_font_feature(""), Some((space_tag, 1)));
        assert_eq!(parse_font_feature("   "), Some((space_tag, 1)));
        assert_eq!(parse_font_feature("\t\n"), Some((space_tag, 1)));
        // ...but an empty *value* is still rejected.
        assert_eq!(parse_font_feature("="), None);
        assert_eq!(parse_font_feature("liga="), None);
        assert_eq!(parse_font_feature("liga=  "), None);
    }
    #[test]
    fn parse_font_feature_rejects_over_long_tags_and_junk() {
        assert_eq!(parse_font_feature("toolongtag"), None);
        assert_eq!(parse_font_feature("lig a"), None); // 5 bytes after trim
        assert_eq!(parse_font_feature("liga;garbage"), None);
        assert_eq!(parse_font_feature("valid;garbage=1"), None);
        // a megabyte-long tag must be rejected by the length check, not parsed
        assert_eq!(parse_font_feature(&"x".repeat(1_000_000)), None);
        assert_eq!(
            parse_font_feature(&format!("{}=1", "x".repeat(1_000_000))),
            None
        );
    }
    #[test]
    fn parse_font_feature_rejects_boundary_and_non_numeric_values() {
        for bad in [
            "liga=-1",
            "liga=-0",
            "liga=1.5",
            "liga=NaN",
            "liga=inf",
            "liga=0x1",
            "liga=4294967296",          // u32::MAX + 1
            "liga=9223372036854775807", // i64::MAX
            "liga=99999999999999999999999999",
            "liga= 1 2",
        ] {
            assert_eq!(parse_font_feature(bad), None, "{bad:?} must be rejected");
        }
        // `u32::from_str` accepts a leading '+', so this one is (surprisingly) valid
        assert_eq!(
            parse_font_feature("liga=+1"),
            Some((u32::from_be_bytes(*b"liga"), 1))
        );
        // a trailing extra '=' segment is ignored: only the first value is read
        assert_eq!(
            parse_font_feature("liga=1=2"),
            Some((u32::from_be_bytes(*b"liga"), 1))
        );
    }
    #[test]
    fn parse_font_feature_unicode_input_does_not_panic() {
        // Multibyte tags pad by *chars* but the tag must be exactly 4 *bytes*,
        // so every one of these must fall out as None rather than slicing a
        // char boundary or panicking on the array conversion.
        for input in [
            "\u{1F600}", // 4 bytes, 1 char
            "\u{1F600}\u{1F600}",
            "é",
            "ß=1",
            "e\u{0301}",    // combining acute
            "\u{202E}liga", // RTL override
            "\u{0000}\u{0001}",
        ] {
            let _ = parse_font_feature(input); // must not panic
        }
        assert_eq!(parse_font_feature("\u{1F600}"), None);
        assert_eq!(parse_font_feature("é"), None);
    }
    // -----------------------------------------------------------------
    // add_variant_features (other)
    // -----------------------------------------------------------------
    #[test]
    fn add_variant_features_maps_css_variants_to_opentype_tags() {
        let tags = |style: &StyleProperties| -> Vec<u32> {
            let mut features = Vec::new();
            add_variant_features(style, &mut features);
            assert!(
                features.iter().all(|f| f.alternate.is_none()),
                "variant features are on/off, never alternates"
            );
            features.iter().map(|f| f.feature_tag).collect()
        };
        // the default style adds nothing
        assert!(tags(&StyleProperties::default()).is_empty());
        let small_caps = StyleProperties {
            font_variant_caps: FontVariantCaps::SmallCaps,
            ..StyleProperties::default()
        };
        assert_eq!(tags(&small_caps), vec![u32::from_be_bytes(*b"smcp")]);
        let all_small = StyleProperties {
            font_variant_caps: FontVariantCaps::AllSmallCaps,
            ..StyleProperties::default()
        };
        assert_eq!(
            tags(&all_small),
            vec![u32::from_be_bytes(*b"c2sc"), u32::from_be_bytes(*b"smcp")]
        );
        let combined = StyleProperties {
            font_variant_ligatures: FontVariantLigatures::Discretionary,
            font_variant_numeric: FontVariantNumeric::TabularNums,
            font_variant_caps: FontVariantCaps::TitlingCaps,
            ..StyleProperties::default()
        };
        assert_eq!(
            tags(&combined),
            vec![
                u32::from_be_bytes(*b"dlig"),
                u32::from_be_bytes(*b"titl"),
                u32::from_be_bytes(*b"tnum"),
            ],
            "ligature, caps and numeric features are all emitted, in that order"
        );
    }
    #[test]
    fn add_variant_features_is_additive_and_never_panics_for_any_variant() {
        let ligatures = [
            FontVariantLigatures::Normal,
            FontVariantLigatures::None,
            FontVariantLigatures::Common,
            FontVariantLigatures::NoCommon,
            FontVariantLigatures::Discretionary,
            FontVariantLigatures::NoDiscretionary,
            FontVariantLigatures::Historical,
            FontVariantLigatures::NoHistorical,
            FontVariantLigatures::Contextual,
            FontVariantLigatures::NoContextual,
        ];
        let caps = [
            FontVariantCaps::Normal,
            FontVariantCaps::SmallCaps,
            FontVariantCaps::AllSmallCaps,
            FontVariantCaps::PetiteCaps,
            FontVariantCaps::AllPetiteCaps,
            FontVariantCaps::Unicase,
            FontVariantCaps::TitlingCaps,
        ];
        let numeric = [
            FontVariantNumeric::Normal,
            FontVariantNumeric::LiningNums,
            FontVariantNumeric::OldstyleNums,
            FontVariantNumeric::ProportionalNums,
            FontVariantNumeric::TabularNums,
            FontVariantNumeric::DiagonalFractions,
            FontVariantNumeric::StackedFractions,
            FontVariantNumeric::Ordinal,
            FontVariantNumeric::SlashedZero,
        ];
        // a pre-existing feature must survive: the helper appends, never clears
        let sentinel = FeatureInfo {
            feature_tag: u32::from_be_bytes(*b"kern"),
            alternate: Some(7),
        };
        for l in ligatures {
            for c in caps {
                for n in numeric {
                    let style = StyleProperties {
                        font_variant_ligatures: l,
                        font_variant_caps: c,
                        font_variant_numeric: n,
                        ..StyleProperties::default()
                    };
                    let mut features = vec![sentinel];
                    add_variant_features(&style, &mut features);
                    assert_eq!(features[0].feature_tag, sentinel.feature_tag);
                    assert_eq!(features[0].alternate, Some(7));
                    // at most 2 (caps) + 1 (ligature) + 1 (numeric) new tags
                    assert!(
                        features.len() <= 5,
                        "{l:?}/{c:?}/{n:?} emitted too many features"
                    );
                    for f in &features[1..] {
                        assert!(f.feature_tag.to_be_bytes().iter().all(u8::is_ascii_graphic));
                    }
                }
            }
        }
    }
    // -----------------------------------------------------------------
    // to_opentype_lang_tag (other, feature-gated)
    // -----------------------------------------------------------------
    #[cfg(feature = "text_layout_hyphenation")]
    #[test]
    fn lang_tags_are_four_byte_uppercase_padded_tags() {
        use hyphenation::Language as HL;
        // A representative spread across the mapping table, including the two
        // arms that intentionally share a tag.
        let sample = [
            HL::EnglishUS,
            HL::EnglishGB,
            HL::German1901,
            HL::German1996,
            HL::French,
            HL::Russian,
            HL::Finnish,
            HL::FinnishScholastic,
            HL::Latin,
            HL::LatinClassic,
            HL::Welsh,
            HL::Thai,
        ];
        for lang in sample {
            let tag = to_opentype_lang_tag(lang);
            let bytes = tag.to_be_bytes();
            for b in bytes {
                assert!(
                    b.is_ascii_uppercase() || b == b' ',
                    "{lang:?} -> {tag:#010x} is not an uppercase, space-padded tag"
                );
            }
            assert_ne!(tag, 0);
        }
        assert_eq!(
            to_opentype_lang_tag(HL::EnglishUS),
            u32::from_be_bytes(*b"ENU ")
        );
        assert_eq!(
            to_opentype_lang_tag(HL::EnglishGB),
            u32::from_be_bytes(*b"ENG ")
        );
        assert_eq!(
            to_opentype_lang_tag(HL::German1996),
            u32::from_be_bytes(*b"DEU ")
        );
        assert_eq!(
            to_opentype_lang_tag(HL::French),
            u32::from_be_bytes(*b"FRA ")
        );
        assert_eq!(
            to_opentype_lang_tag(HL::Russian),
            u32::from_be_bytes(*b"RUS ")
        );
        // documented aliases: both German orthographies and both Finnish variants
        assert_eq!(
            to_opentype_lang_tag(HL::German1901),
            to_opentype_lang_tag(HL::German1996)
        );
        assert_eq!(
            to_opentype_lang_tag(HL::Finnish),
            to_opentype_lang_tag(HL::FinnishScholastic)
        );
    }
    // -----------------------------------------------------------------
    // FontRef trait surface: delegation invariants
    // -----------------------------------------------------------------
    #[test]
    fn font_ref_trait_getters_delegate_to_the_inner_parsed_font() {
        let parsed = mock();
        let font_ref = crate::parsed_font_to_font_ref(mock());
        assert_eq!(font_ref.num_glyphs(), parsed.num_glyphs);
        assert_eq!(font_ref.get_space_width(), parsed.get_space_width());
        assert_eq!(
            font_ref.get_font_metrics().units_per_em,
            parsed.font_metrics.units_per_em
        );
        assert!(font_ref.has_glyph('a' as u32) == parsed.has_glyph('a' as u32));
        assert!(
            !font_ref.has_glyph(0x0011_0000),
            "an invalid scalar value has no glyph"
        );
        let gid = parsed
            .lookup_glyph_index('a' as u32)
            .expect("'a' must be mapped");
        let via_ref = font_ref.get_glyph_size(gid, 16.0).expect("gid decodes");
        let via_parsed = parsed.get_glyph_size(gid, 16.0).expect("gid decodes");
        assert_eq!(via_ref.width, via_parsed.width);
        assert_eq!(via_ref.height, via_parsed.height);
        assert_eq!(
            font_ref.get_hyphen_glyph_and_advance(16.0).map(|(g, _)| g),
            parsed.get_hyphen_glyph_and_advance(16.0).map(|(g, _)| g)
        );
        assert_eq!(
            font_ref.get_kashida_glyph_and_advance(16.0).map(|(g, _)| g),
            parsed.get_kashida_glyph_and_advance(16.0).map(|(g, _)| g)
        );
        // shallow_clone shares the same underlying face
        let cloned = font_ref.shallow_clone();
        assert_eq!(cloned.get_hash(), font_ref.get_hash());
    }
}