f-office-fonts 0.3.0

Font database, metrics and outlines.
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
//! The layout values of a face: every value of a face that the layout reads, keyed by Unicode
//! character and not by glyph, so that two faces with another glyph order compare as equal.
//!
//! [`FontDb::layout_values`] reads them through the same methods of the database that the
//! layout calls, and [`Comparison`] compares two faces' values exactly, with no tolerance.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use crate::{
    FontDb, FontId, KerningSource, MathCorner, PathCommand, ScriptLevel, ShapeRequest, ShapedScript,
};

mod compare;
pub use compare::{Comparison, Difference, KindComparison};

/// A category of font layout values compared between two faces.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum ValueKind {
    /// The characters that the face maps, as [`FontDb::glyph_id`] maps them.
    Characters,
    /// Each character's advance ([`FontDb::advance`]).
    Advance,
    /// Each character's box: the least and greatest x and y of all points of its outline,
    /// control points too ([`FontDb::outline`]), as the layout takes a glyph's ink.
    Box,
    /// The kerning of each pair from the face's own source ([`FontDb::kerning`]), and the
    /// source that [`FontDb::kerning_source`] chooses.
    Kerning,
    /// The kerning of each pair from the `kern` table ([`FontDb::kerning_from`] with
    /// [`KerningSource::KernTable`]), and [`FontDb::has_kern_table`].
    KernTable,
    /// The face's metrics ([`FontDb::metrics`]): units per em and the values of `hhea`, `OS/2`
    /// and `post` that it holds.
    LineValues,
    /// The values of [`FontDb::info`] that font selection reads: weight, italic, PANOSE and
    /// the East Asian code pages. The names and the version are left out: an open font has
    /// names and a version of its own.
    Selection,
    /// The heights of `VDMX` at each size ([`FontDb::device_heights`]).
    PixelHeights,
    /// Each character's bi-level advance at each size ([`FontDb::bi_level_advance`]).
    BiLevelAdvance,
    /// Each character's device width at each size ([`FontDb::device_width`]).
    DeviceWidth,
    /// The standard ligatures of each sequence of characters that the face joins
    /// ([`FontDb::ligatures`]): where each starts, how many characters it takes, and its
    /// glyph's advance and box.
    Ligatures,
    /// The other glyphs that a character takes: its script glyphs
    /// ([`FontDb::script_glyph`]), its flattened accent ([`FontDb::flattened_accent`]) and its
    /// dotless form ([`FontDb::dotless_form`]), each by the glyph's advance and box.
    Forms,
    /// The values of the `MATH` table that the layout reads: the constants and each
    /// character's values.
    Math,
    /// The glyphs that shaping gives each character of a script that the layout shapes
    /// ([`FontDb::shape`]): the character alone and three times in a row, which gives a
    /// joining letter its first, middle and last forms. Longer clusters, such as Devanagari
    /// conjuncts, are not compared.
    Shaping,
}

impl ValueKind {
    /// Every value kind in canonical order.
    pub const ALL: [Self; 14] = [
        Self::Characters,
        Self::Advance,
        Self::Box,
        Self::Kerning,
        Self::KernTable,
        Self::LineValues,
        Self::Selection,
        Self::PixelHeights,
        Self::BiLevelAdvance,
        Self::DeviceWidth,
        Self::Ligatures,
        Self::Forms,
        Self::Math,
        Self::Shaping,
    ];

    /// The kebab-case name of this value kind.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Characters => "characters",
            Self::Advance => "advance",
            Self::Box => "box",
            Self::Kerning => "kerning",
            Self::KernTable => "kern-table",
            Self::LineValues => "line-values",
            Self::Selection => "selection",
            Self::PixelHeights => "pixel-heights",
            Self::BiLevelAdvance => "bi-level",
            Self::DeviceWidth => "device-width",
            Self::Ligatures => "ligatures",
            Self::Forms => "forms",
            Self::Math => "math",
            Self::Shaping => "shaping",
        }
    }

    /// The kind of the name `name`, as [`ValueKind::name`] gives it.
    #[must_use]
    pub fn named(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|kind| kind.name() == name)
    }

    /// Whether the kind's values are in whole pixels; else they are in font units, or a
    /// count, a flag or a class.
    #[must_use]
    pub const fn in_pixels(self) -> bool {
        matches!(
            self,
            Self::PixelHeights | Self::BiLevelAdvance | Self::DeviceWidth
        )
    }

    /// The values of a place that a face does not list: 0 for a pair's kerning, which a face
    /// gives every pair that it does not list; none for the other kinds, where a missing place
    /// is a difference.
    const fn unlisted(self) -> Option<&'static [i64]> {
        match self {
            Self::Kerning | Self::KernTable => Some(&[0]),
            _ => None,
        }
    }
}

/// Where a layout value is.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Place {
    /// A value of the whole face, by its name.
    Face(&'static str),
    /// A character.
    Character(char),
    /// A pair of characters.
    Pair(char, char),
    /// A size in pixels per em.
    Size(u16),
    /// A character at a size in pixels per em.
    CharacterAt(char, u16),
    /// A sequence of characters.
    Sequence(Vec<char>),
    /// A named value of a character.
    CharacterValue(char, &'static str),
}

impl Place {
    /// The characters that the place names.
    #[must_use]
    pub fn characters(&self) -> Vec<char> {
        match self {
            Self::Face(_) | Self::Size(_) => Vec::new(),
            Self::Character(c) | Self::CharacterAt(c, _) | Self::CharacterValue(c, _) => {
                vec![*c]
            }
            Self::Pair(a, b) => vec![*a, *b],
            Self::Sequence(characters) => characters.clone(),
        }
    }
}

impl Place {
    /// The size in pixels per em that the place names, if any.
    #[must_use]
    pub const fn size(&self) -> Option<u16> {
        match self {
            Self::Size(size) | Self::CharacterAt(_, size) => Some(*size),
            _ => None,
        }
    }
}

impl fmt::Display for Place {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let code = |c: &char| format!("U+{:04X}", u32::from(*c));
        match self {
            Self::Face(name) => f.write_str(name),
            Self::Character(c) => f.write_str(&code(c)),
            Self::Pair(a, b) => write!(f, "{} {}", code(a), code(b)),
            Self::Size(size) => write!(f, "{size} px"),
            Self::CharacterAt(c, size) => write!(f, "{} at {size} px", code(c)),
            Self::Sequence(characters) => {
                let codes: Vec<String> = characters.iter().map(code).collect();
                f.write_str(&codes.join(" "))
            }
            Self::CharacterValue(c, name) => write!(f, "{} {name}", code(c)),
        }
    }
}

/// The values of one place: numbers in the kind's unit, or no number for a place whose
/// presence is the value, such as a mapped character.
pub type Values = Vec<i64>;

/// The layout values of one face.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LayoutValues {
    units_per_em: u16,
    sizes: Vec<u16>,
    values: BTreeMap<ValueKind, BTreeMap<Place, Values>>,
}

impl LayoutValues {
    /// The face's units per em.
    #[must_use]
    pub const fn units_per_em(&self) -> u16 {
        self.units_per_em
    }

    /// The sizes in pixels per em at which the values of the kinds in pixels were read.
    #[must_use]
    pub fn sizes(&self) -> &[u16] {
        &self.sizes
    }

    /// The values of one kind, by place.
    #[must_use]
    pub fn of(&self, kind: ValueKind) -> Option<&BTreeMap<Place, Values>> {
        self.values.get(&kind)
    }

    /// The characters that the face maps.
    pub fn characters(&self) -> impl Iterator<Item = char> + '_ {
        self.values
            .get(&ValueKind::Characters)
            .into_iter()
            .flat_map(BTreeMap::keys)
            .flat_map(Place::characters)
    }

    /// Keeps only the places whose characters all lie in `range`; the values of the whole
    /// face and of sizes stay.
    pub fn keep_characters(&mut self, range: std::ops::RangeInclusive<char>) {
        for places in self.values.values_mut() {
            places.retain(|place, _| place.characters().iter().all(|c| range.contains(c)));
        }
    }
}

impl FontDb {
    /// Returns the layout values of face `id`, with the values in pixels at each size of
    /// `sizes` (pixels per em).
    ///
    /// Each value comes from the method of the database that the layout calls for it. The
    /// pairs whose kerning it reads are those that the face's tables list with a value; every
    /// other pair has the kerning 0. Returns `None` for an unknown face.
    #[must_use]
    pub fn layout_values(&self, id: FontId, sizes: &[u16]) -> Option<LayoutValues> {
        let metrics = self.metrics(id)?;
        let mut reader = Reader {
            db: self,
            id,
            glyphs: mapped_characters(self, id),
            values: BTreeMap::new(),
        };
        reader.characters();
        reader.kerning();
        reader.line_values();
        reader.selection();
        reader.pixels(sizes);
        reader.ligatures();
        reader.forms();
        reader.math(metrics.units_per_em);
        reader.shaping();
        Some(LayoutValues {
            units_per_em: metrics.units_per_em,
            sizes: sizes.to_vec(),
            values: reader.values,
        })
    }
}

/// The characters that face `id` maps, with their glyphs, as [`FontDb::glyph_id`] maps them:
/// the codes of its Unicode character map, and the codes from U+0000 to U+00FF, which a symbol
/// character map takes at U+F000 to U+F0FF.
fn mapped_characters(db: &FontDb, id: FontId) -> BTreeMap<char, u32> {
    let listed: Vec<u32> = db
        .face(id)
        .and_then(crate::face::Face::font)
        .map_or_else(Vec::new, |font| {
            font.charmap().unicodes().map(|(code, _)| code).collect()
        });
    listed
        .into_iter()
        .chain(0..=0xFF)
        .filter_map(char::from_u32)
        .filter_map(|c| Some((c, db.glyph_id(id, c)?)))
        .collect()
}

/// Reads the layout values of one face.
struct Reader<'a> {
    db: &'a FontDb,
    id: FontId,
    glyphs: BTreeMap<char, u32>,
    values: BTreeMap<ValueKind, BTreeMap<Place, Values>>,
}

/// A whole number as a value.
fn number(value: impl Into<i64>) -> i64 {
    value.into()
}

/// A flag as a value: 1 when set.
fn flag(set: bool) -> i64 {
    i64::from(set)
}

impl Reader<'_> {
    fn put(&mut self, kind: ValueKind, place: Place, values: Values) {
        self.values.entry(kind).or_default().insert(place, values);
    }

    /// The characters of each glyph of the face's map.
    fn characters_of(&self) -> BTreeMap<u32, Vec<char>> {
        let mut by_glyph: BTreeMap<u32, Vec<char>> = BTreeMap::new();
        for (&c, &glyph) in &self.glyphs {
            by_glyph.entry(glyph).or_default().push(c);
        }
        by_glyph
    }

    /// The advance and the box of a glyph, for a glyph that a character takes in place of its
    /// own.
    fn glyph_values(&self, glyph: u32) -> Values {
        let mut values: Values = self
            .db
            .advance(self.id, glyph)
            .map(number)
            .into_iter()
            .collect();
        values.extend(glyph_box(self.db, self.id, glyph));
        values
    }

    fn characters(&mut self) {
        let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
        for (c, glyph) in glyphs {
            self.put(ValueKind::Characters, Place::Character(c), Vec::new());
            if let Some(advance) = self.db.advance(self.id, glyph) {
                self.put(
                    ValueKind::Advance,
                    Place::Character(c),
                    vec![number(advance)],
                );
            }
            let shape = glyph_box(self.db, self.id, glyph);
            self.put(ValueKind::Box, Place::Character(c), shape);
        }
    }

    fn kerning(&mut self) {
        let source = self.db.kerning_source(self.id);
        let gpos = source == KerningSource::Gpos;
        self.put(
            ValueKind::Kerning,
            Place::Face("source is GPOS"),
            vec![flag(gpos)],
        );
        let table = self.db.has_kern_table(self.id);
        self.put(
            ValueKind::KernTable,
            Place::Face("has a kern table"),
            vec![flag(table)],
        );
        let glyphs: BTreeSet<u32> = self.glyphs.values().copied().collect();
        let by_glyph = self.characters_of();
        for (left, right) in self.db.listed_kerning_pairs(self.id, &glyphs) {
            let values = [
                (ValueKind::Kerning, self.db.kerning(self.id, left, right)),
                (
                    ValueKind::KernTable,
                    self.db
                        .kerning_from(self.id, left, right, KerningSource::KernTable),
                ),
            ];
            for (kind, value) in values {
                if value != 0 {
                    self.put_pairs(kind, &by_glyph, (left, right), value);
                }
            }
        }
    }

    /// Puts the kerning `value` of a glyph pair at each pair of characters that maps to it.
    fn put_pairs(
        &mut self,
        kind: ValueKind,
        by_glyph: &BTreeMap<u32, Vec<char>>,
        (left, right): (u32, u32),
        value: i32,
    ) {
        let lefts = by_glyph.get(&left).map_or(&[][..], Vec::as_slice);
        let rights = by_glyph.get(&right).map_or(&[][..], Vec::as_slice);
        for &a in lefts {
            for &b in rights {
                self.put(kind, Place::Pair(a, b), vec![number(value)]);
            }
        }
    }

    fn line_values(&mut self) {
        let Some(metrics) = self.db.metrics(self.id) else {
            return;
        };
        for (name, value) in metric_fields(metrics) {
            self.put(ValueKind::LineValues, Place::Face(name), vec![value]);
        }
    }

    fn selection(&mut self) {
        let Some(info) = self.db.info(self.id) else {
            return;
        };
        let classification = &info.classification;
        let mut fields = vec![
            ("weight", number(info.weight)),
            ("italic", flag(info.italic)),
            ("PANOSE weight", number(info.panose_weight)),
            ("East Asian code pages", flag(classification.east_asian)),
        ];
        let panose = PANOSE_NAMES.iter().zip(classification.panose);
        fields.extend(panose.map(|(&name, value)| (name, number(value))));
        for (name, value) in fields {
            self.put(ValueKind::Selection, Place::Face(name), vec![value]);
        }
    }

    /// The values in pixels at each size: the heights of `VDMX`, and each character's
    /// bi-level advance and device width.
    fn pixels(&mut self, sizes: &[u16]) {
        for &size in sizes {
            if let Some((above, below)) = self.db.device_heights(self.id, size) {
                let values = vec![number(above), number(below)];
                self.put(ValueKind::PixelHeights, Place::Size(size), values);
            }
        }
        for (glyph, characters) in self.characters_of() {
            for &size in sizes {
                let bi_level = self.db.bi_level_advance(self.id, glyph, size);
                let device = self.db.device_width(self.id, glyph, size);
                for &c in &characters {
                    let at = Place::CharacterAt(c, size);
                    if let Some(width) = bi_level {
                        self.put(ValueKind::BiLevelAdvance, at.clone(), vec![number(width)]);
                    }
                    if let Some(width) = device {
                        self.put(ValueKind::DeviceWidth, at, vec![number(width)]);
                    }
                }
            }
        }
    }

    /// The ligatures of each sequence of characters whose glyphs the face's standard
    /// ligatures join.
    fn ligatures(&mut self) {
        let by_glyph = self.characters_of();
        for glyphs in self.db.ligature_sequences(self.id) {
            let mut values = Vec::new();
            for ligature in self.db.ligatures(self.id, &glyphs) {
                values.push(count(ligature.start));
                values.push(count(ligature.len));
                values.extend(self.glyph_values(ligature.glyph));
            }
            for characters in sequences_of(&glyphs, &by_glyph) {
                self.put(
                    ValueKind::Ligatures,
                    Place::Sequence(characters),
                    values.clone(),
                );
            }
        }
    }

    /// The script glyphs, flattened accents and dotless forms of each character.
    fn forms(&mut self) {
        let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
        for (c, glyph) in glyphs {
            let forms = [
                (
                    "script glyph",
                    self.db.script_glyph(self.id, glyph, ScriptLevel::Script),
                ),
                (
                    "script-of-script glyph",
                    self.db
                        .script_glyph(self.id, glyph, ScriptLevel::ScriptOfScript),
                ),
                ("flattened accent", self.db.flattened_accent(self.id, glyph)),
                ("dotless form", self.db.dotless_form(self.id, glyph)),
            ];
            for (name, form) in forms {
                if let Some(form) = form {
                    let values = self.glyph_values(form);
                    self.put(ValueKind::Forms, Place::CharacterValue(c, name), values);
                }
            }
        }
    }

    /// The constants of the `MATH` table and each character's values in it.
    fn math(&mut self, units_per_em: u16) {
        for (name, value) in math_constants(self.db, self.id) {
            self.put(ValueKind::Math, Place::Face(name), vec![value]);
        }
        let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
        for (c, glyph) in glyphs {
            for (name, values) in self.math_values(glyph, units_per_em) {
                self.put(ValueKind::Math, Place::CharacterValue(c, name), values);
            }
        }
    }

    /// The values of one glyph in the `MATH` table: its italic correction, its top accent
    /// attachment, its display variant, its vertical variant for the heights 0, half an em,
    /// an em, one and a half, two and three ems and the greatest height, its horizontal
    /// construction, and its math kerning at each corner at the heights 0, half an em and an
    /// em.
    fn math_values(&self, glyph: u32, units_per_em: u16) -> Vec<(&'static str, Values)> {
        let (db, id) = (self.db, self.id);
        let mut found = Vec::new();
        if let Some(value) = db.italic_correction(id, glyph) {
            found.push(("italic correction", vec![number(value)]));
        }
        if let Some(value) = db.top_accent_attachment(id, glyph) {
            found.push(("top accent attachment", vec![number(value)]));
        }
        if let Some(variant) = db.display_variant(id, glyph) {
            found.push(("display variant", self.glyph_values(variant)));
        }
        let em = i32::from(units_per_em);
        let heights = [0, em / 2, em, em * 3 / 2, em * 2, em * 3, i32::MAX];
        let variants: Vec<Values> = heights
            .iter()
            .filter_map(|&least| db.vertical_variant(id, glyph, least))
            .map(|(variant, reached)| {
                let mut values = self.glyph_values(variant);
                values.push(flag(reached));
                values
            })
            .collect();
        if !variants.is_empty() {
            found.push(("vertical variants", variants.concat()));
        }
        if let Some(construction) = db.horizontal_construction(id, glyph) {
            found.push(("horizontal construction", self.construction(&construction)));
        }
        found.extend(math_kerning(db, id, glyph, units_per_em));
        found
    }

    /// The glyphs that shaping gives each mapped character of a script that the layout
    /// shapes, alone and three times in a row: each glyph's cluster, advance, offset and
    /// glyph values. A text that does not shape has no values.
    fn shaping(&mut self) {
        let shaped: Vec<(char, ShapedScript)> = self
            .glyphs
            .keys()
            .filter_map(|&c| Some((c, ShapedScript::of(c)?)))
            .collect();
        for (c, script) in shaped {
            for repeat in [1, 3] {
                let text: String = std::iter::repeat_n(c, repeat).collect();
                let request = ShapeRequest {
                    text: &text,
                    script,
                    direction: script.direction(),
                    language: None,
                };
                let Ok(glyphs) = self.db.shape(self.id, &request) else {
                    continue;
                };
                let mut values = Vec::new();
                for glyph in glyphs {
                    values.push(count(glyph.cluster));
                    values.push(number(glyph.advance));
                    values.push(number(glyph.offset.0));
                    values.push(number(glyph.offset.1));
                    values.extend(self.glyph_values(glyph.glyph));
                }
                let place = Place::Sequence(vec![c; repeat]);
                self.put(ValueKind::Shaping, place, values);
            }
        }
    }

    /// A horizontal construction as values: each variant's measurement and glyph values, and
    /// each part's full advance, extender flag and glyph values.
    fn construction(&self, construction: &crate::HorizontalConstruction) -> Values {
        let mut values = vec![count(construction.variants.len())];
        for &(variant, measurement) in &construction.variants {
            values.push(number(measurement));
            values.extend(self.glyph_values(variant));
        }
        values.push(count(construction.assembly.len()));
        for part in &construction.assembly {
            values.push(number(part.full_advance));
            values.push(flag(part.extender));
            values.extend(self.glyph_values(part.glyph));
        }
        values
    }
}

/// A count or an index as a value.
fn count(value: usize) -> i64 {
    i64::try_from(value).unwrap_or(i64::MAX)
}

/// A whole number of font units, which a glyph's coordinates are far inside.
#[expect(
    clippy::cast_possible_truncation,
    reason = "a glyph's coordinates are font units, far inside i64, and are whole when this \
              is called"
)]
fn font_units(value: f32) -> i64 {
    value as i64
}

/// The box of a glyph: the least x, the least y, the greatest x and the greatest y of all
/// points of its outline, control points too, the least down and the greatest up to whole
/// font units, as the layout takes a glyph's ink; none for a glyph without points or whose
/// outline does not read. A TrueType glyph's points are whole font units already.
fn glyph_box(db: &FontDb, id: FontId, glyph: u32) -> Values {
    let Ok(outline) = db.outline(id, glyph) else {
        return Vec::new();
    };
    let points = outline.iter().flat_map(|command| match *command {
        PathCommand::MoveTo(p) | PathCommand::LineTo(p) => vec![p],
        PathCommand::QuadTo(c, p) => vec![c, p],
        PathCommand::CubicTo(c, d, p) => vec![c, d, p],
        PathCommand::Close => Vec::new(),
    });
    let mut bounds: Option<[f32; 4]> = None;
    for p in points {
        let [x0, y0, x1, y1] = bounds.unwrap_or([p.x, p.y, p.x, p.y]);
        bounds = Some([x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)]);
    }
    bounds.map_or_else(Vec::new, |[x0, y0, x1, y1]| {
        vec![
            font_units(x0.floor()),
            font_units(y0.floor()),
            font_units(x1.ceil()),
            font_units(y1.ceil()),
        ]
    })
}

/// The sequences of characters whose glyphs are `glyphs`, each glyph by each of its
/// characters; none when a glyph has no character.
fn sequences_of(glyphs: &[u32], by_glyph: &BTreeMap<u32, Vec<char>>) -> Vec<Vec<char>> {
    let mut sequences: Vec<Vec<char>> = vec![Vec::new()];
    for glyph in glyphs {
        let characters = by_glyph.get(glyph).map_or(&[][..], Vec::as_slice);
        sequences = sequences
            .iter()
            .flat_map(|start| {
                characters.iter().map(move |&c| {
                    let mut next = start.clone();
                    next.push(c);
                    next
                })
            })
            .collect();
    }
    sequences
}

/// The names of the ten PANOSE numbers.
const PANOSE_NAMES: [&str; 10] = [
    "PANOSE family",
    "PANOSE serif",
    "PANOSE weight number",
    "PANOSE proportion",
    "PANOSE contrast",
    "PANOSE stroke",
    "PANOSE arm",
    "PANOSE letterform",
    "PANOSE midline",
    "PANOSE x height",
];

/// Each field of a face's metrics, by name.
fn metric_fields(metrics: &crate::FontMetrics) -> Vec<(&'static str, i64)> {
    let hhea = metrics.hhea;
    let mut fields = vec![
        ("units per em", number(metrics.units_per_em)),
        ("hhea ascender", number(hhea.ascender)),
        ("hhea descender", number(hhea.descender)),
        ("hhea line gap", number(hhea.line_gap)),
    ];
    if let Some(underline) = metrics.underline {
        fields.push(("post underline position", number(underline.position)));
        fields.push(("post underline thickness", number(underline.thickness)));
    }
    if let Some(os2) = metrics.os2 {
        fields.extend(os2_fields(&os2));
    }
    fields
}

/// Each field of the `OS/2` metrics, by name.
fn os2_fields(os2: &crate::Os2Metrics) -> Vec<(&'static str, i64)> {
    let mut fields = vec![
        ("OS/2 average width", number(os2.average_width)),
        ("OS/2 typo ascender", number(os2.typo.ascender)),
        ("OS/2 typo descender", number(os2.typo.descender)),
        ("OS/2 typo line gap", number(os2.typo.line_gap)),
        ("OS/2 win ascent", number(os2.win_ascent)),
        ("OS/2 win descent", number(os2.win_descent)),
        ("OS/2 use typo metrics", flag(os2.use_typo_metrics)),
        ("OS/2 strikeout position", number(os2.strikeout.position)),
        ("OS/2 strikeout size", number(os2.strikeout.thickness)),
        ("OS/2 subscript x size", number(os2.subscript.x_size)),
        ("OS/2 subscript y size", number(os2.subscript.y_size)),
        ("OS/2 subscript x offset", number(os2.subscript.x_offset)),
        ("OS/2 subscript y offset", number(os2.subscript.y_offset)),
        ("OS/2 superscript x size", number(os2.superscript.x_size)),
        ("OS/2 superscript y size", number(os2.superscript.y_size)),
        (
            "OS/2 superscript x offset",
            number(os2.superscript.x_offset),
        ),
        (
            "OS/2 superscript y offset",
            number(os2.superscript.y_offset),
        ),
        ("OS/2 East Asian code pages", flag(os2.east_asian)),
    ];
    if let Some(value) = os2.x_height {
        fields.push(("OS/2 x height", number(value)));
    }
    if let Some(value) = os2.cap_height {
        fields.push(("OS/2 cap height", number(value)));
    }
    fields
}

/// The constants of a face's `MATH` table that the layout reads, by name.
fn math_constants(db: &FontDb, id: FontId) -> Vec<(&'static str, i64)> {
    let mut fields = Vec::new();
    if let Some(accent) = db.math_accent(id) {
        fields.push(("accent base height", number(accent.accent_base_height)));
        let flattened = accent.flattened_accent_base_height;
        fields.push(("flattened accent base height", number(flattened)));
        fields.push((
            "min connector overlap",
            number(accent.min_connector_overlap),
        ));
    }
    if let Some(radical) = db.math_radical(id) {
        fields.extend([
            ("radical vertical gap", number(radical.vertical_gap)),
            ("radical rule thickness", number(radical.rule_thickness)),
            ("radical extra ascender", number(radical.extra_ascender)),
            (
                "radical kern before degree",
                number(radical.kern_before_degree),
            ),
            (
                "radical kern after degree",
                number(radical.kern_after_degree),
            ),
            (
                "radical degree bottom raise",
                number(radical.degree_bottom_raise_percent),
            ),
            (
                "radical flattened accent base height",
                number(radical.flattened_accent_base_height),
            ),
        ]);
    }
    if let Some(bars) = db.math_bars(id) {
        fields.extend([
            ("overbar vertical gap", number(bars.overbar_vertical_gap)),
            (
                "overbar rule thickness",
                number(bars.overbar_rule_thickness),
            ),
            (
                "overbar extra ascender",
                number(bars.overbar_extra_ascender),
            ),
            ("underbar vertical gap", number(bars.underbar_vertical_gap)),
            (
                "underbar rule thickness",
                number(bars.underbar_rule_thickness),
            ),
            (
                "underbar extra descender",
                number(bars.underbar_extra_descender),
            ),
        ]);
    }
    if let Some(skewed) = db.math_skewed_fraction(id) {
        fields.extend([
            (
                "skewed fraction horizontal gap",
                number(skewed.horizontal_gap),
            ),
            ("skewed fraction vertical gap", number(skewed.vertical_gap)),
        ]);
    }
    if let Some(gaps) = db.math_limit_gaps(id) {
        fields.extend([
            ("lower limit gap min", number(gaps.lower_limit_gap_min)),
            ("upper limit gap min", number(gaps.upper_limit_gap_min)),
        ]);
    }
    fields.extend(math_limit_fields(db, id));
    if let Some(space) = db.space_after_script(id) {
        fields.push(("space after script", number(space)));
    }
    fields
}

/// The limit and stretch-stack constants of a face's `MATH` table, by name.
fn math_limit_fields(db: &FontDb, id: FontId) -> Vec<(&'static str, i64)> {
    let mut fields = Vec::new();
    if let Some(limits) = db.math_limits(id) {
        fields.extend([
            ("math leading", number(limits.math_leading)),
            (
                "display operator min height",
                number(limits.display_operator_min_height),
            ),
            (
                "upper limit baseline rise min",
                number(limits.upper_limit_baseline_rise_min),
            ),
            (
                "lower limit baseline drop min",
                number(limits.lower_limit_baseline_drop_min),
            ),
            (
                "superscript baseline drop max",
                number(limits.superscript_baseline_drop_max),
            ),
            (
                "subscript baseline drop min",
                number(limits.subscript_baseline_drop_min),
            ),
            (
                "delimited sub formula min height",
                number(limits.delimited_sub_formula_min_height),
            ),
        ]);
    }
    if let Some(stack) = db.math_stretch_stack(id) {
        fields.extend([
            ("stretch stack top shift up", number(stack.top_shift_up)),
            (
                "stretch stack bottom shift down",
                number(stack.bottom_shift_down),
            ),
            ("stretch stack gap above min", number(stack.gap_above_min)),
            ("stretch stack gap below min", number(stack.gap_below_min)),
            (
                "stretch stack min connector overlap",
                number(stack.min_connector_overlap),
            ),
        ]);
    }
    fields
}

/// A glyph's math kerning at each corner, at the heights 0, half an em and an em.
fn math_kerning(
    db: &FontDb,
    id: FontId,
    glyph: u32,
    units_per_em: u16,
) -> Vec<(&'static str, Values)> {
    let em = i32::from(units_per_em);
    let corners = [
        ("math kerning top right", MathCorner::TopRight),
        ("math kerning top left", MathCorner::TopLeft),
        ("math kerning bottom right", MathCorner::BottomRight),
        ("math kerning bottom left", MathCorner::BottomLeft),
    ];
    corners
        .into_iter()
        .filter_map(|(name, corner)| {
            let values: Option<Values> = [0, em / 2, em]
                .into_iter()
                .map(|height| db.math_kern(id, glyph, corner, height).map(number))
                .collect();
            Some((name, values?))
        })
        .collect()
}

#[cfg(test)]
mod tests;