valo-text 0.12.0

Typographer and paragraph layout for valo: shaping, bidi, wrapping, glyph raster, SDF
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
use std::collections::HashMap;
use std::sync::Arc;

use skrifa::metrics::Metrics;
use skrifa::prelude::Size;
use skrifa::MetadataProvider;

/// `FontId` identifies a registered font within a [`FaceSet`] or [`FontCollection`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FontId(
    /// The zero-based registration index.
    pub u32,
);

/// `FontData` is shared, immutable font-file storage supplied by the host.
///
/// It may wrap owned bytes or memory-mapped data and must remain readable for
/// the lifetime of every [`Font`] created from it.
pub type FontData = Arc<dyn AsRef<[u8]> + Send + Sync>;

/// `FontAttrs` describes a face's position within a font family.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FontAttrs {
    /// `weight` is the CSS font weight, conventionally from 100 to 900.
    pub weight: u16,
    /// `italic` indicates whether the face uses an italic or oblique style.
    pub italic: bool,
    /// `stretch` is the CSS font-width percentage, where 100 is normal.
    pub stretch: f32,
}

/// `NORMAL_STRETCH` is the CSS normal font-width percentage.
pub const NORMAL_STRETCH: f32 = 100.0;

impl Default for FontAttrs {
    fn default() -> Self {
        Self {
            weight: 400,
            italic: false,
            stretch: NORMAL_STRETCH,
        }
    }
}

/// The instance-independent half of a parsed face: bytes, coverage, and
/// the compiled shaping caches are IDENTICAL across a variable font's
/// named instances, so every instance shares one of these (DirectWrite's
/// model: instances enumerate separately, file state is shared).
struct SharedFace {
    data: FontData,
    /// Which face inside `data` — TrueType collections (.ttc) pack
    /// several; 0 for single-face files.
    face_index: u32,
    /// The face's id in the process that renders its glyphs, which every
    /// instance answers alike; None when glyphs render from `data`.
    remote_id: Option<u64>,
    /// cmap materialized ONCE — fallback resolution is per-character and
    /// must never re-parse the font (Skia caches per-typeface the same way).
    charmap: HashMap<u32, u32>,
    /// HarfBuzz's compiled shaping caches (GSUB/GDEF/cmap), built once —
    /// the FontRef itself is cheap to reconstruct per shape (Skia's analog:
    /// HB faces cached per typeface).
    shaper_data: harfrust::ShaperData,
}

/// `FontUid` is the process-unique identity of one font instance.
///
/// Glyph caches may use it as a stable key because equal identifiers imply
/// equal outlines and variation coordinates.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FontUid(
    /// The process-unique numeric identity.
    pub u64,
);

impl FontUid {
    fn next() -> FontUid {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        FontUid(COUNTER.fetch_add(1, Ordering::Relaxed))
    }
}

/// `Font` is one parsed font face or named variable-font instance.
///
/// It retains immutable source bytes and exposes the names, attributes,
/// coverage, and metrics needed for shaping and rendering.
///
/// A clone shares the parsed file and keeps the identifier: it is the same
/// face at the same instance, as Skia shares an `SkTypeface` by reference.
#[derive(Clone)]
pub struct Font {
    uid: FontUid,
    shared: Arc<SharedFace>,
    /// User-space variation coordinates when this font is a named instance
    /// of a variable font ((axis tag, value) per axis); empty = the
    /// file's default instance.
    variation_coordinates: Vec<([u8; 4], f32)>,
    /// The same coordinates in normalized variation space, for the skrifa
    /// views (metrics, COLR paint graphs).
    variation_location: skrifa::instance::Location,
    /// HarfBuzz's compiled per-instance data (None = default instance).
    shaper_instance: Option<harfrust::ShaperInstance>,
    family: String,
    /// Other names this face answers to: the file's localized family names
    /// (fontdb keeps all of them) plus any host-registered alias (Skia's
    /// `registerTypeface(typeface, familyName)`).
    aliases: Vec<String>,
    attrs: FontAttrs,
    units_per_em: f32,
    /// Font-unit metrics, y-up (ascent positive, descent negative).
    ascent: f32,
    descent: f32,
    line_gap: f32,
    /// The height of capital letters above the baseline in font units, 0 when the font does not
    /// say (Skia's `fCapHeight`).
    cap_height: f32,
    /// Union of all glyph ink, font units y-up — Skia's fXMin/fXMax family.
    bounds: Option<(f32, f32, f32, f32)>,
    /// (offset from baseline, thickness) in font units, when the font says.
    underline: Option<(f32, f32)>,
    strikeout: Option<(f32, f32)>,
}

impl std::fmt::Debug for Font {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Font")
            .field("uid", &self.uid)
            .field("family", &self.family)
            .field("attrs", &self.attrs)
            .finish_non_exhaustive()
    }
}

/// Two fonts are equal when they are the same face at the same instance, which is what
/// their identifiers say; equal identifiers imply equal outlines and coordinates.
impl PartialEq for Font {
    fn eq(&self, other: &Font) -> bool {
        self.uid == other.uid
    }
}

impl Font {
    fn parse(
        family: &str,
        attrs: FontAttrs,
        data: FontData,
        face_index: u32,
        variation_coordinates: Vec<([u8; 4], f32)>,
    ) -> Option<Self> {
        let shared = SharedFace::parse(data, face_index, None)?;
        Self::at_coordinates(shared, family, attrs, variation_coordinates)
    }

    /// One instance over already-parsed shared state — metrics and shaping
    /// instance data are the only per-instance work.
    fn at_coordinates(
        shared: Arc<SharedFace>,
        family: &str,
        attrs: FontAttrs,
        variation_coordinates: Vec<([u8; 4], f32)>,
    ) -> Option<Self> {
        let bytes: &[u8] = (*shared.data).as_ref();
        let font = skrifa::FontRef::from_index(bytes, shared.face_index).ok()?;
        let variation_location = font.axes().location(
            variation_coordinates
                .iter()
                .map(|(tag, value)| (skrifa::Tag::new(tag), *value)),
        );
        let metrics = Metrics::new(&font, Size::unscaled(), &variation_location);
        let shaper_instance = (!variation_coordinates.is_empty()).then(|| {
            let harf = harfrust::FontRef::from_index(bytes, shared.face_index).ok();
            harf.map(|harf| {
                harfrust::ShaperInstance::from_variations(
                    &harf,
                    variation_coordinates
                        .iter()
                        .map(|(tag, value)| harfrust::Variation {
                            tag: harfrust::Tag::new(tag),
                            value: *value,
                        }),
                )
            })
        });
        Some(Self {
            uid: FontUid::next(),
            family: family.to_owned(),
            aliases: Vec::new(),
            attrs,
            units_per_em: metrics.units_per_em as f32,
            ascent: metrics.ascent,
            descent: metrics.descent,
            line_gap: metrics.leading,
            cap_height: metrics.cap_height.unwrap_or(0.0),
            bounds: metrics.bounds.map(|b| (b.x_min, b.y_min, b.x_max, b.y_max)),
            underline: metrics.underline.map(|d| (d.offset, d.thickness)),
            strikeout: metrics.strikeout.map(|d| (d.offset, d.thickness)),
            shared,
            variation_coordinates,
            variation_location,
            shaper_instance: shaper_instance.flatten(),
        })
    }

    /// `data` returns the source font-file bytes.
    ///
    /// For a font collection file, use [`Self::face_index`] to select this face.
    pub fn data(&self) -> &[u8] {
        (*self.shared.data).as_ref()
    }

    /// `face_index` returns this face's index within [`Self::data`].
    pub fn face_index(&self) -> u32 {
        self.shared.face_index
    }

    /// `remote_id` returns this face's id in the process that renders its glyphs.
    ///
    /// It is Skia's `SkTypefaceProxy::remoteTypefaceID`. A host whose glyphs are
    /// rendered by another process makes its fonts with
    /// [`Self::from_data_with_remote_id`] or [`Self::instances_from_data_with_remote_id`],
    /// and its [`GlyphRaster`](crate::GlyphRaster) reads the id back to name the face to
    /// that process, with [`Self::variation_coordinates`] naming the instance: every
    /// named instance of a face answers the face's id. It is `None` for a font rendered
    /// from its own bytes, and valo itself never reads it.
    pub fn remote_id(&self) -> Option<u64> {
        self.shared.remote_id
    }

    /// `variation_coordinates` returns user-space axis tags and values.
    ///
    /// It is empty for static fonts and default variable-font instances.
    pub fn variation_coordinates(&self) -> &[([u8; 4], f32)] {
        &self.variation_coordinates
    }

    pub(crate) fn variation_location(&self) -> &skrifa::instance::Location {
        &self.variation_location
    }

    pub(crate) fn shaper_instance(&self) -> Option<&harfrust::ShaperInstance> {
        self.shaper_instance.as_ref()
    }

    /// `uid` returns the process-unique identity of this font instance.
    pub fn uid(&self) -> FontUid {
        self.uid
    }

    /// `family` returns the font's primary family name.
    pub fn family(&self) -> &str {
        &self.family
    }

    /// `aliases` returns additional family names recognized for this font.
    pub fn aliases(&self) -> &[String] {
        &self.aliases
    }

    /// `matches` reports whether `name` matches the family or an alias.
    ///
    /// Matching is ASCII case-insensitive.
    pub fn matches(&self, name: &str) -> bool {
        self.family.eq_ignore_ascii_case(name)
            || self.aliases.iter().any(|a| a.eq_ignore_ascii_case(name))
    }

    /// `add_alias` registers another family name if it is not already recognized.
    pub fn add_alias(&mut self, name: &str) {
        if !self.matches(name) {
            self.aliases.push(name.to_owned());
        }
    }

    /// `attrs` returns the face-selection attributes of this font.
    pub fn attrs(&self) -> FontAttrs {
        self.attrs
    }

    /// `ascent_px` returns the positive distance above the baseline at `size`.
    pub fn ascent_px(&self, size: f32) -> f32 {
        self.ascent * size / self.units_per_em
    }

    /// `cap_height_px` returns the height of capital letters above the baseline at `size`, 0
    /// when the font does not say.
    pub fn cap_height_px(&self, size: f32) -> f32 {
        self.cap_height * size / self.units_per_em
    }

    /// `descent_px` returns the positive distance below the baseline at `size`.
    pub fn descent_px(&self, size: f32) -> f32 {
        -self.descent * size / self.units_per_em
    }

    /// `line_height_px` returns the font's default line height at `size`.
    pub fn line_height_px(&self, size: f32) -> f32 {
        (self.ascent - self.descent + self.line_gap) * size / self.units_per_em
    }

    /// `units_per_em` returns the font's design-space units per em.
    pub fn units_per_em(&self) -> f32 {
        self.units_per_em
    }

    /// `ink_box_px` returns the font-wide ink bounds at `size`.
    ///
    /// The tuple is `(x_min, y_min, x_max, y_max)` in y-up coordinates around
    /// the glyph origin. It returns `None` when the font provides no bounds.
    pub fn ink_box_px(&self, size: f32) -> Option<(f32, f32, f32, f32)> {
        let k = size / self.units_per_em;
        self.bounds
            .map(|(x0, y0, x1, y1)| (x0 * k, y0 * k, x1 * k, y1 * k))
    }

    /// `covers` reports whether the font maps a character to a glyph.
    pub fn covers(&self, ch: char) -> bool {
        self.shared.charmap.contains_key(&(ch as u32))
    }

    /// `glyph_for` returns the glyph identifier mapped from a character.
    pub fn glyph_for(&self, ch: char) -> Option<u32> {
        self.shared.charmap.get(&(ch as u32)).copied()
    }

    pub(crate) fn shaper_data(&self) -> &harfrust::ShaperData {
        &self.shared.shaper_data
    }

    /// `underline_px` returns underline offset and thickness at `size`.
    ///
    /// The offset is positive below the baseline. Conventional values are used
    /// when the font omits underline metrics.
    pub fn underline_px(&self, size: f32) -> (f32, f32) {
        self.decoration_px(self.underline, size, -0.1, 0.05)
    }

    /// `strikeout_px` returns strikeout offset and thickness at `size`.
    ///
    /// The offset is positive above the baseline. Conventional values are used
    /// when the font omits strikeout metrics.
    pub fn strikeout_px(&self, size: f32) -> (f32, f32) {
        self.decoration_px(self.strikeout, size, 0.3, 0.05)
    }

    fn decoration_px(
        &self,
        metric: Option<(f32, f32)>,
        size: f32,
        default_offset: f32,
        default_thickness: f32,
    ) -> (f32, f32) {
        match metric {
            // Font units are y-up: positive offsets sit above the baseline.
            Some((offset, thickness)) => (
                offset * size / self.units_per_em,
                (thickness * size / self.units_per_em).max(0.5),
            ),
            None => (size * default_offset, (size * default_thickness).max(0.5)),
        }
    }
}

/// `FontDemand` describes font requests that no registered face could satisfy.
///
/// Hosts can use it to load additional fonts and lay out affected text again.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FontDemand {
    /// `families` lists requested family names with no registered match.
    pub families: Vec<String>,
    /// `codepoints` lists uncovered characters and their requested attributes.
    pub codepoints: Vec<(char, FontAttrs)>,
}

impl FontDemand {
    /// `is_empty` reports whether every font request was satisfied.
    pub fn is_empty(&self) -> bool {
        self.families.is_empty() && self.codepoints.is_empty()
    }

    pub(crate) fn add_family(&mut self, name: &str) {
        if !self.families.iter().any(|f| f == name) {
            self.families.push(name.to_owned());
        }
    }

    pub(crate) fn add_codepoint(&mut self, ch: char, attrs: FontAttrs) {
        if !self.codepoints.contains(&(ch, attrs)) {
            self.codepoints.push((ch, attrs));
        }
    }
}

/// `FontSource` locates fonts that are not already registered.
///
/// A source may consult installed fonts, downloaded assets, or another
/// host-owned repository. [`FontCollection`] consults sources in registration
/// order.
pub trait FontSource {
    /// `family` returns every available face matching a family name.
    fn family(&mut self, name: &str) -> Vec<Font>;

    /// `face_for_codepoint` returns a covering face nearest to `attrs`.
    fn face_for_codepoint(&mut self, codepoint: char, attrs: FontAttrs) -> Option<Font>;
}

/// `match_style` returns the font nearest `attrs` among `fonts`, by CSS font
/// matching's precedence: width, then style, then weight; ties to the first.
///
/// It is Skia's `SkFontStyleSet::matchStyle`, for a [`FontSource`] choosing
/// among a family's faces, or among a variable face's named instances, so that
/// a bold span's fallback arrives bold. The distances are plain absolute
/// differences rather than CSS's directional walk: a request between two
/// weights takes the closer, not the one CSS's direction prefers. It returns
/// `None` when `fonts` is empty.
pub fn match_style<'a>(
    fonts: impl IntoIterator<Item = &'a Font>,
    attrs: FontAttrs,
) -> Option<&'a Font> {
    fonts
        .into_iter()
        .min_by_key(|font| style_distance(font.attrs, attrs))
}

/// `FaceSet` stores registered fonts and their global fallback order.
///
/// Cloning a face set shares parsed fonts, allowing callers to grow a snapshot
/// without modifying existing holders.
#[derive(Default, Clone)]
pub struct FaceSet {
    /// `Arc` per face: adding a font clones N pointers, never re-parses
    /// (Skia registers typefaces incrementally).
    fonts: Vec<Arc<Font>>,
    fallbacks: Vec<FontId>,
    /// The faces answering to each name, keyed as [`name_key`] spells it, in
    /// registration order. Resolution asks per character, so a name is a
    /// lookup rather than a walk over every face comparing strings.
    by_name: HashMap<String, Vec<FontId>>,
}

/// `StyleFaces` is one text style's font resolution, prepared by
/// [`FaceSet::style_faces`].
///
/// It holds face identifiers only, ordered for [`FaceSet::resolve_prepared`];
/// it is stale once a face is added to the set it came from.
#[derive(Clone, Debug)]
pub struct StyleFaces {
    /// The requested families' faces, in request order, nearest-first.
    families: Vec<Vec<FontId>>,
    /// The fallback chain, nearest-first.
    fallbacks: Vec<FontId>,
    /// Where tofu renders when nothing covers: the style's best variant,
    /// else the first fallback, else the first face; `None` on an empty set.
    tofu: Option<FontId>,
}

impl FaceSet {
    /// `new` creates an empty face set.
    pub fn new() -> Self {
        Self::default()
    }

    /// `register` adds font bytes under a family using default attributes.
    ///
    /// It returns `None` when face zero cannot be parsed.
    pub fn register(&mut self, family: &str, bytes: Vec<u8>) -> Option<FontId> {
        self.register_with(family, FontAttrs::default(), bytes)
    }

    /// `register_with` adds font bytes under a family with explicit attributes.
    ///
    /// It returns `None` when face zero cannot be parsed.
    pub fn register_with(
        &mut self,
        family: &str,
        attrs: FontAttrs,
        bytes: Vec<u8>,
    ) -> Option<FontId> {
        let (data, face_index) = unwrapped(Arc::new(bytes), 0)?;
        let font = Font::parse(family, attrs, data, face_index, Vec::new())?;
        Some(self.add(font))
    }

    /// `add` registers an already parsed font under its embedded names and attributes.
    pub fn add(&mut self, font: Font) -> FontId {
        let id = FontId(self.fonts.len() as u32);
        let aliases = font.aliases().iter().map(String::as_str);
        for name in std::iter::once(font.family()).chain(aliases) {
            let ids = self.by_name.entry(name_key(name)).or_default();
            if ids.last() != Some(&id) {
                ids.push(id);
            }
        }
        self.fonts.push(Arc::new(font));
        id
    }

    /// `with_font` returns a cloned face set containing one additional font.
    ///
    /// Existing fonts remain shared and are not reparsed.
    pub fn with_font(&self, font: Font) -> (FaceSet, FontId) {
        let mut next = self.clone();
        let id = next.add(font);
        (next, id)
    }

    /// `with_fallbacks` returns a clone with its global fallback order replaced.
    ///
    /// Every identifier must belong to this face set.
    pub fn with_fallbacks(&self, fallbacks: Vec<FontId>) -> FaceSet {
        let mut next = self.clone();
        next.fallbacks = fallbacks;
        next
    }

    /// `add_fallback` appends a registered font to the global fallback order.
    ///
    /// Requested families are searched before this chain. `id` must belong to
    /// this face set.
    pub fn add_fallback(&mut self, id: FontId) {
        self.fallbacks.push(id);
    }

    /// `grown_by` returns a clone extended with answers from a font source.
    ///
    /// Requested families are also registered under the requested name.
    /// Uncovered codepoints add matching faces to the fallback chain. It returns
    /// `None` when the source supplies nothing new.
    pub fn grown_by(&self, source: &mut dyn FontSource, demand: &FontDemand) -> Option<FaceSet> {
        let mut next = self.clone();
        let mut grew = false;
        for name in &demand.families {
            if next.family(name).is_some() {
                // Answered already (a stale demand) — resolution matches
                // it now; asking the source again would duplicate faces.
                continue;
            }
            grew |= next.register_answers(source.family(name), name);
        }
        for &(codepoint, attrs) in &demand.codepoints {
            grew |= next.register_fallback_answer(source, codepoint, attrs);
        }
        grew.then_some(next)
    }

    fn register_answers(&mut self, faces: Vec<Font>, requested_name: &str) -> bool {
        let mut added = false;
        for mut font in faces {
            font.add_alias(requested_name);
            self.add(font);
            added = true;
        }
        added
    }

    fn register_fallback_answer(
        &mut self,
        source: &mut dyn FontSource,
        codepoint: char,
        attrs: FontAttrs,
    ) -> bool {
        if is_private_use(codepoint) {
            // Icon fonts resolve by their REGISTERED family name; a
            // generic source "covering" the Private Use Area paints some
            // vendor's glyphs where tofu is the honest render.
            return false;
        }
        if self.fallbacks_cover(codepoint) {
            // Already in the chain — resolution will find that face without
            // a second copy of it.
            return false;
        }
        let Some(font) = source.face_for_codepoint(codepoint, attrs) else {
            return false;
        };
        let id = self.add(font);
        self.add_fallback(id);
        true
    }

    /// Whether the global fallback chain covers `codepoint`.
    ///
    /// A fallback answer is only ever reached through this chain, so this —
    /// not "some registered face" — decides whether another one is needed.
    fn fallbacks_cover(&self, codepoint: char) -> bool {
        self.fallbacks
            .iter()
            .any(|id| self.get(*id).covers(codepoint))
    }

    /// Whether resolution finds a face covering `ch`.
    ///
    /// This is the walk [`Self::resolve_covered`] makes, so a face resolution
    /// cannot reach — registered under a name nobody asked for and absent from
    /// the fallback chain, as an icon font is — does not pass for coverage it
    /// will never supply. Asking "does some registered face cover it" instead
    /// lets such a font suppress the fallback the text actually needs.
    pub(crate) fn covered_by_resolution(
        &self,
        families: &[String],
        attrs: FontAttrs,
        ch: char,
    ) -> bool {
        matches!(
            self.resolve_covered_opt(families, attrs, ch),
            Some((_, true))
        )
    }

    /// `is_empty` reports whether no fonts are registered.
    pub fn is_empty(&self) -> bool {
        self.fonts.is_empty()
    }

    /// `len` returns the number of registered fonts.
    pub fn len(&self) -> usize {
        self.fonts.len()
    }

    /// `get_arc` returns a shared handle to a registered font.
    ///
    /// # Panics
    ///
    /// Panics if `id` does not belong to this face set.
    pub fn get_arc(&self, id: FontId) -> Arc<Font> {
        self.fonts[id.0 as usize].clone()
    }

    /// `get` returns a registered font by identifier.
    ///
    /// # Panics
    ///
    /// Panics if `id` does not belong to this face set.
    pub fn get(&self, id: FontId) -> &Font {
        &self.fonts[id.0 as usize]
    }

    /// `family` returns the first registered font matching a family name or alias.
    pub fn family(&self, name: &str) -> Option<FontId> {
        self.by_name.get(&name_key(name))?.first().copied()
    }

    /// `faces` iterates over every font matching a family name or alias.
    ///
    /// Results follow registration order and include separate subset faces.
    pub fn faces<'a>(&'a self, name: &'a str) -> impl Iterator<Item = FontId> + 'a {
        self.variants(name).map(|(id, _)| id)
    }

    /// `family_variant` returns the family face nearest to requested attributes.
    ///
    /// Faces are matched as [`match_style`] matches them: width first, then
    /// italic style and weight. Registration order breaks ties.
    pub fn family_variant(&self, name: &str, attrs: FontAttrs) -> Option<FontId> {
        let nearest = match_style(self.variants(name).map(|(_, font)| font), attrs)?;
        self.faces(name).find(|id| self.get(*id) == nearest)
    }

    /// `resolve` selects a font for a character and requested style.
    ///
    /// It searches requested families in order, then global fallbacks. If no
    /// font covers the character, it returns a font suitable for rendering
    /// `.notdef`.
    ///
    /// # Panics
    ///
    /// Panics when the face set is empty.
    pub fn resolve(&self, families: &[String], attrs: FontAttrs, ch: char) -> FontId {
        self.resolve_covered(families, attrs, ch).0
    }

    /// `resolve_covered` selects a font and reports whether it covers the character.
    ///
    /// A `false` flag means the returned font will render `.notdef`.
    ///
    /// # Panics
    ///
    /// Panics when the face set is empty.
    pub fn resolve_covered(
        &self,
        families: &[String],
        attrs: FontAttrs,
        ch: char,
    ) -> (FontId, bool) {
        let faces = self.style_faces(families, attrs);
        self.resolve_prepared(&faces, ch).unwrap_or_else(|| {
            panic!(
                "FontCollection has no fonts registered — register() one before building paragraphs"
            );
        })
    }

    /// `style_faces` prepares one style's resolution: the faces of each
    /// requested family and of the fallback chain, nearest-first to `attrs`.
    ///
    /// A run of text asks for a font per character; prepared once per style,
    /// each character is a coverage walk over these lists and no name lookup
    /// (Skia's `SkFontCollection::findTypefaces`, done once per text style).
    pub fn style_faces(&self, families: &[String], attrs: FontAttrs) -> StyleFaces {
        let fallbacks = self.fallbacks.iter().map(|id| (*id, self.get(*id)));
        StyleFaces {
            families: families
                .iter()
                .map(|name| self.nearest_first(self.variants(name), attrs))
                .collect(),
            fallbacks: self.nearest_first(fallbacks, attrs),
            tofu: self.tofu_face_opt(families, attrs),
        }
    }

    /// `resolve_prepared` selects a font for `ch` from a prepared style.
    ///
    /// The first covering face of the first requested family that has one
    /// wins, then the fallback chain's; the flag is `false` when nothing
    /// covers and the returned font renders `.notdef`. `None` when the face
    /// set is empty.
    pub fn resolve_prepared(&self, faces: &StyleFaces, ch: char) -> Option<(FontId, bool)> {
        let covering = faces
            .families
            .iter()
            .chain(std::iter::once(&faces.fallbacks))
            .flatten()
            .find(|id| self.get(**id).covers(ch));
        match covering {
            Some(id) => Some((*id, true)),
            None => faces.tofu.map(|id| (id, false)),
        }
    }

    /// Every face answering to `name`, with its id, in registration order.
    fn variants<'a>(&'a self, name: &str) -> impl Iterator<Item = (FontId, &'a Font)> + 'a {
        self.by_name
            .get(&name_key(name))
            .into_iter()
            .flatten()
            .map(|id| (*id, self.get(*id)))
    }

    /// `faces` in [`match_style`]'s order: the face it would pick first, and
    /// so on, with ties in registration order.
    fn nearest_first<'a>(
        &self,
        faces: impl Iterator<Item = (FontId, &'a Font)>,
        attrs: FontAttrs,
    ) -> Vec<FontId> {
        let mut faces: Vec<(FontId, &Font)> = faces.collect();
        faces.sort_by_key(|(_, f)| style_distance(f.attrs, attrs));
        faces.into_iter().map(|(id, _)| id).collect()
    }

    /// [`Self::tofu_face`] that reports an EMPTY collection instead of
    /// panicking — the `build_with` path, where an empty start is valid
    /// (the chain is asked first; a char no source can render is skipped
    /// and reported through the demand).
    pub(crate) fn tofu_face_opt(&self, families: &[String], attrs: FontAttrs) -> Option<FontId> {
        families
            .iter()
            .find_map(|name| self.family_variant(name, attrs))
            .or_else(|| self.fallbacks.first().copied())
            .or_else(|| (!self.fonts.is_empty()).then_some(FontId(0)))
    }

    /// [`Self::resolve_covered`] that can also report "no face exists at
    /// all" (empty collection on the `build_with` path).
    pub(crate) fn resolve_covered_opt(
        &self,
        families: &[String],
        attrs: FontAttrs,
        ch: char,
    ) -> Option<(FontId, bool)> {
        if self.fonts.is_empty() {
            return None;
        }
        Some(self.resolve_covered(families, attrs, ch))
    }
}

/// The spelling a family name or alias is indexed under: names match
/// ASCII-case-insensitively (as [`Font::matches`] compares them).
fn name_key(name: &str) -> String {
    name.to_ascii_lowercase()
}

impl Font {
    /// `from_bytes` parses face zero from owned font-file bytes.
    ///
    /// Family names and attributes come from the font. Localized family names
    /// become aliases. It returns `None` when the bytes cannot be parsed.
    pub fn from_bytes(bytes: Vec<u8>) -> Option<Font> {
        Self::from_data(Arc::new(bytes), 0)
    }

    /// `from_data` parses one face from shared font-file storage.
    ///
    /// Use face index zero for a single-face file. It returns `None` when the
    /// index or font data is invalid.
    pub fn from_data(data: FontData, face_index: u32) -> Option<Font> {
        Self::parse_face(data, face_index, None)
    }

    /// `from_data_with_remote_id` parses one face whose glyphs another process renders.
    ///
    /// It is [`Self::from_data`] for a font that names its face to that process by
    /// `remote_id`, which [`Self::remote_id`] answers.
    pub fn from_data_with_remote_id(
        data: FontData,
        face_index: u32,
        remote_id: u64,
    ) -> Option<Font> {
        Self::parse_face(data, face_index, Some(remote_id))
    }

    /// `instances_from_data` parses the registrable instances of one face.
    ///
    /// Static fonts produce one item. Variable fonts with named instances
    /// produce one [`Font`] per instance. Invalid data returns an empty vector.
    pub fn instances_from_data(data: FontData, face_index: u32) -> Vec<Font> {
        Self::parse_instances(data, face_index, None)
    }

    /// `instances_from_data_with_remote_id` parses the registrable instances of one face
    /// whose glyphs another process renders.
    ///
    /// It is [`Self::instances_from_data`] for a face that [`Self::from_data_with_remote_id`]
    /// describes: every instance answers `remote_id` from [`Self::remote_id`].
    pub fn instances_from_data_with_remote_id(
        data: FontData,
        face_index: u32,
        remote_id: u64,
    ) -> Vec<Font> {
        Self::parse_instances(data, face_index, Some(remote_id))
    }

    /// [`Self::from_data`], with the face's remote id if it has one.
    fn parse_face(data: FontData, face_index: u32, remote_id: Option<u64>) -> Option<Font> {
        let (data, face_index) = unwrapped(data, face_index)?;
        Self::instance(data, face_index, remote_id, Vec::new())
    }

    /// [`Self::instances_from_data`], with the face's remote id if it has one.
    fn parse_instances(data: FontData, face_index: u32, remote_id: Option<u64>) -> Vec<Font> {
        let Some((data, face_index)) = unwrapped(data, face_index) else {
            return Vec::new();
        };
        let instances = named_instance_coordinates((*data).as_ref(), face_index);
        if instances.is_empty() {
            return Self::instance(data, face_index, remote_id, Vec::new())
                .into_iter()
                .collect();
        }
        // The expensive halves (cmap, shaping caches) parse ONCE; each
        // instance adds only its metrics and axis data.
        let Some(shared) = SharedFace::parse(data, face_index, remote_id) else {
            return Vec::new();
        };
        instances
            .into_iter()
            .filter_map(|coordinates| Self::shared_instance(shared.clone(), coordinates))
            .collect()
    }

    /// One face at one set of coordinates, self-described from its tables
    /// (attrs overridden by the coordinates' weight/italic axes).
    fn instance(
        data: FontData,
        face_index: u32,
        remote_id: Option<u64>,
        coordinates: Vec<([u8; 4], f32)>,
    ) -> Option<Font> {
        let shared = SharedFace::parse(data, face_index, remote_id)?;
        Self::shared_instance(shared, coordinates)
    }

    /// [`Self::instance`] over already-shared file state.
    fn shared_instance(shared: Arc<SharedFace>, coordinates: Vec<([u8; 4], f32)>) -> Option<Font> {
        let bytes: &[u8] = (*shared.data).as_ref();
        let (family, aliases) = embedded_names(bytes, shared.face_index)?;
        let attrs = instance_attrs(embedded_attrs(bytes, shared.face_index), &coordinates);
        let mut font = Font::at_coordinates(shared, &family, attrs, coordinates)?;
        for name in &aliases {
            font.add_alias(name);
        }
        Some(font)
    }
}

impl SharedFace {
    fn parse(data: FontData, face_index: u32, remote_id: Option<u64>) -> Option<Arc<Self>> {
        let bytes: &[u8] = (*data).as_ref();
        let font = skrifa::FontRef::from_index(bytes, face_index).ok()?;
        let charmap = font
            .charmap()
            .mappings()
            .map(|(code, glyph)| (code, glyph.to_u32()))
            .collect();
        let harf = harfrust::FontRef::from_index(bytes, face_index).ok()?;
        let shaper_data = harfrust::ShaperData::new(&harf);
        Some(Arc::new(Self {
            data,
            face_index,
            remote_id,
            charmap,
            shaper_data,
        }))
    }
}

/// The (tag, value) coordinate rows of every fvar named instance.
fn named_instance_coordinates(bytes: &[u8], face_index: u32) -> Vec<Vec<([u8; 4], f32)>> {
    let Ok(font) = skrifa::FontRef::from_index(bytes, face_index) else {
        return Vec::new();
    };
    let axis_tags: Vec<[u8; 4]> = font
        .axes()
        .iter()
        .map(|axis| axis.tag().to_be_bytes())
        .collect();
    font.named_instances()
        .iter()
        .map(|instance| {
            axis_tags
                .iter()
                .copied()
                .zip(instance.user_coords())
                .collect()
        })
        .collect()
}

/// A named instance's place in its family: the weight/italic/width axes
/// override what the file's default-instance OS/2 table says.
fn instance_attrs(base: FontAttrs, coordinates: &[([u8; 4], f32)]) -> FontAttrs {
    let mut attrs = base;
    for (tag, value) in coordinates {
        match tag {
            b"wght" => attrs.weight = value.clamp(1.0, 1000.0) as u16,
            b"ital" => attrs.italic = *value >= 0.5,
            b"slnt" => attrs.italic = attrs.italic || *value < 0.0,
            // `wdth` is already a percentage, which is what CSS asks for.
            b"wdth" => attrs.stretch = value.clamp(1.0, 1000.0),
            _ => {}
        }
    }
    attrs
}

/// How far `candidate` is from `wanted`, as the sort key of CSS font
/// matching's precedence: width, then style, then weight.
fn style_distance(candidate: FontAttrs, wanted: FontAttrs) -> (u32, bool, u16) {
    (
        stretch_distance(candidate.stretch, wanted.stretch),
        candidate.italic != wanted.italic,
        candidate.weight.abs_diff(wanted.weight),
    )
}

/// Ordered width distance for variant matching. Quantized to 1/16 of a
/// percent so it can be an integer sort key without collapsing the named
/// widths (they are 12.5 apart at the closest).
fn stretch_distance(candidate: f32, wanted: f32) -> u32 {
    ((candidate - wanted).abs() * 16.0) as u32
}

/// WOFF2 arrives brotli-wrapped; faces parse the unwrapped TrueType bytes
/// (icon and web fonts ship compressed — the CoreText managers accept
/// them, so registration here does too). Identity for everything else.
/// A collection face is emitted as its own single-face SFNT, so the
/// returned index is always zero after unwrap.
#[cfg(feature = "woff2")]
fn unwrapped(data: FontData, face_index: u32) -> Option<(FontData, u32)> {
    let bytes: &[u8] = (*data).as_ref();
    if !bytes.starts_with(b"wOF2") {
        return Some((data, face_index));
    }
    let unpacked = crate::woff2::to_sfnt(bytes, face_index)?;
    Some((Arc::new(unpacked), 0))
}

#[cfg(not(feature = "woff2"))]
fn unwrapped(data: FontData, face_index: u32) -> Option<(FontData, u32)> {
    Some((data, face_index))
}

/// name table: the primary is the en typographic family (then en family,
/// then any-language); every other family/typographic-family string rides
/// along as an alias.
fn embedded_names(data: &[u8], face_index: u32) -> Option<(String, Vec<String>)> {
    use swash::StringId;
    let font = swash::FontRef::from_index(data, face_index as usize)?;
    let strings = font.localized_strings();
    let pick = |id: StringId| {
        strings
            .find_by_id(id, Some("en"))
            .or_else(|| strings.find_by_id(id, None))
            .map(|s| s.to_string())
    };
    let primary = pick(StringId::TypographicFamily).or_else(|| pick(StringId::Family))?;
    let aliases = strings
        .filter(|s| matches!(s.id(), StringId::Family | StringId::TypographicFamily))
        .map(|s| s.to_string())
        .filter(|name| *name != primary)
        .collect();
    Some((primary, aliases))
}

/// OS/2 weight + width + style flags via swash attributes.
fn embedded_attrs(data: &[u8], face_index: u32) -> FontAttrs {
    let Some(font) = swash::FontRef::from_index(data, face_index as usize) else {
        return FontAttrs::default();
    };
    let attrs = font.attributes();
    FontAttrs {
        weight: attrs.weight().0,
        italic: attrs.style() != swash::Style::Normal,
        stretch: attrs.stretch().to_percentage(),
    }
}

/// Unicode Private Use Areas — codepoints whose meaning belongs to a
/// specific registered font, never to a generic fallback source.
fn is_private_use(codepoint: char) -> bool {
    matches!(
        codepoint,
        '\u{E000}'..='\u{F8FF}' | '\u{F0000}'..='\u{FFFFD}' | '\u{100000}'..='\u{10FFFD}'
    )
}

/// `FontCollection` owns registered faces and sources for resolving missing fonts.
///
/// Paragraph building consults sources in order and registers their answers.
/// Unanswered requests accumulate until [`Self::take_unanswered`] is called.
#[derive(Default)]
pub struct FontCollection {
    faces: FaceSet,
    /// Consulted in order, first answer wins (Skia's manager priority:
    /// registered bytes and downloaders before the platform database).
    sources: Vec<Box<dyn FontSource>>,
    /// Misses no source answered, since the last drain.
    unanswered: FontDemand,
}

impl FontCollection {
    /// `new` creates an empty collection with no font sources.
    pub fn new() -> FontCollection {
        FontCollection::default()
    }

    /// `faces` returns the faces currently registered in the collection.
    ///
    /// A built paragraph clones this set and remains independent of later changes.
    pub fn faces(&self) -> &FaceSet {
        &self.faces
    }

    /// `register` adds font bytes under a family using default attributes.
    ///
    /// It returns `None` when face zero cannot be parsed.
    pub fn register(&mut self, family: &str, bytes: Vec<u8>) -> Option<FontId> {
        self.faces.register(family, bytes)
    }

    /// `add` registers an already parsed font.
    pub fn add(&mut self, font: Font) -> FontId {
        self.faces.add(font)
    }

    /// `add_fallback` appends a registered font to the global fallback order.
    ///
    /// `id` must belong to this collection.
    pub fn add_fallback(&mut self, id: FontId) {
        self.faces.add_fallback(id);
    }

    /// `get` returns a registered font by identifier.
    ///
    /// # Panics
    ///
    /// Panics if `id` does not belong to this collection.
    pub fn get(&self, id: FontId) -> &Font {
        self.faces.get(id)
    }

    /// `len` returns the number of registered fonts.
    pub fn len(&self) -> usize {
        self.faces.len()
    }

    /// `family` returns the first font matching a family name or alias.
    pub fn family(&self, name: &str) -> Option<FontId> {
        self.faces.family(name)
    }

    /// `add_source` appends a source consulted when registered fonts cannot satisfy a request.
    pub fn add_source(&mut self, source: impl FontSource + 'static) {
        self.sources.push(Box::new(source));
    }

    /// `add_boxed_source` appends an already boxed font source.
    pub fn add_boxed_source(&mut self, source: Box<dyn FontSource>) {
        self.sources.push(source);
    }

    /// `is_empty` reports whether no fonts are currently registered.
    pub fn is_empty(&self) -> bool {
        self.faces.is_empty()
    }

    /// `adopt_faces` replaces the registered faces with a prepared set.
    ///
    /// This supports hosts that answer [`FontDemand`] using [`FaceSet::grown_by`].
    pub fn adopt_faces(&mut self, faces: FaceSet) {
        self.faces = faces;
    }

    /// `take_unanswered` drains font requests that no source could satisfy.
    ///
    /// Hosts may load and [`Self::register`] matching fonts before rebuilding
    /// affected paragraphs.
    pub fn take_unanswered(&mut self) -> FontDemand {
        std::mem::take(&mut self.unanswered)
    }

    /// Resolution with growth: look up, else ask the sources in order,
    /// registering what they answer (Skia's `findTypefaces` walking its
    /// managers). `false` = nobody had it; the miss is recorded.
    pub(crate) fn require_family(&mut self, name: &str) -> bool {
        if self.faces.family(name).is_some() {
            return true;
        }
        for source in &mut self.sources {
            let faces = source.family(name);
            if self.faces.register_answers(faces, name) {
                return true;
            }
        }
        self.unanswered.add_family(name);
        false
    }

    /// The per-codepoint half (Skia's `defaultFallback(unicode, ..)`).
    pub(crate) fn require_codepoint(
        &mut self,
        families: &[String],
        codepoint: char,
        attrs: FontAttrs,
    ) -> bool {
        if self.faces.covered_by_resolution(families, attrs, codepoint) {
            return true;
        }
        for index in 0..self.sources.len() {
            let (head, tail) = self.sources.split_at_mut(index);
            let _ = head;
            let source = &mut tail[0];
            if self
                .faces
                .register_fallback_answer(source.as_mut(), codepoint, attrs)
            {
                return true;
            }
        }
        self.unanswered.add_codepoint(codepoint, attrs);
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fira() -> FontData {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../assets/fonts/fira_sans.ttf"
        );
        Arc::new(std::fs::read(path).unwrap())
    }

    /// A variable face's named instances are built over its one shared
    /// parse, each at its own coordinates — the path `parse_instances`
    /// takes, driven here directly because no test font is variable. The
    /// process rendering the glyphs tells instances apart by their
    /// coordinates, so every one must still name the face it came from.
    #[test]
    fn named_instances_answer_their_face_remote_id() {
        let shared = SharedFace::parse(fira(), 0, Some(7)).unwrap();
        for weight in [300.0, 700.0] {
            let instance = Font::shared_instance(shared.clone(), vec![(*b"wght", weight)]).unwrap();
            assert_eq!(instance.remote_id(), Some(7));
            assert_eq!(instance.variation_coordinates(), &[(*b"wght", weight)]);
        }
    }
}