text-typeset 3.4.1

Turns rich text documents into GPU-ready glyph quads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::OnceLock;

use fontdb::{Database, Family, Query, Source, Stretch, Style, Weight};

use crate::font::color::ColorTables;
use crate::font::hinted::{GlyphRendering, HintCache};
use crate::font::script_fallback::{CjkLanguage, Platform};
use crate::font::synthesis::FaceSynthesis;
use crate::font::writing_system_index::{
    FaceBytes, FaceRef, WritingSystemIndexBuilder, build_from_faces,
};
use crate::types::FontFaceId;

/// Summary of one installed font family, for building a font picker.
///
/// `name` is the primary (English, where available) family name; faces of
/// different weights/styles are collapsed into one entry. `monospaced` is
/// true when any face of the family is monospaced — read straight from
/// fontdb metadata, so producing a whole [`Vec<FontFamilyInfo>`] loads no
/// font bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct FontFamilyInfo {
    /// Primary family name (e.g. `"DejaVu Sans"`).
    pub name: String,
    /// True if any face of the family is monospaced.
    pub monospaced: bool,
}

impl FontFamilyInfo {
    /// A family entry, for a host that lists families of its own (a font
    /// picker given a fixed list, a test).
    pub fn new(name: impl Into<String>, monospaced: bool) -> Self {
        Self {
            name: name.into(),
            monospaced,
        }
    }
}

/// Byte container owned by a [`FontEntry`]. Erased behind a trait
/// object so the registry can hold any of `Vec<u8>`, `memmap2::Mmap`,
/// or `&'static [u8]` (via a wrapper) without copying. fontdb's
/// `Source::Binary` uses the same shape, so the same `Arc` can be
/// shared with the database.
pub type SharedFontData = Arc<dyn AsRef<[u8]> + Sync + Send>;

/// Backing bytes for a [`FontEntry`].
///
/// Explicitly registered fonts are [`Resident`](FontData::Resident) — the
/// caller handed us the bytes. System fonts discovered by
/// [`load_system_fonts`](FontRegistry::new) are [`Lazy`](FontData::Lazy):
/// we keep only the file path until the face is actually shaped or queried
/// for coverage, then read and cache it. This keeps `new()` cheap even
/// when the OS has hundreds of installed faces.
enum FontData {
    Resident(SharedFontData),
    Lazy {
        path: PathBuf,
        cell: OnceLock<SharedFontData>,
    },
}

pub struct FontEntry {
    pub fontdb_id: fontdb::ID,
    pub face_index: u32,
    data: FontData,
    pub swash_cache_key: swash::CacheKey,
    /// True for faces discovered via the OS font enumeration. Glyph
    /// fallback prefers explicitly-registered faces and only reaches for
    /// system faces as a last resort (see
    /// [`find_fallback_font`](crate::font::resolve::find_fallback_font)).
    pub is_system: bool,
    /// Lazily-opened harfrust font for this face. It shares this entry's
    /// byte `Arc` (no copy) and caches the preprocessed GSUB/GPOS/cmap
    /// tables inside itself, so it is opened once and reused across every
    /// shape call. Built on first shape via
    /// [`shaping_font`](Self::shaping_font); `None` if the bytes hold no
    /// usable face. `OnceLock` keeps `FontEntry` `Sync`.
    shaping_font: OnceLock<Option<harfrust::Font>>,
    /// The face's colour tables, read on first use by glyph fallback or the
    /// rasterizer (see [`crate::font::color`]).
    color_tables: OnceLock<ColorTables>,
    /// The face's weight and slant, read on first use by the shaper (see
    /// [`crate::font::synthesis`]).
    synthesis: OnceLock<FaceSynthesis>,
    /// Hinting instances and hinted advances for
    /// [`GlyphRendering::Crisp`], built on first use.
    hint_cache: HintCache,
}

impl FontEntry {
    /// Borrow the underlying font bytes, loading them from disk on first
    /// use for lazily-tracked system faces. Returns an empty slice if a
    /// system font file can no longer be read (uninstalled mid-session);
    /// shaping then degrades gracefully to `None`/`.notdef`.
    pub fn bytes(&self) -> &[u8] {
        // Two `as_ref()` hops: Arc<dyn AsRef<[u8]>> → dyn → &[u8].
        (**self.shared_data()).as_ref()
    }

    /// The shared byte container, loading it from disk on first use for
    /// lazily-tracked system faces (see [`bytes`](Self::bytes)).
    fn shared_data(&self) -> &SharedFontData {
        match &self.data {
            FontData::Resident(data) => data,
            FontData::Lazy { path, cell } => cell.get_or_init(|| {
                let bytes = std::fs::read(path).unwrap_or_default();
                Arc::new(bytes) as SharedFontData
            }),
        }
    }

    /// Borrow this face's harfrust font, opening it on first use.
    ///
    /// Opening preprocesses the font tables; doing it once per face
    /// (instead of once per shape call) avoids redundant work on every
    /// relayout/keystroke. `None` if the bytes hold no usable face.
    pub fn shaping_font(&self) -> Option<&harfrust::Font> {
        self.shaping_font
            .get_or_init(|| harfrust::Font::new(self.shared_data().clone(), self.face_index))
            .as_ref()
    }

    /// What this face can draw for real and what is synthesized on it (see
    /// [`crate::font::synthesis`]), read on first use.
    pub(crate) fn synthesis(&self) -> FaceSynthesis {
        *self
            .synthesis
            .get_or_init(|| FaceSynthesis::read(self.bytes(), self.face_index))
    }

    /// This face's crisp hinting state (see [`GlyphRendering::Crisp`]).
    pub(crate) fn hint_cache(&self) -> &HintCache {
        &self.hint_cache
    }

    /// This face's colour tables, read on first use.
    pub(crate) fn color_tables(&self) -> &ColorTables {
        self.color_tables
            .get_or_init(|| ColorTables::read(self.bytes(), self.face_index))
    }
}

pub struct FontRegistry {
    fontdb: Database,
    fonts: Vec<Option<FontEntry>>,
    /// fontdb face ID → our `FontFaceId`, so `query_font` doesn't scan
    /// `fonts` linearly (it can hold hundreds of system faces).
    fontdb_index: HashMap<fontdb::ID, FontFaceId>,
    generic_families: HashMap<String, String>,
    default_font: Option<FontFaceId>,
    default_size_px: f32,
    /// The language Han is drawn for when nothing in its text says (see
    /// [`crate::font::script_fallback`]).
    default_language: Option<CjkLanguage>,
    /// Whose faces the fallback table names: this system's, or another's in
    /// a test.
    fallback_platform: Platform,
    /// How glyphs are fitted to the pixel grid, for shaping and drawing.
    glyph_rendering: GlyphRendering,
}

impl Default for FontRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl FontRegistry {
    /// Create a registry pre-populated with the operating system's fonts.
    ///
    /// OS faces participate in family lookup and glyph fallback so that
    /// arbitrary documents (CJK, emoji, scripts the host didn't bundle)
    /// still render. Their bytes load lazily on first use, but the
    /// enumeration itself scans the OS font directories — a one-time
    /// startup cost. Use [`new_without_system_fonts`](Self::new_without_system_fonts)
    /// when the host ships a controlled font set and wants neither the
    /// scan nor implicit OS fonts.
    pub fn new() -> Self {
        let mut registry = Self::new_without_system_fonts();
        registry.load_system_fonts();
        registry
    }

    /// Create an empty registry with no system fonts. Fonts enter only
    /// via the `register_font*` methods.
    pub fn new_without_system_fonts() -> Self {
        Self {
            fontdb: Database::new(),
            fonts: Vec::new(),
            fontdb_index: HashMap::new(),
            generic_families: HashMap::new(),
            default_font: None,
            default_size_px: 16.0,
            default_language: None,
            fallback_platform: Platform::CURRENT,
            glyph_rendering: GlyphRendering::Natural,
        }
    }

    /// Enumerate OS fonts into `fontdb` and register a lazy [`FontEntry`]
    /// for each so they join family lookup and the fallback chain. Bytes
    /// load on first access; only the file path is kept until then.
    fn load_system_fonts(&mut self) {
        self.fontdb.load_system_fonts();

        // Collect first: `faces()` borrows `self.fontdb` immutably while
        // the loop needs `&mut self` to push entries.
        let discovered: Vec<(fontdb::ID, u32, PathBuf)> = self
            .fontdb
            .faces()
            .filter_map(|f| match &f.source {
                Source::File(path) => Some((f.id, f.index, path.clone())),
                Source::SharedFile(path, _) => Some((f.id, f.index, path.clone())),
                Source::Binary(_) => None,
            })
            .collect();

        for (fontdb_id, face_index, path) in discovered {
            if self.fontdb_index.contains_key(&fontdb_id) {
                continue;
            }
            let entry = FontEntry {
                fontdb_id,
                face_index,
                data: FontData::Lazy {
                    path,
                    cell: OnceLock::new(),
                },
                swash_cache_key: swash::CacheKey::new(),
                is_system: true,
                shaping_font: OnceLock::new(),
                color_tables: OnceLock::new(),
                synthesis: OnceLock::new(),
                hint_cache: HintCache::default(),
            };
            let face_id = FontFaceId(self.fonts.len() as u32);
            self.fonts.push(Some(entry));
            self.fontdb_index.insert(fontdb_id, face_id);
        }
    }

    /// Register a font from raw bytes. Returns IDs for all faces found
    /// (font collections may contain multiple faces).
    ///
    /// This copies the bytes into an owned `Vec<u8>`. For large fonts
    /// where the caller already holds the data in a shareable
    /// container (e.g. an `Arc<Mmap>` for a system emoji font), use
    /// [`register_font_shared`](Self::register_font_shared) instead to
    /// avoid the copy.
    pub fn register_font(&mut self, data: &[u8]) -> Vec<FontFaceId> {
        let arc_data: SharedFontData = Arc::new(data.to_vec());
        self.register_font_shared(arc_data)
    }

    /// Register a font from a pre-built shared byte container,
    /// avoiding the copy that [`register_font`](Self::register_font)
    /// would perform.
    ///
    /// The shared container is held by every resulting [`FontEntry`]
    /// and by fontdb's `Source::Binary`. Drop it after the registry
    /// drops the entries.
    pub fn register_font_shared(&mut self, data: SharedFontData) -> Vec<FontFaceId> {
        let source = Source::Binary(data.clone());
        let fontdb_ids = self.fontdb.load_font_source(source);

        let mut face_ids = Vec::new();
        for fontdb_id in fontdb_ids {
            let face_index = self.fontdb.face(fontdb_id).map(|f| f.index).unwrap_or(0);

            let swash_cache_key = swash::CacheKey::new();
            let entry = FontEntry {
                fontdb_id,
                face_index,
                data: FontData::Resident(data.clone()),
                swash_cache_key,
                is_system: false,
                shaping_font: OnceLock::new(),
                color_tables: OnceLock::new(),
                synthesis: OnceLock::new(),
                hint_cache: HintCache::default(),
            };

            let face_id = FontFaceId(self.fonts.len() as u32);
            self.fonts.push(Some(entry));
            self.fontdb_index.insert(fontdb_id, face_id);
            face_ids.push(face_id);
        }
        face_ids
    }

    /// Register a font with explicit metadata, overriding the font's name table.
    pub fn register_font_as(
        &mut self,
        data: &[u8],
        family: &str,
        weight: u16,
        italic: bool,
    ) -> Vec<FontFaceId> {
        let arc_data: SharedFontData = Arc::new(data.to_vec());
        self.register_font_shared_as(arc_data, family, weight, italic)
    }

    /// Like [`register_font_as`](Self::register_font_as) but takes a
    /// pre-built shared byte container, avoiding the copy.
    pub fn register_font_shared_as(
        &mut self,
        data: SharedFontData,
        family: &str,
        weight: u16,
        italic: bool,
    ) -> Vec<FontFaceId> {
        let source = Source::Binary(data.clone());
        let fontdb_ids = self.fontdb.load_font_source(source);

        let mut face_ids = Vec::new();
        for fontdb_id in fontdb_ids {
            // Override metadata in fontdb
            if let Some(face_info) = self.fontdb.face(fontdb_id) {
                let mut info = face_info.clone();
                info.families = vec![(family.to_string(), fontdb::Language::English_UnitedStates)];
                info.weight = Weight(weight);
                info.style = if italic { Style::Italic } else { Style::Normal };
                // Remove old and re-add with new metadata
                let face_index = info.index;
                self.fontdb.remove_face(fontdb_id);
                let new_id = self.fontdb.push_face_info(info);

                let swash_cache_key = swash::CacheKey::new();
                let entry = FontEntry {
                    fontdb_id: new_id,
                    face_index,
                    data: FontData::Resident(data.clone()),
                    swash_cache_key,
                    is_system: false,
                    shaping_font: OnceLock::new(),
                    color_tables: OnceLock::new(),
                    synthesis: OnceLock::new(),
                    hint_cache: HintCache::default(),
                };

                let face_id = FontFaceId(self.fonts.len() as u32);
                self.fonts.push(Some(entry));
                self.fontdb_index.insert(new_id, face_id);
                face_ids.push(face_id);
            }
        }
        face_ids
    }

    pub fn set_default_font(&mut self, face: FontFaceId, size_px: f32) {
        self.default_font = Some(face);
        self.default_size_px = size_px;
    }

    pub fn default_font(&self) -> Option<FontFaceId> {
        self.default_font
    }

    pub fn default_size_px(&self) -> f32 {
        self.default_size_px
    }

    /// Set the language Han characters are drawn for when neither their
    /// block nor the kana or hangul around them says (see
    /// [`TextFontService::set_default_language`](crate::TextFontService::set_default_language)).
    /// Returns whether the language changed.
    pub(crate) fn set_default_language(&mut self, language: Option<&str>) -> bool {
        let language = language.and_then(CjkLanguage::from_tag);
        let changed = language != self.default_language;
        self.default_language = language;
        changed
    }

    /// Set how glyphs are fitted to the pixel grid; whether it changed.
    pub(crate) fn set_glyph_rendering(&mut self, rendering: GlyphRendering) -> bool {
        let changed = rendering != self.glyph_rendering;
        self.glyph_rendering = rendering;
        changed
    }

    /// How glyphs are fitted to the pixel grid.
    pub fn glyph_rendering(&self) -> GlyphRendering {
        self.glyph_rendering
    }

    pub(crate) fn default_language(&self) -> Option<CjkLanguage> {
        self.default_language
    }

    pub(crate) fn fallback_platform(&self) -> Platform {
        self.fallback_platform
    }

    #[cfg(test)]
    pub(crate) fn set_fallback_platform(&mut self, platform: Platform) {
        self.fallback_platform = platform;
    }

    /// Count a registered face as one the system scan found, as a test's
    /// stand-in for an installed font.
    #[cfg(test)]
    pub(crate) fn treat_as_system(&mut self, face_id: FontFaceId) {
        if let Some(Some(entry)) = self.fonts.get_mut(face_id.0 as usize) {
            entry.is_system = true;
        }
    }

    pub fn set_generic_family(&mut self, generic: &str, family: &str) {
        self.generic_families
            .insert(generic.to_string(), family.to_string());
    }

    /// Resolve a family name, mapping generic names (serif, monospace, etc.)
    /// to their configured concrete family names.
    pub fn resolve_family_name<'a>(&'a self, family: &'a str) -> &'a str {
        self.generic_families
            .get(family)
            .map(|s| s.as_str())
            .unwrap_or(family)
    }

    /// Query fontdb for a font matching the given criteria.
    pub fn query_font(&self, family: &str, weight: u16, italic: bool) -> Option<FontFaceId> {
        let resolved = self.resolve_family_name(family);
        let style = if italic { Style::Italic } else { Style::Normal };

        let query = Query {
            families: &[Family::Name(resolved)],
            weight: Weight(weight),
            style,
            ..Query::default()
        };

        let fontdb_id = self.fontdb.query(&query)?;
        self.fontdb_id_to_face_id(fontdb_id)
    }

    /// Look up the family name of a registered font.
    pub fn font_family_name(&self, face_id: FontFaceId) -> Option<String> {
        let entry = self.get(face_id)?;
        let face_info = self.fontdb.face(entry.fontdb_id)?;
        face_info.families.first().map(|(name, _)| name.clone())
    }

    /// The weight fontdb read for a face (its OS/2 weight class).
    pub(crate) fn fontdb_weight(&self, fontdb_id: fontdb::ID) -> Option<u16> {
        self.fontdb.face(fontdb_id).map(|info| info.weight.0)
    }

    /// The style and width (stretch) of `face_id`, from fontdb's metadata.
    pub(crate) fn face_style(&self, face_id: FontFaceId) -> Option<(Style, Stretch)> {
        let info = self.fontdb.face(self.get(face_id)?.fontdb_id)?;
        Some((info.style, info.stretch))
    }

    /// The face of `face_id`'s family that fontdb's CSS matching picks for
    /// `weight`, `style` and `stretch`: the family's Regular for regular
    /// text, its Bold for bold. Reads metadata only.
    ///
    /// Glyph fallback finds a face by the first one that covers a character,
    /// in the order the system lists its font files, and a family's Bold file
    /// can come first (BIZ-UDGothicB.ttc sorts before BIZ-UDGothicR.ttc on
    /// Windows): regular CJK text was set in bold beside regular Latin.
    pub(crate) fn family_face_matching(
        &self,
        face_id: FontFaceId,
        weight: u16,
        style: Style,
        stretch: Stretch,
    ) -> Option<FontFaceId> {
        let info = self.fontdb.face(self.get(face_id)?.fontdb_id)?;
        let (family, _) = info.families.first()?;
        let query = Query {
            families: &[Family::Name(family)],
            weight: Weight(weight),
            stretch,
            style,
        };
        self.fontdb_id_to_face_id(self.fontdb.query(&query)?)
    }

    /// The face of the family named `family` (any of its names, as fontdb
    /// read them) that fontdb's CSS matching picks for `weight`, `style` and
    /// `stretch`. Reads metadata only.
    pub(crate) fn family_face(
        &self,
        family: &str,
        weight: u16,
        style: Style,
        stretch: Stretch,
    ) -> Option<FontFaceId> {
        let query = Query {
            families: &[Family::Name(family)],
            weight: Weight(weight),
            stretch,
            style,
        };
        self.fontdb_id_to_face_id(self.fontdb.query(&query)?)
    }

    /// Whether a family name of `face_id` contains "emoji", ignoring case.
    /// Reads fontdb metadata only, so it opens no font file.
    pub(crate) fn is_emoji_family(&self, face_id: FontFaceId) -> bool {
        let Some(info) = self
            .get(face_id)
            .and_then(|e| self.fontdb.face(e.fontdb_id))
        else {
            return false;
        };
        info.families.iter().any(|(name, _)| {
            name.as_bytes()
                .windows(5)
                .any(|w| w.eq_ignore_ascii_case(b"emoji"))
        })
    }

    /// Look up a FontEntry by FontFaceId.
    pub fn get(&self, face_id: FontFaceId) -> Option<&FontEntry> {
        self.fonts
            .get(face_id.0 as usize)
            .and_then(|opt| opt.as_ref())
    }

    /// Query for a variant (different weight/style) of an existing registered font.
    /// Looks up the family name of `base_face` and queries fontdb for a match.
    pub fn query_variant(
        &self,
        base_face: FontFaceId,
        weight: u16,
        italic: bool,
    ) -> Option<FontFaceId> {
        let entry = self.get(base_face)?;
        let face_info = self.fontdb.face(entry.fontdb_id)?;
        let family_name = face_info.families.first().map(|(name, _)| name.as_str())?;
        self.query_font(family_name, weight, italic)
    }

    /// Find our FontFaceId for a fontdb ID.
    fn fontdb_id_to_face_id(&self, fontdb_id: fontdb::ID) -> Option<FontFaceId> {
        self.fontdb_index.get(&fontdb_id).copied()
    }

    /// Enumerate every installed font family, deduplicated (case-insensitive)
    /// and sorted (case-insensitive Unicode).
    ///
    /// Cheap: it reads only fontdb metadata (family name + monospaced flag),
    /// so no font file is opened. This is the item source for a font picker.
    /// Multiple faces of one family (Regular/Bold/Italic) collapse into a
    /// single entry, whose `monospaced` is true if any face is monospaced.
    pub fn families(&self) -> Vec<FontFamilyInfo> {
        // key = lowercased name (dedupe); value = (display name, monospaced).
        let mut map: HashMap<String, (String, bool)> = HashMap::new();
        for face in self.fontdb.faces() {
            // `families[0]` is the English (US) name where present.
            let Some((name, _)) = face.families.first() else {
                continue;
            };
            let entry = map
                .entry(name.to_lowercase())
                .or_insert_with(|| (name.clone(), false));
            entry.1 |= face.monospaced;
        }
        let mut out: Vec<FontFamilyInfo> = map
            .into_values()
            .map(|(name, monospaced)| FontFamilyInfo { name, monospaced })
            .collect();
        out.sort_by(|a, b| {
            a.name
                .to_lowercase()
                .cmp(&b.name.to_lowercase())
                .then_with(|| a.name.cmp(&b.name))
        });
        out
    }

    /// Enumerate installed font family names, deduplicated and sorted — the
    /// simple projection of [`families`](Self::families).
    pub fn family_names(&self) -> Vec<String> {
        self.families().into_iter().map(|f| f.name).collect()
    }

    /// True if any face of the named family is monospaced. Reads only fontdb
    /// metadata (no bytes loaded). Case-insensitive on the family name.
    pub fn family_is_monospaced(&self, family: &str) -> bool {
        let target = family.to_lowercase();
        self.fontdb.faces().any(|f| {
            f.monospaced
                && f.families
                    .first()
                    .is_some_and(|(n, _)| n.to_lowercase() == target)
        })
    }

    /// Build a `Send` snapshot of every family's face byte-sources, ready to
    /// be moved to a background thread and turned into a writing-system
    /// coverage map (see [`WritingSystemIndexBuilder`]).
    ///
    /// Cheap on the calling thread: it clones file paths / shares `Arc`s but
    /// reads no font bytes. The expensive OS/2 parsing happens in
    /// [`WritingSystemIndexBuilder::build`], which the caller runs
    /// off-thread.
    /// The coverage map is keyed by the **lowercased** family name so it
    /// aligns with [`families`](Self::families)' case-insensitive dedup —
    /// callers look up by `name.to_lowercase()`. (Faces of one family can
    /// disagree on name casing; a case-sensitive key would split or miss.)
    pub fn writing_system_index_builder(&self) -> WritingSystemIndexBuilder {
        build_from_faces(self.fontdb.faces().filter_map(|face| {
            let (family, _) = face.families.first()?;
            let bytes = match &face.source {
                Source::File(path) => FaceBytes::Path(path.clone()),
                Source::SharedFile(_, data) => FaceBytes::Shared(data.clone()),
                Source::Binary(data) => FaceBytes::Shared(data.clone()),
            };
            Some((
                family.to_lowercase(),
                FaceRef {
                    bytes,
                    index: face.index,
                },
            ))
        }))
    }

    /// Iterate all registered font entries for glyph fallback.
    pub fn all_entries(&self) -> impl Iterator<Item = (FontFaceId, &FontEntry)> {
        self.fonts
            .iter()
            .enumerate()
            .filter_map(|(i, opt)| opt.as_ref().map(|entry| (FontFaceId(i as u32), entry)))
    }
}