crcbl-ui 0.2.0

Crucible immediate-mode GUI
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! Real fonts: parsing, the coverage rasteriser, the glyph atlas and text
//! layout — UI rung 5.
//!
//! ```text
//!  TTF bytes ──skrifa──▶ Font (cmap, advances, metrics, GPOS pair kerning)
//!                          │
//!   text ──layout──▶ TextLayout (advanced, kerned, wrapped glyph positions)
//!                          │
//!                          ▼
//!   DrawList::glyphs ──to_triangles_split──▶ GlyphAtlas::glyph
//!                                             │  hinted outline (skrifa)
//!                                             │  ──raster──▶ coverage mask
//!                                             ▼
//!                                   shelf-packed page, dirty rectangle
//! ```
//!
//! * [`Font`] — one parsed font: glyph ids through the cmap, horizontal
//!   advances, line metrics and pair kerning, read through `skrifa` and its
//!   `read-fonts` (`skrifa::raw`).
//! * [`raster`] — this engine's own coverage rasteriser.
//! * [`atlas`] — the glyph atlas: shelf-packed pages, LRU eviction and a
//!   per-frame rasterisation budget.
//! * [`layout`] — advancing, kerning and greedy line breaking.
//! * [`face`] — choosing a family's face by weight and style, and the bold and
//!   italic synthesised for a family without them.
//! * [`fallback`] — which of a font's fallback faces draws each char, and the
//!   emoji and text presentation selectors.
//! * [`color`] — colour glyphs, drawn as pictures in the image atlas.
//!
//! # Two fonts, two families
//!
//! [`FontFamily::Bitmap`] is [`crate::text::FontAtlas`], the built-in 8×13
//! pixel font every panel, menu and console still draws with.
//! `FontFamily::Sans` is `Font::sans`: Atkinson Hyperlegible Regular, by
//! the Braille Institute of America, under the SIL Open Font License 1.1 —
//! `crates/crcbl-ui/fonts/OFL.txt` is its licence, committed beside
//! `crates/crcbl-ui/fonts/AtkinsonHyperlegible-Regular.ttf` and embedded into
//! every binary that links this crate **with the `parsed-font` feature on**.
//!
//! # The `parsed-font` feature
//!
//! Everything here that reads a font's bytes — `skrifa`, `SANS_TTF`,
//! `Font::sans`, [`Font::parse`]'s tables and the atlas's outlines — is behind
//! the crate's `parsed-font` feature, off by default, because a browser build
//! that links it pays for it whether or not it draws a parsed glyph. Off, the
//! parsed font cannot exist: [`Font`] holds a field of an uninhabited type, so
//! [`layout`], [`atlas`], [`DrawList::glyphs`](crate::draw_list::DrawList::glyphs)
//! and [`Ui::register_font`](crate::tree::Ui::register_font) still compile —
//! nothing that names a `Font` needs a `cfg` of its own — and can never be
//! called, which the compiler says rather than a comment.
//! [`Font::parse`] refuses with [`FontError::ParsedFontOff`], and
//! `FontFamily::Sans` is not there to name, so a stylesheet naming it is
//! refused as a value `font-family` does not take.
//!
//! # Fonts an application registers
//!
//! Beside the two, a tree draws in any [`Font`] an application registers with
//! [`Ui::register_font`](crate::tree::Ui::register_font) under a
//! [`FamilyName`]: a `font-family` list naming it before its first built-in
//! family selects it, and a span in it is measured and emitted exactly as a
//! `FontFamily::Sans` span is — [`layout::TextLayout`] and
//! [`DrawList::glyphs`](crate::draw_list::DrawList::glyphs) — so its glyphs
//! reach the screen through the same [`atlas`] as the committed font's.
//!
//! A font need not be compiled in: [`Font::parse`] takes any [`FontData`],
//! so bytes an application read at run time — a system font it looked up, a
//! file a user picked — parse, register and draw like the committed font,
//! and are freed with the last clone of the [`Font`] rather than leaked.
//!
//! # Latin-1 first
//!
//! Every codepoint goes through the font's cmap, and one no face has a glyph
//! for draws `.notdef` — after the handle's fallback faces have been asked,
//! see [`fallback`]. Kerning is read for the pairs of glyphs Latin-1 maps to;
//! there is no shaping, so no ligatures, no marks positioned and no
//! right-to-left text.

pub mod atlas;
pub mod color;
pub mod face;
pub mod fallback;
#[cfg(all(test, feature = "parsed-font"))]
pub(crate) mod fixtures;
#[cfg(feature = "parsed-font")]
mod kern;
pub mod layout;
pub use crcbl_image::raster;

use core::fmt;
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "parsed-font")]
use std::sync::OnceLock;
#[cfg(feature = "parsed-font")]
use std::sync::atomic::{AtomicU32, Ordering};

#[cfg(feature = "parsed-font")]
use skrifa::instance::{LocationRef, Size};
#[cfg(feature = "parsed-font")]
use skrifa::raw::TableProvider;
#[cfg(feature = "parsed-font")]
use skrifa::{FontRef, MetadataProvider};

use face::Synthesis;

/// The committed UI font's bytes: Atkinson Hyperlegible Regular. See the module
/// docs for its licence.
#[cfg(feature = "parsed-font")]
pub const SANS_TTF: &[u8] = include_bytes!("../../fonts/AtkinsonHyperlegible-Regular.ttf");

/// Which font a text node draws in: `font-family` in a stylesheet.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FontFamily {
    /// [`crate::text::FontAtlas`]'s built-in 8×13 bitmap font — `bitmap` in a
    /// stylesheet, and the initial value, so every panel that names no family
    /// draws as it always has.
    #[default]
    Bitmap,
    /// [`Font::sans`] — `sans-serif` or `"Atkinson Hyperlegible"` in a
    /// stylesheet. Only with the `parsed-font` feature.
    #[cfg(feature = "parsed-font")]
    Sans,
}

impl FontFamily {
    /// The parsed font this family draws with, or `None` for the bitmap font.
    #[must_use]
    pub fn font(self) -> Option<&'static Font> {
        match self {
            Self::Bitmap => None,
            #[cfg(feature = "parsed-font")]
            Self::Sans => Some(Font::sans()),
        }
    }
}

/// A family name no built-in family answers to, hashed: what
/// [`Ui::register_font`](crate::tree::Ui::register_font) registers a font under
/// and a `font-family` list names it by.
///
/// **ASCII case is ignored, and nothing else is**: `Roboto`, `"roboto"` and
/// `ROBOTO` are one name. An unquoted name of several words is its words joined
/// by single spaces, so `Roboto  Mono` in a sheet is `"Roboto Mono"`, while a
/// quoted one is taken as written, spaces and all.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FamilyName(u64);

impl FamilyName {
    /// The name `name`, in any ASCII case.
    #[must_use]
    pub fn new(name: &str) -> Self {
        let mut hasher = std::hash::DefaultHasher::new();
        std::hash::Hash::hash(&name.to_ascii_lowercase(), &mut hasher);
        Self(std::hash::Hasher::finish(&hasher))
    }
}

/// The names a `font-family` list never selects a registered font by, ASCII
/// case aside: the built-in families' own, CSS's generic families and its
/// CSS-wide keywords.
const RESERVED_FAMILIES: &[&str] = &[
    "bitmap",
    "atkinson hyperlegible",
    "serif",
    "sans-serif",
    "monospace",
    "cursive",
    "fantasy",
    "system-ui",
    "ui-serif",
    "ui-sans-serif",
    "ui-monospace",
    "ui-rounded",
    "math",
    "emoji",
    "fangsong",
    "initial",
    "inherit",
    "unset",
    "revert",
    "revert-layer",
    "default",
];

/// Whether `name` is one of [`RESERVED_FAMILIES`], or empty.
pub(crate) fn is_reserved_family(name: &str) -> bool {
    name.is_empty()
        || RESERVED_FAMILIES
            .iter()
            .any(|reserved| reserved.eq_ignore_ascii_case(name))
}

/// Why [`Ui::register_font`](crate::tree::Ui::register_font) refused a name:
/// it is empty, a built-in family's, a generic family or a CSS-wide keyword,
/// so no `font-family` list could ever select a font registered under it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReservedFamilyName(pub String);

impl fmt::Display for ReservedFamilyName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "`{}` is reserved: no `font-family` list selects a registered font by it",
            self.0
        )
    }
}

impl std::error::Error for ReservedFamilyName {}

/// Names one parsed [`Font`] for as long as the process runs: what the glyph
/// atlas keys a glyph's font by.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FontId(u32);

/// A glyph's index in its font.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GlyphId(pub u32);

impl GlyphId {
    /// `.notdef`, glyph zero in every font: what a codepoint with no glyph
    /// draws.
    pub const NOTDEF: Self = Self(0);
}

/// Why [`Font::parse`] refused some bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FontError {
    /// `skrifa` could not read the font's table directory.
    Unreadable(String),
    /// The font's `head` table gives no units per em, so nothing in it can be
    /// scaled to a pixel size.
    NoUnitsPerEm,
    /// This build has no parsed fonts: the crate's `parsed-font` feature is
    /// off. What [`Font::parse`] returns in such a build, whatever the bytes.
    /// The variant is there with the feature on too, so turning the feature on
    /// from another crate never breaks a `match` written without it.
    ParsedFontOff,
}

impl fmt::Display for FontError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unreadable(why) => write!(f, "the font cannot be read: {why}"),
            Self::NoUnitsPerEm => f.write_str("the font's head table gives no units per em"),
            Self::ParsedFontOff => f.write_str(
                "crcbl-ui was built without its `parsed-font` feature, so it parses no fonts",
            ),
        }
    }
}

impl std::error::Error for FontError {}

/// Where a font draws an underline, in font units, as its `post` table says.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Underline {
    /// The baseline to the line's top edge, positive upwards: negative for
    /// an underline below the baseline, as nearly every font's is.
    pub offset: f32,
    /// How thick it is.
    pub thickness: f32,
}

/// A font's line metrics, in font units: the
/// ascender, descender and line gap, as `skrifa` selects them from `hhea` or
/// `OS/2`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FontMetrics {
    /// Font units per em: what a pixel size is divided by.
    pub units_per_em: u16,
    /// Baseline to the top of the line's alignment box, positive upwards.
    pub ascent: f32,
    /// Baseline to its bottom, **negative** below the baseline, as the font
    /// stores it.
    pub descent: f32,
    /// Extra space the font recommends between one line and the next.
    pub line_gap: f32,
}

impl FontMetrics {
    /// Pixels per font unit at `size` pixels per em.
    #[must_use]
    pub fn scale(&self, size: f32) -> f32 {
        size / f32::from(self.units_per_em)
    }

    /// `line-height: normal` at `size`: ascent to descent plus the line gap.
    #[must_use]
    pub fn normal_line_height(&self, size: f32) -> f32 {
        (self.ascent - self.descent + self.line_gap) * self.scale(size)
    }
}

/// The first codepoint past Latin-1: everything below it is looked up in a
/// table built at parse time, everything from it on goes through the cmap.
const LATIN1_END: u32 = 0x100;

/// The bytes a [`Font`] is parsed from: compiled in, or found at run time.
///
/// Made with `From` from an `include_bytes!` (`&'static [u8; N]` or
/// `&'static [u8]`), or from a `Vec<u8>`, `Box<[u8]>` or `Arc<[u8]>` an
/// application read itself — a system font it looked up, a font file a user
/// chose. The font keeps them alive for as long as any clone of it lives, so
/// nothing has to be leaked to make them last.
#[derive(Clone)]
pub struct FontData(Bytes);

/// Where [`FontData`]'s bytes live. Compiled-in bytes are borrowed rather
/// than copied into a shared allocation.
#[derive(Clone)]
enum Bytes {
    Static(&'static [u8]),
    Shared(Arc<[u8]>),
}

impl FontData {
    /// The bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        match &self.0 {
            Bytes::Static(bytes) => bytes,
            Bytes::Shared(bytes) => bytes,
        }
    }
}

impl fmt::Debug for FontData {
    /// The length; not the bytes.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FontData")
            .field("len", &self.as_bytes().len())
            .finish()
    }
}

impl From<&'static [u8]> for FontData {
    fn from(bytes: &'static [u8]) -> Self {
        Self(Bytes::Static(bytes))
    }
}

impl<const N: usize> From<&'static [u8; N]> for FontData {
    fn from(bytes: &'static [u8; N]) -> Self {
        Self(Bytes::Static(bytes))
    }
}

impl From<Arc<[u8]>> for FontData {
    fn from(bytes: Arc<[u8]>) -> Self {
        Self(Bytes::Shared(bytes))
    }
}

impl From<Vec<u8>> for FontData {
    fn from(bytes: Vec<u8>) -> Self {
        Self(Bytes::Shared(bytes.into()))
    }
}

impl From<Box<[u8]>> for FontData {
    fn from(bytes: Box<[u8]>) -> Self {
        Self(Bytes::Shared(bytes.into()))
    }
}

/// One parsed font. See the module docs.
///
/// Parsing reads everything layout needs per glyph up front — the Latin-1
/// cmap, every advance and the kerning of every Latin-1 pair — so measuring
/// and laying out text touches no table. Outlines are read when the atlas
/// rasterises a glyph.
///
/// A handle: cloning it is a reference count, and every clone is the same
/// font. Two fonts are equal when they are one parse drawn with one
/// [`Synthesis`]: equality is [`Font::id`], and **the fallback faces a handle
/// carries ([`Font::with_fallback`]) are not part of it**.
///
/// Without the `parsed-font` feature there is no value of this type: see the
/// module docs.
#[derive(Clone)]
pub struct Font {
    parsed: Arc<Parsed>,
    /// What this handle draws of the face that it lacks; see [`face`].
    synthesis: Synthesis,
    /// The faces asked, in order, for a char this one has no glyph for; see
    /// [`fallback`]. None of them carries fallback faces of its own.
    fallback: Arc<[Font]>,
}

/// What one parse read, shared by every clone of its [`Font`].
struct Parsed {
    /// Uninhabited, so a build without the feature can name a `Font` and never
    /// hold one: a body that reads the font's bytes matches on this instead.
    #[cfg(not(feature = "parsed-font"))]
    never: NoParsedFont,
    /// This parse's identity under each [`Synthesis`], by
    /// [`Synthesis::index`]: a synthesised face's glyphs are not the face's.
    ids: [FontId; SYNTHESES],
    data: FontData,
    metrics: FontMetrics,
    /// Its `post` table's underline, if it has one.
    underline: Option<Underline>,
    /// Its weight class, 1 to 1000.
    weight: f32,
    /// Whether it is an italic or oblique face.
    italic: bool,
    /// Whether it has a `COLR`, `CBDT` or `sbix` table: whether any of its
    /// glyphs can be a colour glyph.
    #[cfg(feature = "parsed-font")]
    color: bool,
    /// Glyph ids of the codepoints below [`LATIN1_END`]; zero where the font
    /// has none.
    latin1: [u32; LATIN1_END as usize],
    /// Every glyph's advance, in font units.
    advances: Box<[f32]>,
    /// `(left, right)` to the first glyph's advance adjustment, in font units.
    /// Only non-zero pairs are held.
    kerning: HashMap<(u32, u32), f32>,
}

impl fmt::Debug for Font {
    /// The id and the metrics; not the tables.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Font")
            .field("id", &self.id())
            .field("metrics", &self.parsed.metrics)
            .field("weight", &self.parsed.weight)
            .field("italic", &self.parsed.italic)
            .field("synthesis", &self.synthesis)
            .field("fallback", &self.fallback.len())
            .field("glyphs", &self.parsed.advances.len())
            .field("kerning_pairs", &self.parsed.kerning.len())
            .finish_non_exhaustive()
    }
}

impl PartialEq for Font {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl Eq for Font {}

/// A clone: what lets a caller holding a `&'static Font` pass it wherever a
/// `Font` is taken.
impl From<&Font> for Font {
    fn from(font: &Font) -> Self {
        font.clone()
    }
}

/// No value: what makes [`Font`] uninhabited without the `parsed-font`
/// feature.
#[cfg(not(feature = "parsed-font"))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NoParsedFont {}

/// How many [`Synthesis`] combinations there are, each an identity of its own.
const SYNTHESES: usize = 4;

/// The next parse's [`FontId`]s, one per [`Synthesis`].
#[cfg(feature = "parsed-font")]
fn next_ids() -> [FontId; SYNTHESES] {
    static NEXT_ID: AtomicU32 = AtomicU32::new(0);
    let first = NEXT_ID.fetch_add(SYNTHESES as u32, Ordering::Relaxed);
    core::array::from_fn(|at| FontId(first + at as u32))
}

impl Font {
    /// The committed UI font, parsed once per process.
    ///
    /// # Panics
    ///
    /// If [`SANS_TTF`] does not parse, which the crate's own tests rule out:
    /// the bytes are compiled in, so they are the same bytes the tests read.
    #[cfg(feature = "parsed-font")]
    #[must_use]
    pub fn sans() -> &'static Self {
        static SANS: OnceLock<Font> = OnceLock::new();
        SANS.get_or_init(|| Self::parse(SANS_TTF).expect("the committed UI font parses"))
    }

    /// Refuses `data`: this build has no parsed fonts. See the module docs.
    ///
    /// # Errors
    ///
    /// [`FontError::ParsedFontOff`], always.
    #[cfg(not(feature = "parsed-font"))]
    pub fn parse(data: impl Into<FontData>) -> Result<Self, FontError> {
        drop(data.into());
        Err(FontError::ParsedFontOff)
    }

    /// Parses `data` — see [`FontData`] for what it can be made from — and
    /// keeps it for the outlines the atlas reads later.
    ///
    /// A font whose GPOS table cannot be read parses with no kerning, and says
    /// so through `crcbl_core::warn!`: a font that draws unkerned is still a
    /// font.
    ///
    /// # Errors
    ///
    /// [`FontError`] when the table directory cannot be read or the font has
    /// no units per em.
    #[cfg(feature = "parsed-font")]
    pub fn parse(data: impl Into<FontData>) -> Result<Self, FontError> {
        let data = data.into();
        let font = FontRef::new(data.as_bytes())
            .map_err(|error| FontError::Unreadable(error.to_string()))?;
        let unscaled = font.metrics(Size::unscaled(), LocationRef::default());
        if unscaled.units_per_em == 0 {
            return Err(FontError::NoUnitsPerEm);
        }
        let metrics = FontMetrics {
            units_per_em: unscaled.units_per_em,
            ascent: unscaled.ascent,
            descent: unscaled.descent,
            line_gap: unscaled.leading,
        };
        let underline = unscaled.underline.map(|line| Underline {
            offset: line.offset,
            thickness: line.thickness,
        });
        let attributes = font.attributes();
        let color = font.colr().is_ok() || font.cbdt().is_ok() || font.sbix().is_ok();

        let charmap = font.charmap();
        let mut latin1 = [0; LATIN1_END as usize];
        for (codepoint, glyph) in latin1.iter_mut().enumerate() {
            *glyph = charmap
                .map(codepoint as u32)
                .map_or(0, skrifa::GlyphId::to_u32);
        }

        let glyph_metrics = font.glyph_metrics(Size::unscaled(), LocationRef::default());
        let advances = (0..glyph_metrics.glyph_count())
            .map(|glyph| {
                glyph_metrics
                    .advance_width(skrifa::GlyphId::new(glyph))
                    .unwrap_or(0.0)
            })
            .collect();

        let mut pair_glyphs: Vec<u32> = latin1.iter().copied().filter(|&g| g != 0).collect();
        pair_glyphs.sort_unstable();
        pair_glyphs.dedup();
        let kerning = match kern::pair_kerning(&font, &pair_glyphs) {
            Ok(kerning) => kerning,
            Err(error) => {
                crcbl_core::warn!(
                    "font: the GPOS table cannot be read ({error}); the font draws unkerned"
                );
                HashMap::new()
            }
        };

        Ok(Self {
            parsed: Arc::new(Parsed {
                ids: next_ids(),
                data,
                metrics,
                underline,
                weight: attributes.weight.value(),
                italic: attributes.style != skrifa::attribute::Style::Normal,
                color,
                latin1,
                advances,
                kerning,
            }),
            synthesis: Synthesis::NONE,
            fallback: no_fallback(),
        })
    }

    /// This font's identity: one per parse and [`Synthesis`].
    #[must_use]
    pub fn id(&self) -> FontId {
        self.parsed.ids[self.synthesis.index()]
    }

    /// This face drawn with `synthesis` — see [`face`] — sharing its parse:
    /// a handle of its own identity, the same one every time it is asked
    /// for, so a span in it is measured and its glyphs cached once.
    #[must_use]
    pub fn synthesized(&self, synthesis: Synthesis) -> Self {
        Self {
            parsed: Arc::clone(&self.parsed),
            synthesis,
            fallback: Arc::clone(&self.fallback),
        }
    }

    /// This face with `fallback` asked, in order, for every char it has no
    /// glyph for — see [`fallback`] — in place of whatever it carried. The
    /// faces' own fallback faces are left behind, and past
    /// [`fallback::MAX_FALLBACK_FACES`] they are left out.
    #[must_use]
    pub fn with_fallback(&self, fallback: &[Self]) -> Self {
        let faces = fallback
            .iter()
            .take(fallback::MAX_FALLBACK_FACES)
            .map(|face| Self {
                parsed: Arc::clone(&face.parsed),
                synthesis: face.synthesis,
                fallback: no_fallback(),
            })
            .collect();
        Self {
            parsed: Arc::clone(&self.parsed),
            synthesis: self.synthesis,
            fallback: faces,
        }
    }

    /// The fallback faces this handle carries, in the order they are asked.
    #[must_use]
    pub fn fallback(&self) -> &[Self] {
        &self.fallback
    }

    /// Face `index` of this handle: itself for zero, its `index`th fallback
    /// face from one — what [`fallback::Mapped::face`] numbers — and itself
    /// for an index past them.
    #[must_use]
    pub fn face(&self, index: u8) -> &Self {
        match index.checked_sub(1) {
            Some(at) => self.fallback.get(usize::from(at)).unwrap_or(self),
            None => self,
        }
    }

    /// Without the `parsed-font` feature there is no font to ask.
    #[cfg(not(feature = "parsed-font"))]
    #[must_use]
    pub fn has_color_glyph(&self, _glyph: GlyphId) -> bool {
        match self.parsed.never {}
    }

    /// Without the `parsed-font` feature there is no font to ask.
    #[cfg(not(feature = "parsed-font"))]
    pub(crate) fn has_color_tables(&self) -> bool {
        match self.parsed.never {}
    }

    /// Whether any of its glyphs can be a colour glyph: whether it has a
    /// `COLR`, `CBDT` or `sbix` table. Read once, when it was parsed.
    #[cfg(feature = "parsed-font")]
    pub(crate) fn has_color_tables(&self) -> bool {
        self.parsed.color
    }

    /// Whether `glyph` has a colour representation: a `COLR` layer list or
    /// paint graph, or a bitmap in one of its `CBDT` or `sbix` strikes.
    #[cfg(feature = "parsed-font")]
    #[must_use]
    pub fn has_color_glyph(&self, glyph: GlyphId) -> bool {
        self.parsed.color
            && FontRef::new(self.data())
                .is_ok_and(|font| color::has_color_glyph(&font, skrifa::GlyphId::new(glyph.0)))
    }

    /// What this handle synthesises; [`Synthesis::NONE`] for a face as
    /// parsed.
    #[must_use]
    pub const fn synthesis(&self) -> Synthesis {
        self.synthesis
    }

    /// The face's weight class, 1 to 1000, as its `OS/2` table gives it — or
    /// its `head` table's bold bit, for a font with none.
    #[must_use]
    pub fn weight(&self) -> f32 {
        self.parsed.weight
    }

    /// Whether the face is italic or oblique, by its `OS/2` or `head` table.
    #[must_use]
    pub fn is_italic(&self) -> bool {
        self.parsed.italic
    }

    /// Where the font says an underline goes, or `None` when it does not
    /// say.
    #[must_use]
    pub fn underline(&self) -> Option<Underline> {
        self.parsed.underline
    }

    /// The bytes it was parsed from.
    #[must_use]
    pub fn data(&self) -> &[u8] {
        self.parsed.data.as_bytes()
    }

    /// Its line metrics.
    #[must_use]
    pub fn metrics(&self) -> FontMetrics {
        self.parsed.metrics
    }

    /// How many glyphs it holds.
    #[must_use]
    pub fn glyph_count(&self) -> usize {
        self.parsed.advances.len()
    }

    /// The glyph `c` draws as: through the cmap, or [`GlyphId::NOTDEF`] when
    /// the font maps it to nothing.
    #[must_use]
    pub fn glyph_id(&self, c: char) -> GlyphId {
        let codepoint = c as u32;
        if codepoint < LATIN1_END {
            return GlyphId(self.parsed.latin1[codepoint as usize]);
        }
        #[cfg(not(feature = "parsed-font"))]
        match self.parsed.never {}
        #[cfg(feature = "parsed-font")]
        FontRef::new(self.data())
            .ok()
            .and_then(|font| font.charmap().map(codepoint))
            .map_or(GlyphId::NOTDEF, |glyph| GlyphId(glyph.to_u32()))
    }

    /// `glyph`'s advance in font units, widened by a synthesised bold's
    /// [`face::SYNTHETIC_BOLD_EM`]; zero for a glyph the font does not have.
    #[must_use]
    pub fn advance(&self, glyph: GlyphId) -> f32 {
        let Some(&advance) = self.parsed.advances.get(glyph.0 as usize) else {
            return 0.0;
        };
        if self.synthesis.bold {
            advance + f32::from(self.parsed.metrics.units_per_em) * face::SYNTHETIC_BOLD_EM
        } else {
            advance
        }
    }

    /// How far `right` moves when it follows `left`, in font units: the pair
    /// adjustment of the GPOS `kern` feature, zero for a pair it does not
    /// kern. Only pairs of glyphs Latin-1 maps to are read.
    #[must_use]
    pub fn kerning(&self, left: GlyphId, right: GlyphId) -> f32 {
        self.parsed
            .kerning
            .get(&(left.0, right.0))
            .copied()
            .unwrap_or(0.0)
    }

    /// How many glyph pairs the font kerns.
    #[must_use]
    pub fn kerning_pairs(&self) -> usize {
        self.parsed.kerning.len()
    }

    /// A font with `metrics` and no outlines, leaked for the process: every
    /// Latin-1 codepoint is glyph 1, `advance` font units wide, and nothing
    /// kerns. What a test measures known widths in; it cannot be rasterised,
    /// and without the `parsed-font` feature it cannot be made.
    #[cfg(all(test, feature = "parsed-font"))]
    pub(crate) fn fixed_pitch(metrics: FontMetrics, advance: f32) -> &'static Self {
        Self::fixed_pitch_face(metrics, advance, 400.0, false)
    }

    /// [`Font::fixed_pitch`] as a face of `weight`, italic or not: what a
    /// test builds a family of faces from.
    #[cfg(all(test, feature = "parsed-font"))]
    pub(crate) fn fixed_pitch_face(
        metrics: FontMetrics,
        advance: f32,
        weight: f32,
        italic: bool,
    ) -> &'static Self {
        Box::leak(Box::new(Self {
            parsed: Arc::new(Parsed {
                ids: next_ids(),
                data: FontData::from(&[]),
                metrics,
                underline: None,
                weight,
                italic,
                color: false,
                latin1: [1; LATIN1_END as usize],
                advances: Box::new([0.0, advance]),
                kerning: HashMap::new(),
            }),
            synthesis: Synthesis::NONE,
            fallback: no_fallback(),
        }))
    }
}

/// An empty fallback list.
fn no_fallback() -> Arc<[Font]> {
    Arc::from(Vec::new())
}

#[cfg(all(test, not(feature = "parsed-font")))]
mod off_tests {
    use super::*;

    /// **Without the feature, nothing parses** — not even the committed font's
    /// own bytes, which a build with it on parses — and the refusal says why.
    #[test]
    fn without_the_feature_every_parse_is_refused_and_says_why() {
        let bytes = include_bytes!("../../fonts/AtkinsonHyperlegible-Regular.ttf");
        let refused = Font::parse(bytes);
        assert!(matches!(refused, Err(FontError::ParsedFontOff)));
        let message = FontError::ParsedFontOff.to_string();
        assert!(message.contains("parsed-font"), "{message}");
        assert_eq!(FontFamily::default().font(), None);
    }
}

#[cfg(all(test, feature = "parsed-font"))]
mod tests {
    use super::*;

    /// **The committed font parses into what layout reads**: its units per em
    /// and line metrics as `skrifa` reports them, a glyph for every printable
    /// Latin-1 codepoint, and kerning.
    #[test]
    fn the_committed_font_parses_with_latin1_and_kerning() {
        let font = Font::sans();
        let reference = FontRef::new(SANS_TTF).expect("reads");
        let metrics = reference.metrics(Size::unscaled(), LocationRef::default());
        assert_eq!(font.metrics().units_per_em, metrics.units_per_em);
        assert_eq!(font.metrics().ascent, metrics.ascent);
        assert_eq!(font.metrics().descent, metrics.descent);
        assert!(font.metrics().ascent > 0.0 && font.metrics().descent < 0.0);

        let printable = (0x20u32..0x7f).chain(0xa0..0x100);
        for codepoint in printable {
            let c = char::from_u32(codepoint).expect("Latin-1 is valid");
            assert_ne!(
                font.glyph_id(c),
                GlyphId::NOTDEF,
                "U+{codepoint:04X} has no glyph"
            );
        }
        assert!(
            font.kerning_pairs() > 0,
            "the committed font's GPOS kerning was not read"
        );
    }

    /// **A codepoint the cmap does not map draws `.notdef`**, inside Latin-1
    /// and past it, and one it does map is read through the cmap past Latin-1
    /// too.
    #[test]
    fn an_unmapped_codepoint_is_notdef_and_a_mapped_one_is_not() {
        let font = Font::sans();
        let reference = FontRef::new(SANS_TTF).expect("reads");
        let charmap = reference.charmap();
        for c in ['\u{1}', '\u{7f}', '\u{4e2d}', '\u{1f600}'] {
            assert_eq!(charmap.map(c as u32), None, "{c:?} is mapped after all");
            assert_eq!(font.glyph_id(c), GlyphId::NOTDEF, "{c:?}");
        }
        // Past Latin-1 and mapped: the Euro sign and the en dash.
        for c in ['€', '–'] {
            let want = charmap.map(c as u32).expect("the font maps it");
            assert_eq!(font.glyph_id(c), GlyphId(want.to_u32()), "{c:?}");
            assert_ne!(font.glyph_id(c), GlyphId::NOTDEF);
        }
    }

    /// **Bytes that are not a font are refused**, not panicked on.
    #[test]
    fn bytes_that_are_not_a_font_are_refused() {
        assert!(matches!(
            Font::parse(b"not a font at all"),
            Err(FontError::Unreadable(_))
        ));
    }

    /// Advances are the font's `hmtx` widths, one per glyph.
    #[test]
    fn advances_are_the_fonts_own() {
        let font = Font::sans();
        let reference = FontRef::new(SANS_TTF).expect("reads");
        let metrics = reference.glyph_metrics(Size::unscaled(), LocationRef::default());
        assert_eq!(font.glyph_count(), metrics.glyph_count() as usize);
        for c in ['A', 'i', 'W', ' ', 'é'] {
            let glyph = font.glyph_id(c);
            assert_eq!(
                Some(font.advance(glyph)),
                metrics.advance_width(skrifa::GlyphId::new(glyph.0)),
                "{c:?}"
            );
        }
        assert_eq!(font.advance(GlyphId(u32::MAX)), 0.0);
    }

    /// **Bytes read at run time parse as the compiled-in ones do**, and the
    /// font holds them once, however many clones of it there are, until the
    /// last clone goes: nothing is leaked to make them last.
    #[test]
    fn a_font_from_run_time_bytes_holds_them_until_its_last_clone_goes() {
        let bytes: Arc<[u8]> = Arc::from(SANS_TTF);
        let font = Font::parse(Arc::clone(&bytes)).expect("parses");
        assert_eq!(font.metrics(), Font::sans().metrics());
        assert_eq!(font.glyph_id('A'), Font::sans().glyph_id('A'));
        let copy = font.clone();
        assert_eq!(copy, font, "a clone is the same font");
        assert_eq!(Arc::strong_count(&bytes), 2);
        drop(font);
        assert_eq!(Arc::strong_count(&bytes), 2, "the clone still holds them");
        drop(copy);
        assert_eq!(Arc::strong_count(&bytes), 1, "freed with the last clone");

        let owned = Font::parse(SANS_TTF.to_vec()).expect("parses");
        assert_eq!(owned.data(), SANS_TTF);
    }

    /// Two parses are two identities, so an atlas never confuses their glyphs.
    #[test]
    fn every_parse_is_its_own_id() {
        let a = Font::parse(SANS_TTF).expect("parses");
        let b = Font::parse(SANS_TTF).expect("parses");
        assert_ne!(a.id(), b.id());
    }
}