Skip to main content

f_office_fonts/
layout_values.rs

1//! The layout values of a face: every value of a face that the layout reads, keyed by Unicode
2//! character and not by glyph, so that two faces with another glyph order compare as equal.
3//!
4//! [`FontDb::layout_values`] reads them through the same methods of the database that the
5//! layout calls, and [`Comparison`] compares two faces' values exactly, with no tolerance.
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::fmt;
9
10use crate::{
11    FontDb, FontId, KerningSource, MathCorner, PathCommand, ScriptLevel, ShapeRequest, ShapedScript,
12};
13
14mod compare;
15pub use compare::{Comparison, Difference, KindComparison};
16
17/// A category of font layout values compared between two faces.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19#[non_exhaustive]
20pub enum ValueKind {
21    /// The characters that the face maps, as [`FontDb::glyph_id`] maps them.
22    Characters,
23    /// Each character's advance ([`FontDb::advance`]).
24    Advance,
25    /// Each character's box: the least and greatest x and y of all points of its outline,
26    /// control points too ([`FontDb::outline`]), as the layout takes a glyph's ink.
27    Box,
28    /// The kerning of each pair from the face's own source ([`FontDb::kerning`]), and the
29    /// source that [`FontDb::kerning_source`] chooses.
30    Kerning,
31    /// The kerning of each pair from the `kern` table ([`FontDb::kerning_from`] with
32    /// [`KerningSource::KernTable`]), and [`FontDb::has_kern_table`].
33    KernTable,
34    /// The face's metrics ([`FontDb::metrics`]): units per em and the values of `hhea`, `OS/2`
35    /// and `post` that it holds.
36    LineValues,
37    /// The values of [`FontDb::info`] that font selection reads: weight, italic, PANOSE and
38    /// the East Asian code pages. The names and the version are left out: an open font has
39    /// names and a version of its own.
40    Selection,
41    /// The heights of `VDMX` at each size ([`FontDb::device_heights`]).
42    PixelHeights,
43    /// Each character's bi-level advance at each size ([`FontDb::bi_level_advance`]).
44    BiLevelAdvance,
45    /// Each character's device width at each size ([`FontDb::device_width`]).
46    DeviceWidth,
47    /// The standard ligatures of each sequence of characters that the face joins
48    /// ([`FontDb::ligatures`]): where each starts, how many characters it takes, and its
49    /// glyph's advance and box.
50    Ligatures,
51    /// The other glyphs that a character takes: its script glyphs
52    /// ([`FontDb::script_glyph`]), its flattened accent ([`FontDb::flattened_accent`]) and its
53    /// dotless form ([`FontDb::dotless_form`]), each by the glyph's advance and box.
54    Forms,
55    /// The values of the `MATH` table that the layout reads: the constants and each
56    /// character's values.
57    Math,
58    /// The glyphs that shaping gives each character of a script that the layout shapes
59    /// ([`FontDb::shape`]): the character alone and three times in a row, which gives a
60    /// joining letter its first, middle and last forms. Longer clusters, such as Devanagari
61    /// conjuncts, are not compared.
62    Shaping,
63}
64
65impl ValueKind {
66    /// Every value kind in canonical order.
67    pub const ALL: [Self; 14] = [
68        Self::Characters,
69        Self::Advance,
70        Self::Box,
71        Self::Kerning,
72        Self::KernTable,
73        Self::LineValues,
74        Self::Selection,
75        Self::PixelHeights,
76        Self::BiLevelAdvance,
77        Self::DeviceWidth,
78        Self::Ligatures,
79        Self::Forms,
80        Self::Math,
81        Self::Shaping,
82    ];
83
84    /// The kebab-case name of this value kind.
85    #[must_use]
86    pub const fn name(self) -> &'static str {
87        match self {
88            Self::Characters => "characters",
89            Self::Advance => "advance",
90            Self::Box => "box",
91            Self::Kerning => "kerning",
92            Self::KernTable => "kern-table",
93            Self::LineValues => "line-values",
94            Self::Selection => "selection",
95            Self::PixelHeights => "pixel-heights",
96            Self::BiLevelAdvance => "bi-level",
97            Self::DeviceWidth => "device-width",
98            Self::Ligatures => "ligatures",
99            Self::Forms => "forms",
100            Self::Math => "math",
101            Self::Shaping => "shaping",
102        }
103    }
104
105    /// The kind of the name `name`, as [`ValueKind::name`] gives it.
106    #[must_use]
107    pub fn named(name: &str) -> Option<Self> {
108        Self::ALL.into_iter().find(|kind| kind.name() == name)
109    }
110
111    /// Whether the kind's values are in whole pixels; else they are in font units, or a
112    /// count, a flag or a class.
113    #[must_use]
114    pub const fn in_pixels(self) -> bool {
115        matches!(
116            self,
117            Self::PixelHeights | Self::BiLevelAdvance | Self::DeviceWidth
118        )
119    }
120
121    /// The values of a place that a face does not list: 0 for a pair's kerning, which a face
122    /// gives every pair that it does not list; none for the other kinds, where a missing place
123    /// is a difference.
124    const fn unlisted(self) -> Option<&'static [i64]> {
125        match self {
126            Self::Kerning | Self::KernTable => Some(&[0]),
127            _ => None,
128        }
129    }
130}
131
132/// Where a layout value is.
133#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
134#[non_exhaustive]
135pub enum Place {
136    /// A value of the whole face, by its name.
137    Face(&'static str),
138    /// A character.
139    Character(char),
140    /// A pair of characters.
141    Pair(char, char),
142    /// A size in pixels per em.
143    Size(u16),
144    /// A character at a size in pixels per em.
145    CharacterAt(char, u16),
146    /// A sequence of characters.
147    Sequence(Vec<char>),
148    /// A named value of a character.
149    CharacterValue(char, &'static str),
150}
151
152impl Place {
153    /// The characters that the place names.
154    #[must_use]
155    pub fn characters(&self) -> Vec<char> {
156        match self {
157            Self::Face(_) | Self::Size(_) => Vec::new(),
158            Self::Character(c) | Self::CharacterAt(c, _) | Self::CharacterValue(c, _) => {
159                vec![*c]
160            }
161            Self::Pair(a, b) => vec![*a, *b],
162            Self::Sequence(characters) => characters.clone(),
163        }
164    }
165}
166
167impl Place {
168    /// The size in pixels per em that the place names, if any.
169    #[must_use]
170    pub const fn size(&self) -> Option<u16> {
171        match self {
172            Self::Size(size) | Self::CharacterAt(_, size) => Some(*size),
173            _ => None,
174        }
175    }
176}
177
178impl fmt::Display for Place {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        let code = |c: &char| format!("U+{:04X}", u32::from(*c));
181        match self {
182            Self::Face(name) => f.write_str(name),
183            Self::Character(c) => f.write_str(&code(c)),
184            Self::Pair(a, b) => write!(f, "{} {}", code(a), code(b)),
185            Self::Size(size) => write!(f, "{size} px"),
186            Self::CharacterAt(c, size) => write!(f, "{} at {size} px", code(c)),
187            Self::Sequence(characters) => {
188                let codes: Vec<String> = characters.iter().map(code).collect();
189                f.write_str(&codes.join(" "))
190            }
191            Self::CharacterValue(c, name) => write!(f, "{} {name}", code(c)),
192        }
193    }
194}
195
196/// The values of one place: numbers in the kind's unit, or no number for a place whose
197/// presence is the value, such as a mapped character.
198pub type Values = Vec<i64>;
199
200/// The layout values of one face.
201#[derive(Clone, Debug, Default, PartialEq)]
202pub struct LayoutValues {
203    units_per_em: u16,
204    sizes: Vec<u16>,
205    values: BTreeMap<ValueKind, BTreeMap<Place, Values>>,
206}
207
208impl LayoutValues {
209    /// The face's units per em.
210    #[must_use]
211    pub const fn units_per_em(&self) -> u16 {
212        self.units_per_em
213    }
214
215    /// The sizes in pixels per em at which the values of the kinds in pixels were read.
216    #[must_use]
217    pub fn sizes(&self) -> &[u16] {
218        &self.sizes
219    }
220
221    /// The values of one kind, by place.
222    #[must_use]
223    pub fn of(&self, kind: ValueKind) -> Option<&BTreeMap<Place, Values>> {
224        self.values.get(&kind)
225    }
226
227    /// The characters that the face maps.
228    pub fn characters(&self) -> impl Iterator<Item = char> + '_ {
229        self.values
230            .get(&ValueKind::Characters)
231            .into_iter()
232            .flat_map(BTreeMap::keys)
233            .flat_map(Place::characters)
234    }
235
236    /// Keeps only the places whose characters all lie in `range`; the values of the whole
237    /// face and of sizes stay.
238    pub fn keep_characters(&mut self, range: std::ops::RangeInclusive<char>) {
239        for places in self.values.values_mut() {
240            places.retain(|place, _| place.characters().iter().all(|c| range.contains(c)));
241        }
242    }
243}
244
245impl FontDb {
246    /// Returns the layout values of face `id`, with the values in pixels at each size of
247    /// `sizes` (pixels per em).
248    ///
249    /// Each value comes from the method of the database that the layout calls for it. The
250    /// pairs whose kerning it reads are those that the face's tables list with a value; every
251    /// other pair has the kerning 0. Returns `None` for an unknown face.
252    #[must_use]
253    pub fn layout_values(&self, id: FontId, sizes: &[u16]) -> Option<LayoutValues> {
254        let metrics = self.metrics(id)?;
255        let mut reader = Reader {
256            db: self,
257            id,
258            glyphs: mapped_characters(self, id),
259            values: BTreeMap::new(),
260        };
261        reader.characters();
262        reader.kerning();
263        reader.line_values();
264        reader.selection();
265        reader.pixels(sizes);
266        reader.ligatures();
267        reader.forms();
268        reader.math(metrics.units_per_em);
269        reader.shaping();
270        Some(LayoutValues {
271            units_per_em: metrics.units_per_em,
272            sizes: sizes.to_vec(),
273            values: reader.values,
274        })
275    }
276}
277
278/// The characters that face `id` maps, with their glyphs, as [`FontDb::glyph_id`] maps them:
279/// the codes of its Unicode character map, and the codes from U+0000 to U+00FF, which a symbol
280/// character map takes at U+F000 to U+F0FF.
281fn mapped_characters(db: &FontDb, id: FontId) -> BTreeMap<char, u32> {
282    let listed: Vec<u32> = db
283        .face(id)
284        .and_then(crate::face::Face::font)
285        .map_or_else(Vec::new, |font| {
286            font.charmap().unicodes().map(|(code, _)| code).collect()
287        });
288    listed
289        .into_iter()
290        .chain(0..=0xFF)
291        .filter_map(char::from_u32)
292        .filter_map(|c| Some((c, db.glyph_id(id, c)?)))
293        .collect()
294}
295
296/// Reads the layout values of one face.
297struct Reader<'a> {
298    db: &'a FontDb,
299    id: FontId,
300    glyphs: BTreeMap<char, u32>,
301    values: BTreeMap<ValueKind, BTreeMap<Place, Values>>,
302}
303
304/// A whole number as a value.
305fn number(value: impl Into<i64>) -> i64 {
306    value.into()
307}
308
309/// A flag as a value: 1 when set.
310fn flag(set: bool) -> i64 {
311    i64::from(set)
312}
313
314impl Reader<'_> {
315    fn put(&mut self, kind: ValueKind, place: Place, values: Values) {
316        self.values.entry(kind).or_default().insert(place, values);
317    }
318
319    /// The characters of each glyph of the face's map.
320    fn characters_of(&self) -> BTreeMap<u32, Vec<char>> {
321        let mut by_glyph: BTreeMap<u32, Vec<char>> = BTreeMap::new();
322        for (&c, &glyph) in &self.glyphs {
323            by_glyph.entry(glyph).or_default().push(c);
324        }
325        by_glyph
326    }
327
328    /// The advance and the box of a glyph, for a glyph that a character takes in place of its
329    /// own.
330    fn glyph_values(&self, glyph: u32) -> Values {
331        let mut values: Values = self
332            .db
333            .advance(self.id, glyph)
334            .map(number)
335            .into_iter()
336            .collect();
337        values.extend(glyph_box(self.db, self.id, glyph));
338        values
339    }
340
341    fn characters(&mut self) {
342        let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
343        for (c, glyph) in glyphs {
344            self.put(ValueKind::Characters, Place::Character(c), Vec::new());
345            if let Some(advance) = self.db.advance(self.id, glyph) {
346                self.put(
347                    ValueKind::Advance,
348                    Place::Character(c),
349                    vec![number(advance)],
350                );
351            }
352            let shape = glyph_box(self.db, self.id, glyph);
353            self.put(ValueKind::Box, Place::Character(c), shape);
354        }
355    }
356
357    fn kerning(&mut self) {
358        let source = self.db.kerning_source(self.id);
359        let gpos = source == KerningSource::Gpos;
360        self.put(
361            ValueKind::Kerning,
362            Place::Face("source is GPOS"),
363            vec![flag(gpos)],
364        );
365        let table = self.db.has_kern_table(self.id);
366        self.put(
367            ValueKind::KernTable,
368            Place::Face("has a kern table"),
369            vec![flag(table)],
370        );
371        let glyphs: BTreeSet<u32> = self.glyphs.values().copied().collect();
372        let by_glyph = self.characters_of();
373        for (left, right) in self.db.listed_kerning_pairs(self.id, &glyphs) {
374            let values = [
375                (ValueKind::Kerning, self.db.kerning(self.id, left, right)),
376                (
377                    ValueKind::KernTable,
378                    self.db
379                        .kerning_from(self.id, left, right, KerningSource::KernTable),
380                ),
381            ];
382            for (kind, value) in values {
383                if value != 0 {
384                    self.put_pairs(kind, &by_glyph, (left, right), value);
385                }
386            }
387        }
388    }
389
390    /// Puts the kerning `value` of a glyph pair at each pair of characters that maps to it.
391    fn put_pairs(
392        &mut self,
393        kind: ValueKind,
394        by_glyph: &BTreeMap<u32, Vec<char>>,
395        (left, right): (u32, u32),
396        value: i32,
397    ) {
398        let lefts = by_glyph.get(&left).map_or(&[][..], Vec::as_slice);
399        let rights = by_glyph.get(&right).map_or(&[][..], Vec::as_slice);
400        for &a in lefts {
401            for &b in rights {
402                self.put(kind, Place::Pair(a, b), vec![number(value)]);
403            }
404        }
405    }
406
407    fn line_values(&mut self) {
408        let Some(metrics) = self.db.metrics(self.id) else {
409            return;
410        };
411        for (name, value) in metric_fields(metrics) {
412            self.put(ValueKind::LineValues, Place::Face(name), vec![value]);
413        }
414    }
415
416    fn selection(&mut self) {
417        let Some(info) = self.db.info(self.id) else {
418            return;
419        };
420        let classification = &info.classification;
421        let mut fields = vec![
422            ("weight", number(info.weight)),
423            ("italic", flag(info.italic)),
424            ("PANOSE weight", number(info.panose_weight)),
425            ("East Asian code pages", flag(classification.east_asian)),
426        ];
427        let panose = PANOSE_NAMES.iter().zip(classification.panose);
428        fields.extend(panose.map(|(&name, value)| (name, number(value))));
429        for (name, value) in fields {
430            self.put(ValueKind::Selection, Place::Face(name), vec![value]);
431        }
432    }
433
434    /// The values in pixels at each size: the heights of `VDMX`, and each character's
435    /// bi-level advance and device width.
436    fn pixels(&mut self, sizes: &[u16]) {
437        for &size in sizes {
438            if let Some((above, below)) = self.db.device_heights(self.id, size) {
439                let values = vec![number(above), number(below)];
440                self.put(ValueKind::PixelHeights, Place::Size(size), values);
441            }
442        }
443        for (glyph, characters) in self.characters_of() {
444            for &size in sizes {
445                let bi_level = self.db.bi_level_advance(self.id, glyph, size);
446                let device = self.db.device_width(self.id, glyph, size);
447                for &c in &characters {
448                    let at = Place::CharacterAt(c, size);
449                    if let Some(width) = bi_level {
450                        self.put(ValueKind::BiLevelAdvance, at.clone(), vec![number(width)]);
451                    }
452                    if let Some(width) = device {
453                        self.put(ValueKind::DeviceWidth, at, vec![number(width)]);
454                    }
455                }
456            }
457        }
458    }
459
460    /// The ligatures of each sequence of characters whose glyphs the face's standard
461    /// ligatures join.
462    fn ligatures(&mut self) {
463        let by_glyph = self.characters_of();
464        for glyphs in self.db.ligature_sequences(self.id) {
465            let mut values = Vec::new();
466            for ligature in self.db.ligatures(self.id, &glyphs) {
467                values.push(count(ligature.start));
468                values.push(count(ligature.len));
469                values.extend(self.glyph_values(ligature.glyph));
470            }
471            for characters in sequences_of(&glyphs, &by_glyph) {
472                self.put(
473                    ValueKind::Ligatures,
474                    Place::Sequence(characters),
475                    values.clone(),
476                );
477            }
478        }
479    }
480
481    /// The script glyphs, flattened accents and dotless forms of each character.
482    fn forms(&mut self) {
483        let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
484        for (c, glyph) in glyphs {
485            let forms = [
486                (
487                    "script glyph",
488                    self.db.script_glyph(self.id, glyph, ScriptLevel::Script),
489                ),
490                (
491                    "script-of-script glyph",
492                    self.db
493                        .script_glyph(self.id, glyph, ScriptLevel::ScriptOfScript),
494                ),
495                ("flattened accent", self.db.flattened_accent(self.id, glyph)),
496                ("dotless form", self.db.dotless_form(self.id, glyph)),
497            ];
498            for (name, form) in forms {
499                if let Some(form) = form {
500                    let values = self.glyph_values(form);
501                    self.put(ValueKind::Forms, Place::CharacterValue(c, name), values);
502                }
503            }
504        }
505    }
506
507    /// The constants of the `MATH` table and each character's values in it.
508    fn math(&mut self, units_per_em: u16) {
509        for (name, value) in math_constants(self.db, self.id) {
510            self.put(ValueKind::Math, Place::Face(name), vec![value]);
511        }
512        let glyphs: Vec<(char, u32)> = self.glyphs.iter().map(|(&c, &g)| (c, g)).collect();
513        for (c, glyph) in glyphs {
514            for (name, values) in self.math_values(glyph, units_per_em) {
515                self.put(ValueKind::Math, Place::CharacterValue(c, name), values);
516            }
517        }
518    }
519
520    /// The values of one glyph in the `MATH` table: its italic correction, its top accent
521    /// attachment, its display variant, its vertical variant for the heights 0, half an em,
522    /// an em, one and a half, two and three ems and the greatest height, its horizontal
523    /// construction, and its math kerning at each corner at the heights 0, half an em and an
524    /// em.
525    fn math_values(&self, glyph: u32, units_per_em: u16) -> Vec<(&'static str, Values)> {
526        let (db, id) = (self.db, self.id);
527        let mut found = Vec::new();
528        if let Some(value) = db.italic_correction(id, glyph) {
529            found.push(("italic correction", vec![number(value)]));
530        }
531        if let Some(value) = db.top_accent_attachment(id, glyph) {
532            found.push(("top accent attachment", vec![number(value)]));
533        }
534        if let Some(variant) = db.display_variant(id, glyph) {
535            found.push(("display variant", self.glyph_values(variant)));
536        }
537        let em = i32::from(units_per_em);
538        let heights = [0, em / 2, em, em * 3 / 2, em * 2, em * 3, i32::MAX];
539        let variants: Vec<Values> = heights
540            .iter()
541            .filter_map(|&least| db.vertical_variant(id, glyph, least))
542            .map(|(variant, reached)| {
543                let mut values = self.glyph_values(variant);
544                values.push(flag(reached));
545                values
546            })
547            .collect();
548        if !variants.is_empty() {
549            found.push(("vertical variants", variants.concat()));
550        }
551        if let Some(construction) = db.horizontal_construction(id, glyph) {
552            found.push(("horizontal construction", self.construction(&construction)));
553        }
554        found.extend(math_kerning(db, id, glyph, units_per_em));
555        found
556    }
557
558    /// The glyphs that shaping gives each mapped character of a script that the layout
559    /// shapes, alone and three times in a row: each glyph's cluster, advance, offset and
560    /// glyph values. A text that does not shape has no values.
561    fn shaping(&mut self) {
562        let shaped: Vec<(char, ShapedScript)> = self
563            .glyphs
564            .keys()
565            .filter_map(|&c| Some((c, ShapedScript::of(c)?)))
566            .collect();
567        for (c, script) in shaped {
568            for repeat in [1, 3] {
569                let text: String = std::iter::repeat_n(c, repeat).collect();
570                let request = ShapeRequest {
571                    text: &text,
572                    script,
573                    direction: script.direction(),
574                    language: None,
575                };
576                let Ok(glyphs) = self.db.shape(self.id, &request) else {
577                    continue;
578                };
579                let mut values = Vec::new();
580                for glyph in glyphs {
581                    values.push(count(glyph.cluster));
582                    values.push(number(glyph.advance));
583                    values.push(number(glyph.offset.0));
584                    values.push(number(glyph.offset.1));
585                    values.extend(self.glyph_values(glyph.glyph));
586                }
587                let place = Place::Sequence(vec![c; repeat]);
588                self.put(ValueKind::Shaping, place, values);
589            }
590        }
591    }
592
593    /// A horizontal construction as values: each variant's measurement and glyph values, and
594    /// each part's full advance, extender flag and glyph values.
595    fn construction(&self, construction: &crate::HorizontalConstruction) -> Values {
596        let mut values = vec![count(construction.variants.len())];
597        for &(variant, measurement) in &construction.variants {
598            values.push(number(measurement));
599            values.extend(self.glyph_values(variant));
600        }
601        values.push(count(construction.assembly.len()));
602        for part in &construction.assembly {
603            values.push(number(part.full_advance));
604            values.push(flag(part.extender));
605            values.extend(self.glyph_values(part.glyph));
606        }
607        values
608    }
609}
610
611/// A count or an index as a value.
612fn count(value: usize) -> i64 {
613    i64::try_from(value).unwrap_or(i64::MAX)
614}
615
616/// A whole number of font units, which a glyph's coordinates are far inside.
617#[expect(
618    clippy::cast_possible_truncation,
619    reason = "a glyph's coordinates are font units, far inside i64, and are whole when this \
620              is called"
621)]
622fn font_units(value: f32) -> i64 {
623    value as i64
624}
625
626/// The box of a glyph: the least x, the least y, the greatest x and the greatest y of all
627/// points of its outline, control points too, the least down and the greatest up to whole
628/// font units, as the layout takes a glyph's ink; none for a glyph without points or whose
629/// outline does not read. A TrueType glyph's points are whole font units already.
630fn glyph_box(db: &FontDb, id: FontId, glyph: u32) -> Values {
631    let Ok(outline) = db.outline(id, glyph) else {
632        return Vec::new();
633    };
634    let points = outline.iter().flat_map(|command| match *command {
635        PathCommand::MoveTo(p) | PathCommand::LineTo(p) => vec![p],
636        PathCommand::QuadTo(c, p) => vec![c, p],
637        PathCommand::CubicTo(c, d, p) => vec![c, d, p],
638        PathCommand::Close => Vec::new(),
639    });
640    let mut bounds: Option<[f32; 4]> = None;
641    for p in points {
642        let [x0, y0, x1, y1] = bounds.unwrap_or([p.x, p.y, p.x, p.y]);
643        bounds = Some([x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y)]);
644    }
645    bounds.map_or_else(Vec::new, |[x0, y0, x1, y1]| {
646        vec![
647            font_units(x0.floor()),
648            font_units(y0.floor()),
649            font_units(x1.ceil()),
650            font_units(y1.ceil()),
651        ]
652    })
653}
654
655/// The sequences of characters whose glyphs are `glyphs`, each glyph by each of its
656/// characters; none when a glyph has no character.
657fn sequences_of(glyphs: &[u32], by_glyph: &BTreeMap<u32, Vec<char>>) -> Vec<Vec<char>> {
658    let mut sequences: Vec<Vec<char>> = vec![Vec::new()];
659    for glyph in glyphs {
660        let characters = by_glyph.get(glyph).map_or(&[][..], Vec::as_slice);
661        sequences = sequences
662            .iter()
663            .flat_map(|start| {
664                characters.iter().map(move |&c| {
665                    let mut next = start.clone();
666                    next.push(c);
667                    next
668                })
669            })
670            .collect();
671    }
672    sequences
673}
674
675/// The names of the ten PANOSE numbers.
676const PANOSE_NAMES: [&str; 10] = [
677    "PANOSE family",
678    "PANOSE serif",
679    "PANOSE weight number",
680    "PANOSE proportion",
681    "PANOSE contrast",
682    "PANOSE stroke",
683    "PANOSE arm",
684    "PANOSE letterform",
685    "PANOSE midline",
686    "PANOSE x height",
687];
688
689/// Each field of a face's metrics, by name.
690fn metric_fields(metrics: &crate::FontMetrics) -> Vec<(&'static str, i64)> {
691    let hhea = metrics.hhea;
692    let mut fields = vec![
693        ("units per em", number(metrics.units_per_em)),
694        ("hhea ascender", number(hhea.ascender)),
695        ("hhea descender", number(hhea.descender)),
696        ("hhea line gap", number(hhea.line_gap)),
697    ];
698    if let Some(underline) = metrics.underline {
699        fields.push(("post underline position", number(underline.position)));
700        fields.push(("post underline thickness", number(underline.thickness)));
701    }
702    if let Some(os2) = metrics.os2 {
703        fields.extend(os2_fields(&os2));
704    }
705    fields
706}
707
708/// Each field of the `OS/2` metrics, by name.
709fn os2_fields(os2: &crate::Os2Metrics) -> Vec<(&'static str, i64)> {
710    let mut fields = vec![
711        ("OS/2 average width", number(os2.average_width)),
712        ("OS/2 typo ascender", number(os2.typo.ascender)),
713        ("OS/2 typo descender", number(os2.typo.descender)),
714        ("OS/2 typo line gap", number(os2.typo.line_gap)),
715        ("OS/2 win ascent", number(os2.win_ascent)),
716        ("OS/2 win descent", number(os2.win_descent)),
717        ("OS/2 use typo metrics", flag(os2.use_typo_metrics)),
718        ("OS/2 strikeout position", number(os2.strikeout.position)),
719        ("OS/2 strikeout size", number(os2.strikeout.thickness)),
720        ("OS/2 subscript x size", number(os2.subscript.x_size)),
721        ("OS/2 subscript y size", number(os2.subscript.y_size)),
722        ("OS/2 subscript x offset", number(os2.subscript.x_offset)),
723        ("OS/2 subscript y offset", number(os2.subscript.y_offset)),
724        ("OS/2 superscript x size", number(os2.superscript.x_size)),
725        ("OS/2 superscript y size", number(os2.superscript.y_size)),
726        (
727            "OS/2 superscript x offset",
728            number(os2.superscript.x_offset),
729        ),
730        (
731            "OS/2 superscript y offset",
732            number(os2.superscript.y_offset),
733        ),
734        ("OS/2 East Asian code pages", flag(os2.east_asian)),
735    ];
736    if let Some(value) = os2.x_height {
737        fields.push(("OS/2 x height", number(value)));
738    }
739    if let Some(value) = os2.cap_height {
740        fields.push(("OS/2 cap height", number(value)));
741    }
742    fields
743}
744
745/// The constants of a face's `MATH` table that the layout reads, by name.
746fn math_constants(db: &FontDb, id: FontId) -> Vec<(&'static str, i64)> {
747    let mut fields = Vec::new();
748    if let Some(accent) = db.math_accent(id) {
749        fields.push(("accent base height", number(accent.accent_base_height)));
750        let flattened = accent.flattened_accent_base_height;
751        fields.push(("flattened accent base height", number(flattened)));
752        fields.push((
753            "min connector overlap",
754            number(accent.min_connector_overlap),
755        ));
756    }
757    if let Some(radical) = db.math_radical(id) {
758        fields.extend([
759            ("radical vertical gap", number(radical.vertical_gap)),
760            ("radical rule thickness", number(radical.rule_thickness)),
761            ("radical extra ascender", number(radical.extra_ascender)),
762            (
763                "radical kern before degree",
764                number(radical.kern_before_degree),
765            ),
766            (
767                "radical kern after degree",
768                number(radical.kern_after_degree),
769            ),
770            (
771                "radical degree bottom raise",
772                number(radical.degree_bottom_raise_percent),
773            ),
774            (
775                "radical flattened accent base height",
776                number(radical.flattened_accent_base_height),
777            ),
778        ]);
779    }
780    if let Some(bars) = db.math_bars(id) {
781        fields.extend([
782            ("overbar vertical gap", number(bars.overbar_vertical_gap)),
783            (
784                "overbar rule thickness",
785                number(bars.overbar_rule_thickness),
786            ),
787            (
788                "overbar extra ascender",
789                number(bars.overbar_extra_ascender),
790            ),
791            ("underbar vertical gap", number(bars.underbar_vertical_gap)),
792            (
793                "underbar rule thickness",
794                number(bars.underbar_rule_thickness),
795            ),
796            (
797                "underbar extra descender",
798                number(bars.underbar_extra_descender),
799            ),
800        ]);
801    }
802    if let Some(skewed) = db.math_skewed_fraction(id) {
803        fields.extend([
804            (
805                "skewed fraction horizontal gap",
806                number(skewed.horizontal_gap),
807            ),
808            ("skewed fraction vertical gap", number(skewed.vertical_gap)),
809        ]);
810    }
811    if let Some(gaps) = db.math_limit_gaps(id) {
812        fields.extend([
813            ("lower limit gap min", number(gaps.lower_limit_gap_min)),
814            ("upper limit gap min", number(gaps.upper_limit_gap_min)),
815        ]);
816    }
817    fields.extend(math_limit_fields(db, id));
818    if let Some(space) = db.space_after_script(id) {
819        fields.push(("space after script", number(space)));
820    }
821    fields
822}
823
824/// The limit and stretch-stack constants of a face's `MATH` table, by name.
825fn math_limit_fields(db: &FontDb, id: FontId) -> Vec<(&'static str, i64)> {
826    let mut fields = Vec::new();
827    if let Some(limits) = db.math_limits(id) {
828        fields.extend([
829            ("math leading", number(limits.math_leading)),
830            (
831                "display operator min height",
832                number(limits.display_operator_min_height),
833            ),
834            (
835                "upper limit baseline rise min",
836                number(limits.upper_limit_baseline_rise_min),
837            ),
838            (
839                "lower limit baseline drop min",
840                number(limits.lower_limit_baseline_drop_min),
841            ),
842            (
843                "superscript baseline drop max",
844                number(limits.superscript_baseline_drop_max),
845            ),
846            (
847                "subscript baseline drop min",
848                number(limits.subscript_baseline_drop_min),
849            ),
850            (
851                "delimited sub formula min height",
852                number(limits.delimited_sub_formula_min_height),
853            ),
854        ]);
855    }
856    if let Some(stack) = db.math_stretch_stack(id) {
857        fields.extend([
858            ("stretch stack top shift up", number(stack.top_shift_up)),
859            (
860                "stretch stack bottom shift down",
861                number(stack.bottom_shift_down),
862            ),
863            ("stretch stack gap above min", number(stack.gap_above_min)),
864            ("stretch stack gap below min", number(stack.gap_below_min)),
865            (
866                "stretch stack min connector overlap",
867                number(stack.min_connector_overlap),
868            ),
869        ]);
870    }
871    fields
872}
873
874/// A glyph's math kerning at each corner, at the heights 0, half an em and an em.
875fn math_kerning(
876    db: &FontDb,
877    id: FontId,
878    glyph: u32,
879    units_per_em: u16,
880) -> Vec<(&'static str, Values)> {
881    let em = i32::from(units_per_em);
882    let corners = [
883        ("math kerning top right", MathCorner::TopRight),
884        ("math kerning top left", MathCorner::TopLeft),
885        ("math kerning bottom right", MathCorner::BottomRight),
886        ("math kerning bottom left", MathCorner::BottomLeft),
887    ];
888    corners
889        .into_iter()
890        .filter_map(|(name, corner)| {
891            let values: Option<Values> = [0, em / 2, em]
892                .into_iter()
893                .map(|height| db.math_kern(id, glyph, corner, height).map(number))
894                .collect();
895            Some((name, values?))
896        })
897        .collect()
898}
899
900#[cfg(test)]
901mod tests;