cranpose-text 0.21.2

Text styles, fonts, shaping and paragraph layout for Cranpose
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
use std::{
    hash::{BuildHasher, Hash, Hasher},
    sync::{Arc, OnceLock},
};

use foldhash::fast::FixedState;
use read_fonts::{
    FontRef, TableProvider,
    model::{Blob, Font, Source, Variation, attribute::Style, metrics::GlyphExtents, name::NameId},
    types::{Fixed, GlyphId as FontGlyphId, Tag},
};
use smallvec::SmallVec;

use crate::{
    coverage::Coverage,
    font::{FontFamily, FontStyle, FontSynthesis, FontWeight},
    glyph_id::GlyphId,
    glyph_ink::GlyphInks,
    simple_glyf::{self, GlyfTables},
};

/// The bytes a typeface is read from.
pub enum FontBytes {
    /// Bytes that live as long as the process, such as an embedded font or a
    /// font file read once: the typeface reads them in place.
    Static(&'static [u8]),
    /// Bytes the typeface takes over.
    Owned(Vec<u8>),
}

impl FontBytes {
    /// The font file's bytes.
    pub fn as_slice(&self) -> &[u8] {
        match self {
            Self::Static(bytes) => bytes,
            Self::Owned(bytes) => bytes,
        }
    }
}

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

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

impl From<Vec<u8>> for FontBytes {
    fn from(bytes: Vec<u8>) -> Self {
        Self::Owned(bytes)
    }
}

/// The identity an app-supplied typeface was registered under.
///
/// `FontFamily::FileBacked` and `FontFamily::LoadedTypeface` name a typeface by
/// its files rather than by a name inside the font, so resolution cannot
/// compare strings from the `name` table. Hashing the `FontFamily` value once
/// at registration and once per resolve keeps the two sides in step without
/// walking path lists on every frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FontFamilyKey(u64);

impl FontFamilyKey {
    /// Returns the key of `family`, the same for equal families.
    pub fn of(family: &FontFamily) -> Self {
        Self(HASH_STATE.hash_one(family))
    }
}

/// Why bytes could not become a typeface.
#[derive(Debug, PartialEq, thiserror::Error)]
pub enum TypefaceError {
    /// The bytes are not a font this crate reads.
    #[error("the bytes are not a readable font")]
    InvalidFont,
    /// A variation names an axis the font lacks, or a value outside its range.
    #[error("variation {tag:?} is not an axis of the font, or lies outside its range")]
    InvalidVariation {
        /// The axis tag of the variation.
        tag: [u8; 4],
    },
}

/// A font loaded for text at one location in its design space, with the
/// family names, weight and style text chooses it by: Compose's `Typeface`.
/// Clones share one load; two typefaces are equal when they draw the same
/// glyphs, from the same bytes at the same axis positions.
#[derive(Clone)]
pub struct Typeface(Arc<Loaded>);

impl PartialEq for Typeface {
    fn eq(&self, other: &Self) -> bool {
        self.same(other) || self.0.content_hash == other.0.content_hash
    }
}

struct Loaded {
    font: Font,
    families: Box<[String]>,
    registered_family: Option<FontFamilyKey>,
    weight: FontWeight,
    style: FontStyle,
    // The weights the typeface draws: its `wght` axis range when it was read
    // without a declaration, otherwise its one weight.
    weights: (f32, f32),
    // Whether an `ital` or `slnt` axis lets the typeface draw italic as well.
    italic_axis: bool,
    // The `wght`, `ital` and `slnt` axes a font read without a declaration
    // draws a weight and style on; none for a registered one, which its
    // declaration instanced.
    style_axes: SmallVec<[StyleAxis; 3]>,
    is_color: bool,
    // The axis positions the typeface is instanced at, sorted by tag.
    variations: Box<[([u8; 4], f32)]>,
    content_hash: u64,
    found: Found,
    // The normal track of the font's `trak` table: the tracking in ems at
    // each point size it lists, ascending; empty without one.
    tracking: Box<[(f32, f32)]>,
    // The glyph of the space, whose advance justification stretches.
    space: Option<GlyphId>,
}

// What a typeface reads of its font on first use.
#[derive(Default)]
struct Found {
    coverage: OnceLock<Coverage>,
    glyf: OnceLock<Option<GlyfTables>>,
    // Which glyphs put ink past their advance or the font's lines, read as
    // layouts meet them.
    inks: OnceLock<GlyphInks>,
}

impl Typeface {
    /// Reads `bytes` as a typeface no family was declared for: its weight,
    /// style and family names come from the font.
    pub fn from_bytes(bytes: impl Into<FontBytes>) -> Result<Self, TypefaceError> {
        let font = Font::new(blob(bytes.into()), 0).ok_or(TypefaceError::InvalidFont)?;
        let content_hash = content_hash(&font, &[]);
        let weight = (&font.tables())
            .os2()
            .ok()
            .and_then(|os2| FontWeight::try_new(os2.us_weight_class()))
            .unwrap_or_default();
        let style = match font.default_attributes().style {
            Style::Normal => FontStyle::Normal,
            Style::Italic | Style::Oblique(_) => FontStyle::Italic,
        };
        let style_axes = style_axes(&font);
        let axis = |tag: &[u8; 4]| style_axes.iter().find(|axis| axis.tag == *tag);
        let default_weight = f32::from(weight.value());
        let weights = axis(b"wght").map_or((default_weight, default_weight), |axis| {
            (axis.min.max(1.0), axis.max.min(1000.0))
        });
        let italic_axis = axis(b"ital").is_some_and(|axis| axis.max >= 1.0)
            || axis(b"slnt").is_some_and(|axis| axis.min < 0.0);
        Ok(Self(Arc::new(Loaded {
            families: family_names(&font),
            registered_family: None,
            weight,
            style,
            weights,
            italic_axis,
            style_axes,
            is_color: is_color(&font),
            variations: Box::default(),
            content_hash,
            found: Found::default(),
            tracking: normal_track(&font),
            space: space_glyph(&font),
            font,
        })))
    }

    /// Reads `bytes` as a typeface an app registered under `family`,
    /// declaring `weight` and `style` for it, as a Compose `Font(resId,
    /// weight, style)` entry does: the declaration wins over the font's own
    /// values, and a variable font is instanced on its `wght`, `ital` and
    /// `slnt` axes, so one file backs a whole family. The explicit
    /// `variations` then win over the declared positions; a variation of an
    /// axis the font lacks, or outside that axis's range, fails.
    pub fn from_registered(
        family: &FontFamily,
        weight: FontWeight,
        style: FontStyle,
        bytes: impl Into<FontBytes>,
        variations: &[([u8; 4], f32)],
    ) -> Result<Self, TypefaceError> {
        let font = Font::new(blob(bytes.into()), 0).ok_or(TypefaceError::InvalidFont)?;
        let mut applied = declared_variations(&style_axes(&font), weight, style);
        for &(tag, value) in variations {
            let valid = value.is_finite()
                && font.axes().iter().any(|axis| {
                    axis.tag() == Tag::new(&tag)
                        && (axis.min_value()..=axis.max_value()).contains(&value)
                });
            if !valid {
                return Err(TypefaceError::InvalidVariation { tag });
            }
            applied.retain(|(existing, _)| *existing != tag);
            applied.push((tag, value));
        }
        applied.sort_unstable_by_key(|(tag, _)| *tag);
        let content_hash = content_hash(&font, &applied);
        let font = if applied.is_empty() {
            font
        } else {
            font.instance_builder()
                .variations(
                    applied
                        .iter()
                        .map(|(tag, value)| Variation::new(Tag::new(tag), *value)),
                )
                .build()
        };
        let declared_weight = f32::from(weight.value());
        Ok(Self(Arc::new(Loaded {
            families: family_names(&font),
            registered_family: Some(FontFamilyKey::of(family)),
            weight,
            style,
            weights: (declared_weight, declared_weight),
            italic_axis: false,
            style_axes: SmallVec::new(),
            is_color: is_color(&font),
            variations: applied.into_boxed_slice(),
            content_hash,
            found: Found::default(),
            tracking: normal_track(&font),
            space: space_glyph(&font),
            font,
        })))
    }

    /// The family names the font's `name` table gives it, typographic family
    /// first.
    pub fn family_names(&self) -> &[String] {
        &self.0.families
    }

    /// The family the typeface was registered under, `None` for one read
    /// with [`Typeface::from_bytes`].
    pub fn registered_family(&self) -> Option<FontFamilyKey> {
        self.0.registered_family
    }

    /// The weight text chooses the typeface by.
    pub fn weight(&self) -> FontWeight {
        self.0.weight
    }

    /// The style text chooses the typeface by.
    pub fn style(&self) -> FontStyle {
        self.0.style
    }

    /// Whether the font draws glyphs in color (a `COLR`, `CBDT`, `sbix` or
    /// `SVG` table), as emoji fonts do.
    pub fn is_color(&self) -> bool {
        self.0.is_color
    }

    /// What Compose synthesizes for text in `weight` and `style` drawn with
    /// this typeface, as `synthesis` allows: a bold for a weight of 600 or
    /// more when the typeface draws none that heavy, and an italic when it
    /// draws none.
    pub fn synthesis(
        &self,
        weight: FontWeight,
        style: FontStyle,
        synthesis: FontSynthesis,
    ) -> Synthesis {
        const BOLD: u16 = 600;
        Synthesis {
            bold: matches!(synthesis, FontSynthesis::All | FontSynthesis::Weight)
                && weight.value() >= BOLD
                && self.0.weights.1 < f32::from(BOLD),
            italic: matches!(synthesis, FontSynthesis::All | FontSynthesis::Style)
                && style == FontStyle::Italic
                && !self.draws(FontStyle::Italic),
        }
    }

    // The weights the typeface draws, lowest and highest.
    pub(crate) fn weights(&self) -> (f32, f32) {
        self.0.weights
    }

    // Whether the typeface draws `style`.
    pub(crate) fn draws(&self, style: FontStyle) -> bool {
        self.0.style == style || self.0.italic_axis
    }

    // The characters the font maps to glyphs, read from the `cmap` on first use.
    pub(crate) fn coverage(&self) -> &Coverage {
        self.0.found.coverage.get_or_init(|| {
            Coverage::from_codepoints(
                self.0
                    .font
                    .charmap()
                    .unicodes()
                    .filter(|(_, glyph)| *glyph != FontGlyphId::NOTDEF)
                    .map(|(codepoint, _)| codepoint),
            )
        })
    }

    /// The axis positions the typeface is instanced at, sorted by tag.
    pub fn variations(&self) -> &[([u8; 4], f32)] {
        &self.0.variations
    }

    /// A hash of the font's bytes and its axis positions: equal for two
    /// loads of one instance.
    pub fn content_hash(&self) -> u64 {
        self.0.content_hash
    }

    /// The font's design units in an em.
    pub fn units_per_em(&self) -> u16 {
        self.0.font.units_per_em()
    }

    /// The font's line metrics at the instance, in design units: the
    /// typographic line when the font asks for it with `USE_TYPO_METRICS`,
    /// otherwise the `hhea` line, as Skia and FreeType read them.
    #[inline(never)]
    pub fn line_metrics(&self) -> LineMetrics {
        let metrics = self.0.font.metrics();
        metrics
            .h_line()
            .map_or_else(LineMetrics::default, |line| LineMetrics {
                ascent: line.ascender.to_f32(),
                descent: line.descender.to_f32(),
                line_gap: line.line_gap.to_f32(),
            })
    }

    /// Where the font draws an underline and a line through its text, in
    /// design units: its `post` underline and `OS/2` strikeout, or Skia's
    /// defaults for a font without them.
    pub fn decoration_metrics(&self) -> DecorationMetrics {
        let metrics = self.0.font.style_metrics();
        let em = f32::from(self.units_per_em());
        let top = |decoration: Option<read_fonts::model::metrics::Decoration>,
                   default: (f32, f32)| {
            decoration.map_or(default, |decoration| {
                (-decoration.position.to_f32(), decoration.thickness.to_f32())
            })
        };
        let (underline_top, underline_thickness) = top(metrics.underline, (em / 9.0, em / 18.0));
        let (strike_through_top, strike_through_thickness) =
            top(metrics.strike_through, (-em * 6.0 / 21.0, em / 18.0));
        DecorationMetrics {
            underline_top,
            underline_thickness,
            strike_through_top,
            strike_through_thickness,
        }
    }

    // The font's default tracking at `size` pixels per em, in pixels: its
    // normal track interpolated between the point sizes it lists, held at
    // either end; zero for a font without a `trak` table.
    pub(crate) fn tracking(&self, size: f32) -> f32 {
        let track = &self.0.tracking;
        if track.is_empty() || !size.is_finite() || size <= 0.0 {
            return 0.0;
        }
        self.tracked(size)
    }

    // `tracking` of a font with a `trak` table. Out of line, as most fonts
    // have none.
    #[inline(never)]
    fn tracked(&self, size: f32) -> f32 {
        let track = &self.0.tracking;
        let above = track.partition_point(|&(point_size, _)| point_size < size);
        let em = match (
            above.checked_sub(1).map(|below| track[below]),
            track.get(above),
        ) {
            (Some((low_size, low)), Some(&(high_size, high))) => {
                low + (high - low) * (size - low_size) / (high_size - low_size)
            }
            (Some((_, em)), None) | (None, Some(&(_, em))) => em,
            (None, None) => 0.0,
        };
        em * size
    }

    /// The glyph the font maps `ch` to, `None` when it has none.
    pub fn glyph(&self, ch: char) -> Option<GlyphId> {
        self.0
            .font
            .charmap()
            .map_unicode(ch)
            .map(|glyph| GlyphId(glyph.to_u32()))
    }

    // The glyph of the space.
    pub(crate) fn space(&self) -> Option<GlyphId> {
        self.0.space
    }

    /// Whether the font maps `ch` to a glyph.
    pub fn covers(&self, ch: char) -> bool {
        self.coverage().contains(ch)
    }

    /// The horizontal advance of `glyph` at the instance, in design units.
    pub fn advance(&self, glyph: GlyphId) -> f32 {
        self.0
            .font
            .glyph_metrics()
            .h_advance(FontGlyphId::new(glyph.0))
    }

    // Whether `other` is a clone of this typeface.
    pub(crate) fn same(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }

    // The font model at the typeface's instance.
    pub(crate) fn font(&self) -> &Font {
        &self.0.font
    }

    // Where `glyph` puts ink, in design units: from its `glyf` header for a
    // simple TrueType font, otherwise as the general loader measures it.
    pub(crate) fn glyph_extents(&self, glyph: GlyphId) -> Option<GlyphExtents<f32>> {
        let id = FontGlyphId::new(glyph.0);
        match self.glyf_tables() {
            Some(tables) => simple_glyf::extents(&self.0.font, tables, id),
            None => self.0.font.glyph_metrics().extents(id),
        }
    }

    // Which glyphs put ink past their advance or the font's lines.
    pub(crate) fn glyph_inks(&self) -> &GlyphInks {
        self.0.found.inks.get_or_init(|| GlyphInks::of(self))
    }

    // Where the font keeps its simple glyphs, found on first use; `None`
    // for a font the general loader draws.
    pub(crate) fn glyf_tables(&self) -> Option<&GlyfTables> {
        self.0
            .found
            .glyf
            .get_or_init(|| GlyfTables::of(&self.0.font))
            .as_ref()
    }

    // The axis positions that draw the typeface at `weight` and `style`: for
    // a variable font read without a declaration, its `wght`, `ital` and
    // `slnt` positions; none for a registered typeface, which its declaration
    // already instanced.
    pub(crate) fn axis_positions(
        &self,
        weight: FontWeight,
        style: FontStyle,
    ) -> SmallVec<[([u8; 4], f32); 3]> {
        declared_variations(&self.0.style_axes, weight, style)
    }
}

impl std::fmt::Debug for Typeface {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Typeface")
            .field("family_names", &self.0.families)
            .field("weight", &self.0.weight)
            .field("style", &self.0.style)
            .field("variations", &self.0.variations)
            .finish_non_exhaustive()
    }
}

/// What a typeface lacks for a text's weight and style that is drawn in its
/// place.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Synthesis {
    /// A bold the typeface lacks.
    pub bold: bool,
    /// An italic the typeface lacks.
    pub italic: bool,
}

/// Where a font draws an underline and a line through its text, in design
/// units: Android's underline and strike-through metrics.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct DecorationMetrics {
    /// How far below the baseline the top of an underline sits.
    pub underline_top: f32,
    /// How thick an underline is.
    pub underline_thickness: f32,
    /// How far below the baseline the top of a line through the text sits;
    /// negative above it.
    pub strike_through_top: f32,
    /// How thick a line through the text is.
    pub strike_through_thickness: f32,
}

/// A font's vertical line metrics, in design units.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LineMetrics {
    /// Height above the baseline.
    pub ascent: f32,
    /// Depth below the baseline, negative.
    pub descent: f32,
    /// Space between one line's bottom and the next line's top.
    pub line_gap: f32,
}

fn blob(bytes: FontBytes) -> Blob {
    match bytes {
        FontBytes::Static(bytes) => Blob::from(bytes),
        FontBytes::Owned(bytes) => Blob::from(bytes),
    }
}

// The normal track of `font`'s `trak` table, the tracking in ems at each
// point size it lists; empty for a font without one or with sizes out of
// order.
fn normal_track(font: &Font) -> Box<[(f32, f32)]> {
    let read = || {
        let trak = font.tables().trak().ok()?;
        let data = trak.horiz()?.ok()?;
        let offset_data = trak.offset_data();
        let normal = data
            .track_table()
            .iter()
            .find(|track| track.track() == Fixed::ZERO)?;
        let values = normal.per_size_values(offset_data, data.n_sizes())?;
        let sizes = data.size_table(offset_data)?;
        let em = f32::from(font.units_per_em());
        let mut points = Vec::with_capacity(sizes.len());
        for (size, value) in sizes.iter().zip(values) {
            let size = size.get().to_f32();
            if size <= 0.0 || points.last().is_some_and(|&(previous, _)| size <= previous) {
                return None;
            }
            points.push((size, f32::from(value.get()) / em));
        }
        Some(points.into_boxed_slice())
    };
    read().unwrap_or_default()
}

// The model's tables expose no color tables, so this reads the table
// directory of the bytes.
fn is_color(font: &Font) -> bool {
    let Source::Blob(bytes) = font.source() else {
        return false;
    };
    FontRef::from_index(bytes.as_ref(), 0).is_ok_and(|font| {
        [*b"COLR", *b"CBDT", *b"sbix", *b"SVG "]
            .iter()
            .any(|tag| font.table_data(Tag::new(tag)).is_some())
    })
}

// The state every hash of this module starts from, the same each run, so a
// family key and a content hash stay put for the process's life.
const HASH_STATE: FixedState = FixedState::with_seed(0);

// A hash of the font's bytes and the axis positions it is instanced at.
fn content_hash(font: &Font, variations: &[([u8; 4], f32)]) -> u64 {
    let mut state = HASH_STATE.build_hasher();
    if let Source::Blob(bytes) = font.source() {
        bytes.as_ref().hash(&mut state);
    }
    for (tag, value) in variations {
        tag.hash(&mut state);
        value.to_bits().hash(&mut state);
    }
    state.finish()
}

fn family_names(font: &Font) -> Box<[String]> {
    let names = font.names();
    let mut families: Vec<String> = Vec::new();
    for id in [NameId::TYPOGRAPHIC_FAMILY_NAME, NameId::FAMILY_NAME] {
        let Some(name) = names.get(id) else {
            continue;
        };
        for localized in name.iter() {
            let value: String = localized.name().chars().collect();
            if !value.is_empty()
                && !families
                    .iter()
                    .any(|existing| existing.eq_ignore_ascii_case(&value))
            {
                families.push(value);
            }
        }
    }
    families.into_boxed_slice()
}

// The positions a declared weight and style ask of the font's axes, clamped
// into each axis's range.
fn declared_variations(
    axes: &[StyleAxis],
    weight: FontWeight,
    style: FontStyle,
) -> SmallVec<[([u8; 4], f32); 3]> {
    const OBLIQUE_DEGREES: f32 = -12.0;
    axes.iter()
        .filter_map(|axis| {
            let requested = match &axis.tag {
                b"wght" => f32::from(weight.value()),
                b"ital" if style == FontStyle::Italic => 1.0,
                b"slnt" if style == FontStyle::Italic => OBLIQUE_DEGREES,
                _ => return None,
            };
            Some((axis.tag, requested.clamp(axis.min, axis.max)))
        })
        .collect()
}

// An axis a weight or style sets, with its range.
#[derive(Clone, Copy, Debug)]
struct StyleAxis {
    tag: [u8; 4],
    min: f32,
    max: f32,
}

// The `wght`, `ital` and `slnt` axes of `font`.
fn style_axes(font: &Font) -> SmallVec<[StyleAxis; 3]> {
    font.axes()
        .iter()
        .map(|axis| StyleAxis {
            tag: axis.tag().to_be_bytes(),
            min: axis.min_value(),
            max: axis.max_value(),
        })
        .filter(|axis| matches!(&axis.tag, b"wght" | b"ital" | b"slnt"))
        .collect()
}

fn space_glyph(font: &Font) -> Option<GlyphId> {
    font.charmap()
        .map_unicode(' ')
        .map(|glyph| GlyphId(glyph.to_u32()))
}