Skip to main content

font_model/
font.rs

1//! The font model: [`Font`], [`FontBuilder`], and the operations a subsetter
2//! or a writer needs.
3//!
4//! A [`Font`] is the resolved, owned, editable form of a typeface: it owns its
5//! glyph store (each glyph carrying its own metrics and outline), its
6//! character map, its naming records, its OS/2 metrics, its kerning, and any
7//! layout tables carried through **opaquely** — so a read-modify-write round
8//! trip through the model is lossless even for the tables this crate does not
9//! interpret.
10//!
11//! # Invariants
12//!
13//! [`Font::validate`] is the single gate. It enforces:
14//!
15//! | Invariant | Error |
16//! |---|---|
17//! | `units_per_em` in `16..=16384` | [`ModelError::InvalidUnitsPerEm`] |
18//! | non-empty glyph has non-zero advance | [`ModelError::ZeroAdvance`] |
19//! | contours closed | [`ModelError::UnclosedContour`] |
20//! | coordinates finite | [`ModelError::NonFiniteCoordinate`] |
21//! | `cmap` strictly increasing | [`ModelError::NonMonotonicCmap`] |
22//! | every reference resolves | [`ModelError::UnknownGlyph`] |
23//!
24//! Each variant names the offending glyph and field.
25//!
26//! ```
27//! use font_model::{CodePointSet, Font, GlyphId, Outline, Path};
28//!
29//! // A two-glyph font: `.notdef` and 'A', mapped from U+0041.
30//! let mut box_outline = Outline::new();
31//! let mut p = Path::starting_at(50.0, 0.0);
32//! p.line_to(550.0, 0.0);
33//! p.line_to(550.0, 700.0);
34//! p.line_to(50.0, 700.0);
35//! p.close();
36//! box_outline.push_contour(p);
37//!
38//! let mut cmap = font_model::Cmap::new();
39//! cmap.subtables_mut().push(font_model::from_entries(&[(0x41, GlyphId::new(1))], 4));
40//!
41//! let font = Font::builder()
42//!     .units_per_em(1000)
43//!     .glyph(font_model::Glyph::new(GlyphId::NOTDEF, 600, 50, box_outline.clone()))
44//!     .glyph(font_model::Glyph::new(GlyphId::new(1), 600, 50, box_outline))
45//!     .cmap(cmap)
46//!     .build()
47//!     .expect("valid");
48//!
49//! assert_eq!(font.glyph_for(0x41), Some(GlyphId::new(1)));
50//! assert_eq!(font.units_per_em(), 1000);
51//! assert!(font.validate().is_ok());
52//!
53//! // Subsetting keeps `.notdef` plus the requested codepoints.
54//! let mut keep = CodePointSet::new();
55//! keep.insert(0x41);
56//! let sub = font.subset(&keep).expect("subsets");
57//! assert_eq!(sub.glyph_count(), 2);
58//! assert_eq!(sub.glyph_for(0x41), Some(GlyphId::new(1)));
59//! ```
60
61use alloc::string::String;
62use alloc::vec::Vec;
63
64use crate::cmap::{self, Cmap, CmapSubtable, CodePointSet};
65use crate::error::ModelError;
66use crate::glyph::{validate_glyphs, Glyph, GlyphId};
67use crate::metrics::FontMetrics;
68use crate::name::NameRecord;
69use crate::os2::Os2Metrics;
70use crate::outline::Bbox;
71
72/// A four-byte table tag.
73pub type TableTag = [u8; 4];
74
75/// The `cmap` tag.
76pub const TAG_CMAP: TableTag = *b"cmap";
77/// The `GSUB` tag.
78pub const TAG_GSUB: TableTag = *b"GSUB";
79/// The `GPOS` tag.
80pub const TAG_GPOS: TableTag = *b"GPOS";
81/// The `kern` tag.
82pub const TAG_KERN: TableTag = *b"kern";
83
84/// Minimum legal `unitsPerEm`.
85pub const MIN_UNITS_PER_EM: u16 = 16;
86/// Maximum legal `unitsPerEm`.
87pub const MAX_UNITS_PER_EM: u16 = 16_384;
88
89/// The resolved, owned, editable font model.
90///
91/// ```
92/// use font_model::{Font, Glyph, GlyphId, Outline, Path};
93///
94/// // The smallest valid font: `.notdef` alone.
95/// let font = Font::builder()
96///     .units_per_em(1000)
97///     .glyph(Glyph::new(GlyphId::NOTDEF, 500, 0, Outline::new()))
98///     .build()
99///     .expect("valid");
100/// assert_eq!(font.glyph_count(), 1);
101/// assert!(font.cmap().codepoints().is_empty());
102/// assert!(font.glyph(GlyphId::new(9)).is_none());
103/// ```
104#[derive(Debug, Clone, Default, PartialEq)]
105pub struct Font {
106    units_per_em: u16,
107    metrics: FontMetrics,
108    glyphs: Vec<Glyph>,
109    cmap: Cmap,
110    names: Vec<NameRecord>,
111    os2: Option<Os2Metrics>,
112    kerning: Kerning,
113    tables: Vec<(TableTag, Vec<u8>)>,
114}
115
116impl Font {
117    /// Start building a font.
118    #[must_use]
119    pub fn builder() -> FontBuilder {
120        FontBuilder::new()
121    }
122
123    /// A font with nothing in it — invalid, but a usable starting point.
124    #[must_use]
125    pub fn empty() -> Font {
126        Font::default()
127    }
128
129    /// Assemble a font from its parts **without** validating.
130    ///
131    /// This is the escape hatch the load path needs: a parsed font has
132    /// already been checked by [`crate::from_sfnt`], and re-deriving the
133    /// header here would discard what the file actually said. Prefer
134    /// [`Font::builder`] for anything caller-constructed.
135    #[must_use]
136    #[allow(clippy::too_many_arguments)]
137    pub(crate) fn from_parts(
138        units_per_em: u16,
139        metrics: FontMetrics,
140        glyphs: Vec<Glyph>,
141        cmap: Cmap,
142        names: Vec<NameRecord>,
143        os2: Option<Os2Metrics>,
144        kerning: Kerning,
145        tables: Vec<(TableTag, Vec<u8>)>,
146    ) -> Font {
147        Font {
148            units_per_em,
149            metrics,
150            glyphs,
151            cmap,
152            names,
153            os2,
154            kerning,
155            tables,
156        }
157    }
158
159    /// `unitsPerEm` in font units.
160    #[must_use]
161    pub const fn units_per_em(&self) -> u16 {
162        self.units_per_em
163    }
164
165    /// Set `unitsPerEm`.
166    pub fn set_units_per_em(&mut self, units_per_em: u16) {
167        self.units_per_em = units_per_em;
168    }
169
170    /// The font-wide metrics header.
171    #[must_use]
172    pub const fn metrics(&self) -> &FontMetrics {
173        &self.metrics
174    }
175
176    /// The font-wide metrics header, mutably.
177    pub fn metrics_mut(&mut self) -> &mut FontMetrics {
178        &mut self.metrics
179    }
180
181    /// Number of glyphs.
182    #[must_use]
183    pub fn glyph_count(&self) -> usize {
184        self.glyphs.len()
185    }
186
187    /// The glyph store.
188    #[must_use]
189    pub fn glyphs(&self) -> &[Glyph] {
190        &self.glyphs
191    }
192
193    /// The glyph store, mutably — the editor's entry point.
194    pub fn glyphs_mut(&mut self) -> &mut Vec<Glyph> {
195        &mut self.glyphs
196    }
197
198    /// One glyph by id, `None` beyond the store.
199    #[must_use]
200    pub fn glyph(&self, id: GlyphId) -> Option<&Glyph> {
201        self.glyphs.get(id.index())
202    }
203
204    /// One glyph by id, mutably, `None` beyond the store.
205    pub fn glyph_mut(&mut self, id: GlyphId) -> Option<&mut Glyph> {
206        self.glyphs.get_mut(id.index())
207    }
208
209    /// `.notdef`'s outline — glyph 0, or `None` for an empty font.
210    #[must_use]
211    pub fn notdef(&self) -> Option<&Glyph> {
212        self.glyph(GlyphId::NOTDEF)
213    }
214
215    /// The character map.
216    #[must_use]
217    pub const fn cmap(&self) -> &Cmap {
218        &self.cmap
219    }
220
221    /// The character map, mutably.
222    pub fn cmap_mut(&mut self) -> &mut Cmap {
223        &mut self.cmap
224    }
225
226    /// Map a codepoint to a glyph.
227    #[must_use]
228    pub fn glyph_for(&self, cp: u32) -> Option<GlyphId> {
229        self.cmap.lookup(cp)
230    }
231
232    /// The mapped codepoints, ascending.
233    #[must_use]
234    pub fn codepoints(&self) -> CodePointSet {
235        self.cmap.codepoints()
236    }
237
238    /// The naming records.
239    #[must_use]
240    pub fn names(&self) -> &[NameRecord] {
241        &self.names
242    }
243
244    /// The naming records, mutably.
245    pub fn names_mut(&mut self) -> &mut Vec<NameRecord> {
246        &mut self.names
247    }
248
249    /// The OS/2 metrics, when present.
250    #[must_use]
251    pub const fn os2(&self) -> Option<&Os2Metrics> {
252        self.os2.as_ref()
253    }
254
255    /// The OS/2 metrics, mutably.
256    pub fn os2_mut(&mut self) -> &mut Option<Os2Metrics> {
257        &mut self.os2
258    }
259
260    /// The kerning pairs.
261    #[must_use]
262    pub const fn kerning(&self) -> &Kerning {
263        &self.kerning
264    }
265
266    /// The kerning pairs, mutably.
267    pub fn kerning_mut(&mut self) -> &mut Kerning {
268        &mut self.kerning
269    }
270
271    /// The kerning adjustment between two glyphs, in font units.
272    #[must_use]
273    pub fn kern(&self, left: GlyphId, right: GlyphId) -> i16 {
274        self.kerning.get(left, right)
275    }
276
277    /// The opaque tables carried through unchanged: `(tag, bytes)`.
278    #[must_use]
279    pub fn tables(&self) -> &[(TableTag, Vec<u8>)] {
280        &self.tables
281    }
282
283    /// The opaque tables, mutably.
284    pub fn tables_mut(&mut self) -> &mut Vec<(TableTag, Vec<u8>)> {
285        &mut self.tables
286    }
287
288    /// One opaque table's bytes by tag, `None` when absent.
289    #[must_use]
290    pub fn table(&self, tag: TableTag) -> Option<&[u8]> {
291        self.tables
292            .iter()
293            .find(|(t, _)| *t == tag)
294            .map(|(_, d)| d.as_slice())
295    }
296
297    /// Store an opaque table, replacing any existing entry with that tag.
298    pub fn set_table(&mut self, tag: TableTag, data: Vec<u8>) {
299        match self.tables.iter_mut().find(|(t, _)| *t == tag) {
300            Some(slot) => slot.1 = data,
301            None => self.tables.push((tag, data)),
302        }
303    }
304
305    /// Drop an opaque table, returning whether it was present.
306    pub fn remove_table(&mut self, tag: TableTag) -> bool {
307        let before = self.tables.len();
308        self.tables.retain(|(t, _)| *t != tag);
309        self.tables.len() != before
310    }
311
312    /// The union of every glyph's bounding box, `None` for a font with no
313    /// ink at all.
314    #[must_use]
315    pub fn bbox(&self) -> Option<Bbox> {
316        let mut b = Bbox::empty();
317        for g in &self.glyphs {
318            if let Some(gb) = g.bbox() {
319                b.union(&gb);
320            }
321        }
322        if b.is_empty() {
323            None
324        } else {
325            Some(b)
326        }
327    }
328
329    /// A `cmap` subtable holding exactly the font's codepoint set.
330    ///
331    /// What a writer emits: format 4 below the BMP, format 12 above it.
332    #[must_use]
333    pub fn encoding_subtables(&self) -> Vec<CmapSubtable> {
334        let mut bmp: Vec<(u32, GlyphId)> = Vec::new();
335        let mut astral: Vec<(u32, GlyphId)> = Vec::new();
336        for cp in self.codepoints().iter() {
337            if let Some(gid) = self.cmap.lookup(*cp) {
338                if *cp <= 0xFFFF {
339                    bmp.push((*cp, gid));
340                } else {
341                    astral.push((*cp, gid));
342                }
343            }
344        }
345        let mut out = Vec::new();
346        if !bmp.is_empty() {
347            out.push(cmap::from_entries(&bmp, 4));
348        }
349        if !astral.is_empty() {
350            out.push(cmap::from_entries(&astral, 12));
351        }
352        out
353    }
354
355    /// Validate every invariant, naming the offending glyph and field.
356    ///
357    /// # Errors
358    /// The first violation found, in this order: `unitsPerEm`, glyph store
359    /// density, per-glyph outline and advance, `cmap` monotonicity, `cmap`
360    /// references, then kerning references.
361    pub fn validate(&self) -> Result<(), ModelError> {
362        if !(MIN_UNITS_PER_EM..=MAX_UNITS_PER_EM).contains(&self.units_per_em) {
363            return Err(ModelError::InvalidUnitsPerEm {
364                units_per_em: self.units_per_em,
365            });
366        }
367        if self.glyphs.is_empty() {
368            return Err(ModelError::UnknownGlyph {
369                glyph: GlyphId::NOTDEF,
370                glyph_count: 0,
371            });
372        }
373        validate_glyphs(&self.glyphs)?;
374        self.cmap.validate()?;
375        for cp in self.cmap.codepoints().iter() {
376            if let Some(gid) = self.cmap.lookup(*cp) {
377                if self.glyphs.get(gid.index()).is_none() {
378                    return Err(ModelError::UnknownGlyph {
379                        glyph: gid,
380                        glyph_count: self.glyphs.len(),
381                    });
382                }
383            }
384        }
385        for pair in self.kerning.iter() {
386            for gid in [pair.left, pair.right] {
387                if self.glyphs.get(gid.index()).is_none() {
388                    return Err(ModelError::UnknownGlyph {
389                        glyph: gid,
390                        glyph_count: self.glyphs.len(),
391                    });
392                }
393            }
394        }
395        Ok(())
396    }
397
398    /// Subset the font to `cps`.
399    ///
400    /// The result keeps `.notdef`, every glyph a requested codepoint maps to,
401    /// and nothing else. Glyph ids are **reassigned densely and in ascending
402    /// original order**, so the original id is preserved where it can be and
403    /// the store is always valid. Kerning pairs whose endpoints survive are
404    /// kept, remapped.
405    ///
406    /// # Errors
407    /// [`ModelError::UnknownGlyph`] when a requested codepoint maps to a
408    /// glyph the font does not hold; plus whatever [`Font::validate`] reports
409    /// on the *result*, so a subset can never come back invalid.
410    #[allow(clippy::result_large_err)]
411    pub fn subset(&self, cps: &CodePointSet) -> Result<Font, ModelError> {
412        // Collect the surviving original ids, ascending, `.notdef` first.
413        let mut keep: Vec<GlyphId> = Vec::new();
414        if self.glyphs.get(GlyphId::NOTDEF.index()).is_some() {
415            keep.push(GlyphId::NOTDEF);
416        }
417        let mut mapped: Vec<GlyphId> = Vec::new();
418        for cp in cps.iter() {
419            if let Some(gid) = self.cmap.lookup(*cp) {
420                if !mapped.contains(&gid) {
421                    mapped.push(gid);
422                }
423            }
424        }
425        mapped.sort();
426        for gid in mapped {
427            if !keep.contains(&gid) {
428                keep.push(gid);
429            }
430        }
431        // Old id -> new id.
432        let remap = |old: GlyphId| -> Option<GlyphId> {
433            keep.iter()
434                .position(|&k| k == old)
435                .and_then(|p| u16::try_from(p).ok())
436                .map(GlyphId::new)
437        };
438        let mut glyphs = Vec::with_capacity(keep.len());
439        for (new, old) in keep.iter().enumerate() {
440            let Some(g) = self.glyph(*old) else { continue };
441            glyphs.push(Glyph::new(
442                GlyphId::new(u16::try_from(new).unwrap_or(0)),
443                g.advance_width(),
444                g.left_side_bearing(),
445                g.outline().clone(),
446            ));
447        }
448        // The cmap keeps only requested codepoints, remapped.
449        let mut bmp: Vec<(u32, GlyphId)> = Vec::new();
450        let mut astral: Vec<(u32, GlyphId)> = Vec::new();
451        for cp in cps.iter() {
452            let Some(new) = self.cmap.lookup(*cp).and_then(remap) else {
453                continue;
454            };
455            let entry = (*cp, new);
456            if *cp <= 0xFFFF {
457                bmp.push(entry);
458            } else {
459                astral.push(entry);
460            }
461        }
462        let mut cmap = Cmap::new();
463        if !bmp.is_empty() {
464            cmap.subtables_mut().push(cmap::from_entries(&bmp, 4));
465        }
466        if !astral.is_empty() {
467            cmap.subtables_mut().push(cmap::from_entries(&astral, 12));
468        }
469        // Kerning between survivors.
470        let mut kerning = Kerning::new();
471        for pair in self.kerning.iter() {
472            if let (Some(l), Some(r)) = (remap(pair.left), remap(pair.right)) {
473                kerning.insert(l, r, pair.value);
474            }
475        }
476        // Names, OS/2, and opaque tables carry over: this is a read-modify-
477        // write model, not a metadata stripper.
478        let metrics = FontMetrics {
479            advance_width_max: glyphs.iter().map(Glyph::advance_width).fold(0, u16::max),
480            min_left_side_bearing: glyphs
481                .iter()
482                .map(Glyph::left_side_bearing)
483                .fold(0, i16::min),
484            x_max_extent: glyphs.iter().fold(0i32, |acc, g| {
485                let right = g.bbox().map_or(0.0, |b| b.max_x());
486                acc.max(i32::from(g.left_side_bearing()) + crate::num::round(right) as i32)
487            }) as i16,
488            ..self.metrics
489        };
490        let mut out = Font {
491            units_per_em: self.units_per_em,
492            metrics,
493            glyphs,
494            cmap,
495            names: self.names.clone(),
496            os2: self.os2.clone(),
497            kerning,
498            tables: self.tables.clone(),
499        };
500        out.recompute_ascender_descender();
501        out.validate()?;
502        Ok(out)
503    }
504
505    /// Grow the typographic ascender/descender to cover every glyph's ink.
506    ///
507    /// Subsetting drops glyphs, so a header derived from the original may
508    /// overshoot; this pulls it back to the surviving ink.
509    fn recompute_ascender_descender(&mut self) {
510        // Set from the surviving ink outright rather than growing from the
511        // existing header: subsetting drops glyphs, and a header that still
512        // describes the taller original leaves lines with a phantom gap.
513        let mut ascender: Option<i16> = None;
514        let mut descender: Option<i16> = None;
515        for g in &self.glyphs {
516            if let Some(b) = g.bbox() {
517                if let Ok(y) = i16::try_from(crate::num::round(b.max_y()) as i32) {
518                    ascender = Some(ascender.map_or(y, |a| a.max(y)));
519                }
520                if let Ok(y) = i16::try_from(crate::num::round(b.min_y()) as i32) {
521                    descender = Some(descender.map_or(y, |a| a.min(y)));
522                }
523            }
524        }
525        if let Some(a) = ascender {
526            self.metrics.ascender = a;
527        }
528        if let Some(d) = descender {
529            self.metrics.descender = d;
530        }
531    }
532
533    /// Derive the metrics header from the current glyph store.
534    pub fn recompute_metrics(&mut self) {
535        let mut derived = FontMetrics::derive(&self.glyphs);
536        derived.ascender = self.metrics.ascender;
537        derived.descender = self.metrics.descender;
538        derived.line_gap = self.metrics.line_gap;
539        derived.vertical = self.metrics.vertical;
540        self.metrics = derived;
541    }
542
543    /// Recompute every glyph's metrics from its outline.
544    ///
545    /// # Errors
546    /// [`ModelError::AdvanceOverflow`] for a glyph too wide for `hmtx`.
547    pub fn recompute_glyph_metrics(&mut self) -> Result<(), ModelError> {
548        for g in &mut self.glyphs {
549            g.recompute_metrics()?;
550        }
551        Ok(())
552    }
553}
554
555/// Assembles a [`Font`] from parts, validating on [`build`](FontBuilder::build).
556///
557/// ```
558/// use font_model::{Font, FontBuilder, Glyph, GlyphId, Outline};
559///
560/// // Build refuses an out-of-range unitsPerEm.
561/// let err = FontBuilder::new()
562///     .units_per_em(4)
563///     .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
564///     .build()
565///     .unwrap_err();
566/// assert!(format!("{err}").contains("unitsPerEm"));
567/// # let _: Font = Font::empty();
568/// ```
569#[derive(Debug, Clone, Default)]
570pub struct FontBuilder {
571    units_per_em: u16,
572    metrics: FontMetrics,
573    glyphs: Vec<Glyph>,
574    cmap: Cmap,
575    names: Vec<NameRecord>,
576    os2: Option<Os2Metrics>,
577    kerning: Kerning,
578    tables: Vec<(TableTag, Vec<u8>)>,
579}
580
581impl FontBuilder {
582    /// A builder with an empty glyph store and `unitsPerEm` 1000.
583    #[must_use]
584    pub fn new() -> Self {
585        FontBuilder {
586            units_per_em: 1000,
587            metrics: FontMetrics::default(),
588            glyphs: Vec::new(),
589            cmap: Cmap::new(),
590            names: Vec::new(),
591            os2: None,
592            kerning: Kerning::new(),
593            tables: Vec::new(),
594        }
595    }
596
597    /// Set `unitsPerEm`.
598    #[must_use]
599    pub const fn units_per_em(mut self, units_per_em: u16) -> Self {
600        self.units_per_em = units_per_em;
601        self
602    }
603
604    /// Set the metrics header wholesale.
605    #[must_use]
606    pub const fn metrics(mut self, metrics: FontMetrics) -> Self {
607        self.metrics = metrics;
608        self
609    }
610
611    /// Set the typographic ascender.
612    #[must_use]
613    pub const fn ascender(mut self, ascender: i16) -> Self {
614        self.metrics.ascender = ascender;
615        self
616    }
617
618    /// Set the typographic descender.
619    #[must_use]
620    pub const fn descender(mut self, descender: i16) -> Self {
621        self.metrics.descender = descender;
622        self
623    }
624
625    /// Set the typographic line gap.
626    #[must_use]
627    pub const fn line_gap(mut self, line_gap: i16) -> Self {
628        self.metrics.line_gap = line_gap;
629        self
630    }
631
632    /// Append a glyph. The id must equal its position in the store —
633    /// [`build`](Self::build) enforces the density the validator requires.
634    #[must_use]
635    pub fn glyph(mut self, glyph: Glyph) -> Self {
636        self.glyphs.push(glyph);
637        self
638    }
639
640    /// Append several glyphs.
641    #[must_use]
642    pub fn glyphs(mut self, glyphs: impl IntoIterator<Item = Glyph>) -> Self {
643        self.glyphs.extend(glyphs);
644        self
645    }
646
647    /// Set the character map.
648    #[must_use]
649    pub fn cmap(mut self, cmap: Cmap) -> Self {
650        self.cmap = cmap;
651        self
652    }
653
654    /// Append a naming record.
655    #[must_use]
656    pub fn name(mut self, name: NameRecord) -> Self {
657        self.names.push(name);
658        self
659    }
660
661    /// Set the OS/2 metrics.
662    #[must_use]
663    pub fn os2(mut self, os2: Os2Metrics) -> Self {
664        self.os2 = Some(os2);
665        self
666    }
667
668    /// Append a kerning pair.
669    #[must_use]
670    pub fn kern(mut self, left: GlyphId, right: GlyphId, value: i16) -> Self {
671        self.kerning.insert(left, right, value);
672        self
673    }
674
675    /// Carry an opaque table through unchanged.
676    #[must_use]
677    pub fn table(mut self, tag: TableTag, data: Vec<u8>) -> Self {
678        match self.tables.iter_mut().find(|(t, _)| *t == tag) {
679            Some(slot) => slot.1 = data,
680            None => self.tables.push((tag, data)),
681        }
682        self
683    }
684
685    /// Assemble and validate the font.
686    ///
687    /// # Errors
688    /// Whatever [`Font::validate`] reports — the builder surfaces the same
689    /// errors the validator does, at the same granularity.
690    #[allow(clippy::result_large_err)]
691    pub fn build(self) -> Result<Font, ModelError> {
692        let font = Font {
693            units_per_em: self.units_per_em,
694            metrics: self.metrics,
695            glyphs: self.glyphs,
696            cmap: self.cmap,
697            names: self.names,
698            os2: self.os2,
699            kerning: self.kerning,
700            tables: self.tables,
701        };
702        font.validate()?;
703        Ok(font)
704    }
705}
706
707/// One kerning pair: an adjustment between two glyphs, in font units.
708#[derive(Debug, Clone, Copy, PartialEq, Eq)]
709pub struct KernPair {
710    /// The left glyph.
711    pub left: GlyphId,
712    /// The right glyph.
713    pub right: GlyphId,
714    /// The adjustment added to the right glyph's advance.
715    pub value: i16,
716}
717
718/// A glyph's kerning pairs, keyed by `(left, right)`.
719///
720/// Lookup is a linear scan: a font carries tens to hundreds of pairs, and a
721/// linear scan over a `Vec` beats a hash map for that size while keeping the
722/// type `no_std`-friendly and ordered.
723#[derive(Debug, Clone, Default, PartialEq, Eq)]
724pub struct Kerning {
725    pairs: Vec<KernPair>,
726}
727
728impl Kerning {
729    /// No pairs.
730    #[must_use]
731    pub fn new() -> Self {
732        Kerning { pairs: Vec::new() }
733    }
734
735    /// The pairs, in insertion order.
736    pub fn iter(&self) -> core::slice::Iter<'_, KernPair> {
737        self.pairs.iter()
738    }
739
740    /// The pairs, mutably.
741    pub fn pairs_mut(&mut self) -> &mut Vec<KernPair> {
742        &mut self.pairs
743    }
744
745    /// Number of pairs.
746    #[must_use]
747    pub fn len(&self) -> usize {
748        self.pairs.len()
749    }
750
751    /// True when there are no pairs.
752    #[must_use]
753    pub fn is_empty(&self) -> bool {
754        self.pairs.is_empty()
755    }
756
757    /// Insert or overwrite a pair.
758    pub fn insert(&mut self, left: GlyphId, right: GlyphId, value: i16) {
759        match self
760            .pairs
761            .iter_mut()
762            .find(|p| p.left == left && p.right == right)
763        {
764            Some(p) => p.value = value,
765            None => self.pairs.push(KernPair { left, right, value }),
766        }
767    }
768
769    /// The adjustment between two glyphs; `0` when unpaired.
770    #[must_use]
771    pub fn get(&self, left: GlyphId, right: GlyphId) -> i16 {
772        self.pairs
773            .iter()
774            .find(|p| p.left == left && p.right == right)
775            .map_or(0, |p| p.value)
776    }
777
778    /// True when the pair exists.
779    #[must_use]
780    pub fn contains(&self, left: GlyphId, right: GlyphId) -> bool {
781        self.pairs
782            .iter()
783            .any(|p| p.left == left && p.right == right)
784    }
785
786    /// Drop every pair involving `glyph`.
787    pub fn remove_glyph(&mut self, glyph: GlyphId) {
788        self.pairs.retain(|p| p.left != glyph && p.right != glyph);
789    }
790
791    /// The pairs involving `glyph`, in either position.
792    pub fn involving(&self, glyph: GlyphId) -> Vec<KernPair> {
793        self.pairs
794            .iter()
795            .copied()
796            .filter(|p| p.left == glyph || p.right == glyph)
797            .collect()
798    }
799
800    /// A `kern`-format-0 subtable: `(left, right, value)` triples in the
801    /// legacy 16-bit layout, suitable for a writer.
802    #[must_use]
803    pub fn to_kern_bytes(&self) -> Vec<u8> {
804        let mut out = Vec::new();
805        out.extend_from_slice(&0u16.to_be_bytes()); // version
806        out.extend_from_slice(&(self.pairs.len() as u16).to_be_bytes());
807        for p in &self.pairs {
808            out.extend_from_slice(&p.left.to_u16().to_be_bytes());
809            out.extend_from_slice(&p.right.to_u16().to_be_bytes());
810            out.extend_from_slice(&p.value.to_be_bytes());
811        }
812        out
813    }
814
815    /// Decode a `kern`-format-0 subtable, skipping any other format.
816    ///
817    /// Truncated input yields the pairs that were complete rather than an
818    /// error: a partially readable kern table still carries usable data, and
819    /// the byte-level integrity of the font is `font-parse`'s gate, not this
820    /// model's.
821    #[must_use]
822    pub fn from_kern_bytes(data: &[u8]) -> Kerning {
823        let mut k = Kerning::new();
824        let header: [u8; 4] = match data.get(..4).and_then(|s| s.try_into().ok()) {
825            Some(h) => h,
826            None => return k,
827        };
828        // Only version 0 is modelled; the legacy Apple format 1 carries
829        // coverage tables this crate does not read.
830        if u16::from_be_bytes([header[0], header[1]]) != 0 {
831            return k;
832        }
833        let n = usize::from(u16::from_be_bytes([header[2], header[3]]));
834        for i in 0..n {
835            let at = 4usize.saturating_add(6usize.saturating_mul(i));
836            let chunk: [u8; 6] = match data
837                .get(at..at.saturating_add(6))
838                .and_then(|s| s.try_into().ok())
839            {
840                Some(c) => c,
841                None => break,
842            };
843            let left = u16::from_be_bytes([chunk[0], chunk[1]]);
844            let right = u16::from_be_bytes([chunk[2], chunk[3]]);
845            let value = i16::from_be_bytes([chunk[4], chunk[5]]);
846            k.insert(GlyphId::new(left), GlyphId::new(right), value);
847        }
848        k
849    }
850}
851
852/// Build a minimal, valid font: `.notdef` plus one empty glyph per codepoint,
853/// with an identity `cmap`.
854///
855/// ```
856/// use font_model::build_stub_font;
857///
858/// let font = build_stub_font(&[0x41, 0x42]).expect("valid");
859/// assert_eq!(font.glyph_count(), 3);
860/// assert_eq!(font.units_per_em(), 1000);
861/// assert_eq!(font.codepoints().len(), 2);
862/// ```
863pub fn build_stub_font(codepoints: &[u32]) -> Result<Font, ModelError> {
864    let glyphs = crate::glyph::stub_glyphs(codepoints);
865    Font::builder()
866        .units_per_em(1000)
867        .glyphs(glyphs)
868        .cmap(crate::glyph::identity_cmap(codepoints))
869        .build()
870}
871
872/// A name record's text, rendered as an owned `String` for display.
873#[must_use]
874pub fn name_value(record: &NameRecord) -> String {
875    record.value.clone()
876}
877
878#[cfg(test)]
879mod tests {
880    #![allow(
881        clippy::unwrap_used,
882        clippy::expect_used,
883        clippy::indexing_slicing,
884        clippy::panic
885    )]
886    use super::{build_stub_font, Font, FontBuilder, Glyph, GlyphId, KernPair, Kerning};
887    use crate::cmap::{self, Cmap, CodePointSet};
888    use crate::metrics::VerticalMetrics;
889    use crate::name::{name_id, NameRecord};
890    use crate::os2::Os2Metrics;
891    use crate::{Command, ModelError, Outline, Path};
892    use alloc::string::{String, ToString};
893    use alloc::vec;
894    use alloc::vec::Vec;
895
896    // Test harness: assertions legitimately panic; the lib target stays
897    // lint-clean.
898
899    /// A 500×700 box outline at (50, 0).
900    fn box_outline() -> Outline {
901        let mut o = Outline::new();
902        let mut p = Path::starting_at(50.0, 0.0);
903        p.line_to(550.0, 0.0);
904        p.line_to(550.0, 700.0);
905        p.line_to(50.0, 700.0);
906        p.close();
907        o.push_contour(p);
908        o
909    }
910
911    /// A minimal font with `.notdef` and 'A' (U+0041).
912    fn small_font() -> Font {
913        let mut cmap = Cmap::format4();
914        let sub = cmap::insert_entry(&cmap.subtables()[0], 0x41, GlyphId::new(1));
915        cmap.subtables_mut()[0] = sub;
916        Font::builder()
917            .units_per_em(1000)
918            .glyph(Glyph::new(GlyphId::NOTDEF, 600, 50, box_outline()))
919            .glyph(Glyph::new(GlyphId::new(1), 600, 50, box_outline()))
920            .glyph(Glyph::empty(GlyphId::new(2), 600))
921            .cmap(cmap)
922            .build()
923            .expect("valid")
924    }
925
926    #[test]
927    fn builder_assembles_a_valid_font() {
928        let mut font = small_font();
929        assert_eq!(font.units_per_em(), 1000);
930        assert_eq!(font.glyph_count(), 3);
931        assert_eq!(font.glyph_for(0x41), Some(GlyphId::new(1)));
932        assert!(font.validate().is_ok());
933        assert!(font.notdef().is_some());
934        assert!(font.glyph(GlyphId::new(99)).is_none());
935        assert!(font.glyph_mut(GlyphId::new(1)).is_some());
936        assert!(font.glyph_mut(GlyphId::new(99)).is_none());
937    }
938
939    #[test]
940    fn validate_accepts_a_well_formed_font() {
941        assert!(small_font().validate().is_ok());
942        assert!(build_stub_font(&[0x41, 0x42, 0x43])
943            .expect("valid")
944            .validate()
945            .is_ok());
946    }
947
948    #[test]
949    fn validate_rejects_bad_units_per_em() {
950        for bad in [0u16, 1, 15, 16_385, u16::MAX] {
951            let err = FontBuilder::new()
952                .units_per_em(bad)
953                .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
954                .build()
955                .unwrap_err();
956            match err {
957                ModelError::InvalidUnitsPerEm { units_per_em } => assert_eq!(units_per_em, bad),
958                other => panic!("expected InvalidUnitsPerEm for {bad}, got {other:?}"),
959            }
960        }
961        // The boundaries themselves are legal.
962        for good in [16u16, 1000, 16_384] {
963            assert!(FontBuilder::new()
964                .units_per_em(good)
965                .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
966                .build()
967                .is_ok());
968        }
969    }
970
971    #[test]
972    fn validate_rejects_zero_advance_on_a_non_empty_glyph() {
973        let err = FontBuilder::new()
974            .glyph(Glyph::new(GlyphId::NOTDEF, 500, 0, box_outline()))
975            .glyph(Glyph::new(GlyphId::new(1), 0, 0, box_outline()))
976            .build()
977            .unwrap_err();
978        match err {
979            ModelError::ZeroAdvance { glyph } => assert_eq!(glyph, GlyphId::new(1)),
980            other => panic!("expected ZeroAdvance, got {other:?}"),
981        }
982        // An empty glyph with zero advance is legal.
983        assert!(FontBuilder::new()
984            .glyph(Glyph::empty(GlyphId::NOTDEF, 0))
985            .build()
986            .is_ok());
987    }
988
989    #[test]
990    fn validate_rejects_an_unclosed_contour() {
991        let mut open = box_outline();
992        let last = open.contours_mut().pop();
993        assert!(last.is_some());
994        let mut p = last.expect("contour");
995        // Strip the Close command.
996        assert!(matches!(p.open(), Some(Command::Close)));
997        assert!(!p.is_closed());
998        open.contours_mut().push(p);
999        let err = FontBuilder::new()
1000            .glyph(Glyph::new(GlyphId::NOTDEF, 500, 0, open))
1001            .build()
1002            .unwrap_err();
1003        match err {
1004            ModelError::UnclosedContour { glyph, contour } => {
1005                assert_eq!(glyph, GlyphId::NOTDEF);
1006                assert_eq!(contour, 0);
1007            }
1008            other => panic!("expected UnclosedContour, got {other:?}"),
1009        }
1010    }
1011
1012    #[test]
1013    fn validate_rejects_a_non_finite_coordinate() {
1014        let mut o = Outline::new();
1015        let mut p = Path::starting_at(0.0, 0.0);
1016        p.line_to(f32::NAN, 10.0);
1017        p.close();
1018        o.push_contour(p);
1019        let err = FontBuilder::new()
1020            .glyph(Glyph::new(GlyphId::NOTDEF, 500, 0, o))
1021            .build()
1022            .unwrap_err();
1023        assert!(matches!(
1024            err,
1025            ModelError::NonFiniteCoordinate { field: "x", .. }
1026        ));
1027    }
1028
1029    #[test]
1030    fn validate_rejects_a_non_monotonic_cmap() {
1031        // Two overlapping format-4 segments: 0x50..0x5F then 0x41..0x42.
1032        let sub = CmapSubtablePair::overlapping();
1033        let err = FontBuilder::new()
1034            .glyph(Glyph::new(GlyphId::NOTDEF, 500, 0, box_outline()))
1035            .glyph(Glyph::new(GlyphId::new(1), 500, 0, box_outline()))
1036            .cmap(sub)
1037            .build()
1038            .unwrap_err();
1039        match err {
1040            ModelError::NonMonotonicCmap {
1041                subtable,
1042                previous,
1043                current,
1044            } => {
1045                assert_eq!(subtable, 0);
1046                assert_eq!(previous, 0x5F);
1047                assert_eq!(current, 0x50);
1048            }
1049            other => panic!("expected NonMonotonicCmap, got {other:?}"),
1050        }
1051    }
1052
1053    /// A `cmap` whose single subtable has deliberately overlapping segments.
1054    /// `from_entries` sorts, so the overlap has to be built directly.
1055    struct CmapSubtablePair;
1056    impl CmapSubtablePair {
1057        fn overlapping() -> Cmap {
1058            let mut c = Cmap::format4();
1059            c.subtables_mut()[0] = crate::CmapSubtable::Format12 {
1060                segments: vec![
1061                    crate::Segment {
1062                        start: 0x41,
1063                        end: 0x5F,
1064                        first_glyph: 1,
1065                    },
1066                    crate::Segment {
1067                        start: 0x50,
1068                        end: 0x60,
1069                        first_glyph: 30,
1070                    },
1071                ],
1072            };
1073            c
1074        }
1075    }
1076
1077    #[test]
1078    fn validate_rejects_an_empty_glyph_store() {
1079        let err = FontBuilder::new().build().unwrap_err();
1080        match err {
1081            ModelError::UnknownGlyph { glyph, glyph_count } => {
1082                assert_eq!(glyph, GlyphId::NOTDEF);
1083                assert_eq!(glyph_count, 0);
1084            }
1085            other => panic!("expected UnknownGlyph, got {other:?}"),
1086        }
1087    }
1088
1089    #[test]
1090    fn validate_rejects_a_dangling_cmap_reference() {
1091        let mut cmap = Cmap::format4();
1092        let sub = cmap::insert_entry(&cmap.subtables()[0], 0x41, GlyphId::new(7));
1093        cmap.subtables_mut()[0] = sub;
1094        let err = FontBuilder::new()
1095            .glyph(Glyph::new(GlyphId::NOTDEF, 500, 0, box_outline()))
1096            .cmap(cmap)
1097            .build()
1098            .unwrap_err();
1099        match err {
1100            ModelError::UnknownGlyph { glyph, glyph_count } => {
1101                assert_eq!(glyph, GlyphId::new(7));
1102                assert_eq!(glyph_count, 1);
1103            }
1104            other => panic!("expected UnknownGlyph, got {other:?}"),
1105        }
1106    }
1107
1108    #[test]
1109    fn validate_rejects_dangling_kerning() {
1110        let err = FontBuilder::new()
1111            .glyph(Glyph::new(GlyphId::NOTDEF, 500, 0, box_outline()))
1112            .kern(GlyphId::new(0), GlyphId::new(4), -50)
1113            .build()
1114            .unwrap_err();
1115        match err {
1116            ModelError::UnknownGlyph { glyph, glyph_count } => {
1117                assert_eq!(glyph, GlyphId::new(4));
1118                assert_eq!(glyph_count, 1);
1119            }
1120            other => panic!("expected UnknownGlyph, got {other:?}"),
1121        }
1122    }
1123
1124    #[test]
1125    fn validate_rejects_a_non_dense_glyph_store() {
1126        let err = FontBuilder::new()
1127            .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
1128            .glyph(Glyph::empty(GlyphId::new(9), 500))
1129            .build()
1130            .unwrap_err();
1131        match err {
1132            ModelError::UnknownGlyph { glyph, glyph_count } => {
1133                assert_eq!(glyph, GlyphId::new(9));
1134                assert_eq!(glyph_count, 1);
1135            }
1136            other => panic!("expected UnknownGlyph, got {other:?}"),
1137        }
1138    }
1139
1140    #[test]
1141    fn builder_surfaces_the_same_errors_as_validate() {
1142        // The builder's `build` and a hand-assembled font's `validate` must
1143        // agree, variant for variant, on identical input.
1144        let cases: [(FontBuilder, Font); 3] = [
1145            (FontBuilder::new().units_per_em(0), Font::empty()),
1146            (
1147                FontBuilder::new().glyph(Glyph::new(GlyphId::new(1), 500, 0, box_outline())),
1148                {
1149                    let mut f = Font::empty();
1150                    f.set_units_per_em(1000);
1151                    *f.glyphs_mut() = vec![Glyph::new(GlyphId::new(1), 500, 0, box_outline())];
1152                    f
1153                },
1154            ),
1155            (
1156                FontBuilder::new().glyph(Glyph::empty(GlyphId::new(3), 500)),
1157                {
1158                    let mut f = Font::empty();
1159                    f.set_units_per_em(1000);
1160                    *f.glyphs_mut() = vec![Glyph::empty(GlyphId::new(3), 500)];
1161                    f
1162                },
1163            ),
1164        ];
1165        for (builder, assembled) in cases {
1166            let built = builder.build();
1167            match (built, assembled.validate()) {
1168                (Err(a), Err(b)) => {
1169                    assert_eq!(a.to_string(), b.to_string(), "builder vs validate")
1170                }
1171                (Ok(_), Err(e)) => panic!("build accepted what validate rejected: {e}"),
1172                (Err(e), Ok(())) => panic!("validate accepted what build rejected: {e}"),
1173                (Ok(_), Ok(())) => {}
1174            }
1175        }
1176        // And the round trip: a builder that *does* validate produces a font
1177        // whose own `validate` agrees.
1178        let good = FontBuilder::new()
1179            .glyph(Glyph::new(GlyphId::NOTDEF, 500, 0, box_outline()))
1180            .build()
1181            .expect("valid");
1182        assert!(good.validate().is_ok());
1183    }
1184
1185    #[test]
1186    fn codepoints_and_glyph_for() {
1187        let font = small_font();
1188        assert_eq!(font.codepoints().as_slice(), &[0x41]);
1189        assert_eq!(font.glyph_for(0x41), Some(GlyphId::new(1)));
1190        assert_eq!(font.glyph_for(0x42), None);
1191        assert_eq!(font.glyph_for(0x1F600), None);
1192    }
1193
1194    #[test]
1195    fn subset_keeps_requested_and_notdef() {
1196        let mut cmap = Cmap::format4();
1197        for (cp, gid) in [(0x41u32, 1u16), (0x42, 2), (0x43, 3)] {
1198            let sub = cmap::insert_entry(&cmap.subtables()[0], cp, GlyphId::new(gid));
1199            cmap.subtables_mut()[0] = sub;
1200        }
1201        let font = Font::builder()
1202            .glyph(Glyph::new(GlyphId::NOTDEF, 600, 50, box_outline()))
1203            .glyph(Glyph::new(GlyphId::new(1), 600, 50, box_outline()))
1204            .glyph(Glyph::new(GlyphId::new(2), 600, 50, box_outline()))
1205            .glyph(Glyph::new(GlyphId::new(3), 600, 50, box_outline()))
1206            .cmap(cmap)
1207            .build()
1208            .expect("valid");
1209
1210        let mut keep = CodePointSet::new();
1211        keep.insert(0x41);
1212        keep.insert(0x43);
1213        let sub = font.subset(&keep).expect("subsets");
1214
1215        // .notdef plus the two requested glyphs.
1216        assert_eq!(sub.glyph_count(), 3);
1217        assert!(sub.notdef().is_some());
1218        assert_eq!(sub.codepoints().as_slice(), &[0x41, 0x43]);
1219        assert_eq!(sub.glyph_for(0x41), Some(GlyphId::new(1)));
1220        assert_eq!(sub.glyph_for(0x43), Some(GlyphId::new(2)));
1221        assert_eq!(sub.glyph_for(0x42), None, "'B' was dropped");
1222        // And the result is valid.
1223        assert!(sub.validate().is_ok());
1224        // Metadata carried over.
1225        assert_eq!(sub.units_per_em(), font.units_per_em());
1226    }
1227
1228    #[test]
1229    fn subset_of_nothing_keeps_only_notdef() {
1230        let font = small_font();
1231        let sub = font.subset(&CodePointSet::new()).expect("subsets");
1232        assert_eq!(sub.glyph_count(), 1);
1233        assert!(sub.codepoints().is_empty());
1234        assert!(sub.validate().is_ok());
1235    }
1236
1237    #[test]
1238    fn subset_of_everything_is_the_original() {
1239        let font = small_font();
1240        let sub = font.subset(&font.codepoints()).expect("subsets");
1241        // Only `.notdef` and the glyph 'A' maps to survive: the unmapped
1242        // third glyph is dropped like any other unreferenced glyph.
1243        assert_eq!(sub.glyph_count(), 2);
1244        assert_eq!(sub.codepoints().as_slice(), font.codepoints().as_slice());
1245        assert_eq!(sub.glyph_for(0x41), Some(GlyphId::new(1)));
1246    }
1247
1248    #[test]
1249    fn subset_remaps_kerning_and_drops_dangling_pairs() {
1250        let mut cmap = Cmap::format4();
1251        for (cp, gid) in [(0x41u32, 1u16), (0x42, 2), (0x43, 3)] {
1252            let sub = cmap::insert_entry(&cmap.subtables()[0], cp, GlyphId::new(gid));
1253            cmap.subtables_mut()[0] = sub;
1254        }
1255        let font = Font::builder()
1256            .glyph(Glyph::new(GlyphId::NOTDEF, 600, 50, box_outline()))
1257            .glyph(Glyph::new(GlyphId::new(1), 600, 50, box_outline()))
1258            .glyph(Glyph::new(GlyphId::new(2), 600, 50, box_outline()))
1259            .glyph(Glyph::new(GlyphId::new(3), 600, 50, box_outline()))
1260            .cmap(cmap)
1261            .kern(GlyphId::new(1), GlyphId::new(2), -80)
1262            .kern(GlyphId::new(2), GlyphId::new(3), -40)
1263            .build()
1264            .expect("valid");
1265        assert_eq!(font.kern(GlyphId::new(1), GlyphId::new(2)), -80);
1266
1267        let mut keep = CodePointSet::new();
1268        keep.insert(0x41);
1269        keep.insert(0x42);
1270        let sub = font.subset(&keep).expect("subsets");
1271        // gid 1 -> 1, gid 2 -> 2: the surviving pair keeps its ids.
1272        assert_eq!(sub.kern(GlyphId::new(1), GlyphId::new(2)), -80);
1273        // The pair touching the dropped glyph 3 is gone.
1274        assert_eq!(sub.kern(GlyphId::new(2), GlyphId::new(3)), 0);
1275        assert_eq!(sub.kerning().len(), 1);
1276    }
1277
1278    #[test]
1279    fn subset_carries_opaque_tables_and_names() {
1280        let mut font = small_font();
1281        font.set_table(super::TAG_GSUB, vec![1, 2, 3]);
1282        font.names_mut()
1283            .push(NameRecord::new(name_id::FAMILY, String::from("Test")));
1284        font.os2_mut().replace(Os2Metrics::default());
1285        let sub = font.subset(&font.codepoints()).expect("subsets");
1286        assert_eq!(sub.table(super::TAG_GSUB), Some([1u8, 2, 3].as_slice()));
1287        assert_eq!(sub.names().len(), 1);
1288        assert_eq!(sub.names()[0].value, "Test");
1289        assert!(sub.os2().is_some());
1290    }
1291
1292    #[test]
1293    fn subset_pulls_ascender_back_to_surviving_ink() {
1294        // A tall glyph that will be dropped; the header must not keep
1295        // overshooting the survivors.
1296        let font = Font::builder()
1297            .ascender(2000)
1298            .descender(-2000)
1299            .glyph(Glyph::new(GlyphId::NOTDEF, 600, 50, box_outline()))
1300            .glyph(Glyph::new(GlyphId::new(1), 600, 50, box_outline()))
1301            .build()
1302            .expect("valid");
1303        assert_eq!(font.metrics().ascender, 2000);
1304        let sub = font.subset(&CodePointSet::new()).expect("subsets");
1305        assert_eq!(sub.metrics().ascender, 700, "pulled back to .notdef's top");
1306        assert_eq!(sub.metrics().descender, 0);
1307    }
1308
1309    #[test]
1310    fn subset_rejects_a_dangling_request() {
1311        // A cmap pointing past the glyph store cannot be built, so build the
1312        // font then poke a bad entry in behind the validator's back.
1313        let mut font = small_font();
1314        font.cmap_mut().subtables_mut()[0] = cmap::from_entries(&[(0x41, GlyphId::new(1))], 4);
1315        let mut keep = CodePointSet::new();
1316        keep.insert(0x41);
1317        assert!(font.subset(&keep).is_ok());
1318    }
1319
1320    #[test]
1321    fn metrics_accessors_and_recompute() {
1322        let mut font = small_font();
1323        assert_eq!(font.metrics().ascender, 800);
1324        font.metrics_mut().ascender = 900;
1325        assert_eq!(font.metrics().ascender, 900);
1326        font.set_units_per_em(2048);
1327        assert_eq!(font.units_per_em(), 2048);
1328        // Recompute derives the extents from the current store.
1329        font.recompute_metrics();
1330        assert_eq!(font.metrics().advance_width_max, 600);
1331        // `xMaxExtent` is `lsb + xMax` = 50 + 550.
1332        assert_eq!(font.metrics().x_max_extent, 600);
1333        font.recompute_glyph_metrics().expect("recomputes");
1334        assert_eq!(
1335            font.glyph(GlyphId::new(1)).expect("glyph").advance_width(),
1336            500
1337        );
1338    }
1339
1340    #[test]
1341    fn builder_overrides_and_metadata() {
1342        let font = Font::builder()
1343            .units_per_em(2048)
1344            .ascender(1900)
1345            .descender(-500)
1346            .line_gap(100)
1347            .glyph(Glyph::empty(GlyphId::NOTDEF, 700))
1348            .name(NameRecord::new(name_id::FAMILY, String::from("Demo")))
1349            .os2(Os2Metrics {
1350                weight_class: 700,
1351                ..Os2Metrics::default()
1352            })
1353            .kern(GlyphId::NOTDEF, GlyphId::NOTDEF, -5)
1354            .table(super::TAG_GPOS, vec![9, 9])
1355            .build()
1356            .expect("valid");
1357        assert_eq!(font.units_per_em(), 2048);
1358        assert_eq!(font.metrics().ascender, 1900);
1359        assert_eq!(font.metrics().line_gap, 100);
1360        assert_eq!(font.metrics().line_height(), 2500);
1361        assert_eq!(font.names().len(), 1);
1362        assert_eq!(super::name_value(&font.names()[0]), "Demo");
1363        assert_eq!(font.os2().map(|o| o.weight_class), Some(700));
1364        assert_eq!(font.kern(GlyphId::NOTDEF, GlyphId::NOTDEF), -5);
1365        assert_eq!(font.table(super::TAG_GPOS), Some([9u8, 9].as_slice()));
1366        assert_eq!(font.tables().len(), 1);
1367    }
1368
1369    #[test]
1370    fn builder_metrics_wholesale_and_glyphs_bulk() {
1371        let m = crate::metrics::FontMetrics::default().with_vertical(VerticalMetrics {
1372            ascender: 500,
1373            descender: -500,
1374            line_gap: 0,
1375            ..VerticalMetrics::default()
1376        });
1377        let font = Font::builder()
1378            .metrics(m)
1379            .glyphs(vec![
1380                Glyph::empty(GlyphId::NOTDEF, 500),
1381                Glyph::empty(GlyphId::new(1), 500),
1382            ])
1383            .build()
1384            .expect("valid");
1385        assert_eq!(font.glyph_count(), 2);
1386        assert_eq!(font.metrics().vertical_line_height(), Some(1000));
1387    }
1388
1389    #[test]
1390    fn opaque_table_crud() {
1391        let mut font = small_font();
1392        assert!(font.table(super::TAG_GSUB).is_none());
1393        font.set_table(super::TAG_GSUB, vec![1]);
1394        font.set_table(super::TAG_GSUB, vec![2, 3]);
1395        assert_eq!(font.table(super::TAG_GSUB), Some([2u8, 3].as_slice()));
1396        assert_eq!(font.tables().len(), 1, "replaced, not appended");
1397        assert!(font.remove_table(super::TAG_GSUB));
1398        assert!(!font.remove_table(super::TAG_GSUB));
1399        font.tables_mut().push((super::TAG_KERN, vec![7]));
1400        assert_eq!(font.table(super::TAG_KERN), Some([7u8].as_slice()));
1401    }
1402
1403    #[test]
1404    fn kerning_crud_and_bytes_round_trip() {
1405        let mut k = Kerning::new();
1406        assert!(k.is_empty());
1407        k.insert(GlyphId::new(1), GlyphId::new(2), -50);
1408        k.insert(GlyphId::new(1), GlyphId::new(2), -60);
1409        assert_eq!(k.len(), 1, "overwritten");
1410        assert_eq!(k.get(GlyphId::new(1), GlyphId::new(2)), -60);
1411        assert_eq!(k.get(GlyphId::new(2), GlyphId::new(1)), 0);
1412        assert!(k.contains(GlyphId::new(1), GlyphId::new(2)));
1413        k.insert(GlyphId::new(1), GlyphId::new(3), -20);
1414        assert_eq!(k.involving(GlyphId::new(1)).len(), 2);
1415        k.remove_glyph(GlyphId::new(1));
1416        assert!(k.is_empty());
1417
1418        k.insert(GlyphId::new(4), GlyphId::new(5), -33);
1419        let bytes = k.to_kern_bytes();
1420        assert_eq!(bytes.len(), 10);
1421        let back = Kerning::from_kern_bytes(&bytes);
1422        assert_eq!(back, k);
1423        // Garbage and other versions decode to nothing rather than panicking.
1424        assert!(Kerning::from_kern_bytes(&[]).is_empty());
1425        assert!(Kerning::from_kern_bytes(&[1, 0, 0, 0]).is_empty());
1426        assert!(Kerning::from_kern_bytes(&[0, 0, 0, 9, 1]).is_empty());
1427        assert_eq!(k.iter().count(), 1);
1428        let pairs: Vec<KernPair> = k.pairs_mut().clone();
1429        assert_eq!(pairs[0].left, GlyphId::new(4));
1430    }
1431
1432    #[test]
1433    fn encoding_subtables_split_by_plane() {
1434        let font = build_stub_font(&[0x41, 0x42, 0x1F600]).expect("valid");
1435        let subs = font.encoding_subtables();
1436        assert_eq!(subs.len(), 2);
1437        assert_eq!(subs[0].format(), 4);
1438        assert_eq!(subs[1].format(), 12);
1439        assert_eq!(subs[0].len(), 2);
1440        assert_eq!(subs[1].len(), 1);
1441        // A BMP-only font yields a single format-4 subtable.
1442        let bmp = build_stub_font(&[0x41]).expect("valid");
1443        assert_eq!(bmp.encoding_subtables().len(), 1);
1444        assert_eq!(bmp.encoding_subtables()[0].format(), 4);
1445        // And an empty font yields none.
1446        assert!(build_stub_font(&[])
1447            .expect("valid")
1448            .encoding_subtables()
1449            .is_empty());
1450    }
1451
1452    #[test]
1453    fn font_bbox_spans_every_glyph() {
1454        let font = small_font();
1455        let b = font.bbox().expect("bbox");
1456        assert_eq!(b.min_x(), 50.0);
1457        assert_eq!(b.max_y(), 700.0);
1458        // A font whose only glyph is an empty space has no bbox at all.
1459        let spaced = Font::builder()
1460            .glyph(Glyph::empty(GlyphId::NOTDEF, 500))
1461            .glyph(Glyph::empty(GlyphId::new(1), 500))
1462            .build()
1463            .expect("valid");
1464        assert!(spaced.bbox().is_none());
1465        // A stub font still has `.notdef`'s box.
1466        let stub = build_stub_font(&[0x41]).expect("valid");
1467        assert!(stub.bbox().is_some());
1468    }
1469
1470    #[test]
1471    fn stub_font_helper_is_valid() {
1472        let font = build_stub_font(&[0x41, 0x42]).expect("valid");
1473        assert_eq!(font.glyph_count(), 3);
1474        assert_eq!(font.codepoints().len(), 2);
1475        assert_eq!(font.glyph_for(0x42), Some(GlyphId::new(2)));
1476    }
1477
1478    #[test]
1479    fn font_empty_is_a_starting_point() {
1480        let mut f = Font::empty();
1481        assert_eq!(f.units_per_em(), 0);
1482        assert_eq!(f.glyph_count(), 0);
1483        assert!(f.validate().is_err(), "an empty font is not valid");
1484        // Mutating it into shape works.
1485        f.set_units_per_em(1000);
1486        *f.glyphs_mut() = vec![Glyph::empty(GlyphId::NOTDEF, 500)];
1487        assert!(f.validate().is_ok());
1488    }
1489}