Skip to main content

read_fonts/model/
font.rs

1//! Font representation.
2
3mod blob;
4mod cache;
5mod format;
6mod source;
7mod tables;
8
9#[doc(inline)]
10pub use blob::Blob;
11#[doc(inline)]
12pub use format::Format;
13#[doc(inline)]
14pub use source::Source;
15#[doc(inline)]
16pub use tables::{TableFunction, Tables};
17
18// Do our best to not expose this to users through docs or rust-analyzer.
19#[doc(hidden)]
20#[rust_analyzer::completions(hidden_from_completion)]
21pub mod interop;
22
23use super::attribute::Attributes;
24use super::charmap::{Charmap, EncodingTables, SfntUnicodeCharmap};
25use super::glyph::{
26    bitmap::BitmapStrikes,
27    color::{ColorGlyphs, Palettes},
28    outline::{varc, OutlineGlyphs, OutlineSource},
29    GlyphSource, GlyphSourceOrder,
30};
31use super::metrics::{empty_glyph_metrics, GlyphMetrics, Metrics, StyleMetrics};
32use super::name::{self, GlyphName, Names};
33use super::once::Once;
34use super::variation::{Axes, NamedInstances, NormalizedCoord, Variation};
35use crate::tables::glyf::outline::OutlineContext;
36use crate::tables::loca::LocaGlyph;
37use crate::tables::{
38    avar::Avar,
39    fvar::Fvar,
40    glyf::{Glyf, PHANTOM_POINT_COUNT},
41    gvar::{GlyphVariationData, SelectedGvar},
42    hmtx::GlyphMetricRecords,
43    hvar::Hvar,
44    layout::SelectedFeatureVariations,
45    loca::Loca,
46    vorg::Vorg,
47    vvar::Vvar,
48};
49use crate::{
50    ps::{
51        cff::{CffFontRef, Subfont},
52        type1::{MultipleMaster, Type1Font, Type1Instance},
53    },
54    tables::{
55        cbdt::Cbdt, cblc::Cblc, cpal::Cpal, ebdt::Ebdt, eblc::Eblc, fvar::VariationAxisRecord,
56        sbix::Sbix,
57    },
58    TableProvider,
59};
60use alloc::{boxed::Box, sync::Arc};
61pub(crate) use cache::ColrTables;
62use cache::{
63    CbdtTables, Cff2Font, CffFont, CpalTable, EbdtTables, GlyfLoca, GvarTable, HvarTable,
64    MetricsTable, SbixTable, TableCache, VorgTable, VvarTable,
65};
66use core::{
67    any::Any,
68    sync::atomic::{self, AtomicBool, AtomicU32},
69};
70use smallvec::SmallVec;
71use types::{F2Dot14, Fixed, GlyphId, Point};
72use yoke::Yoke;
73
74/// A font at one location in its design space.
75///
76/// Cloning is cheap: clones share one instance rather than copying it.
77#[derive(Clone)]
78pub struct Font(Repr);
79
80#[derive(Clone)]
81enum Repr {
82    Default(SharedFont),
83    Varied(Arc<VariedInstance>),
84}
85
86impl Font {
87    /// Creates a font from `source`, at its default location.
88    ///
89    /// `index` selects a font within the data:
90    ///
91    /// - SFNT: the font in a collection (`ttc` or `otc`). Data holding a
92    ///   single font accepts only zero.
93    /// - Standalone CFF: the font in the CFF font set.
94    /// - Type 1: ignored, since the data holds one font.
95    /// - [`TableFunction`]: ignored, since the function supplies the tables
96    ///   of one font.
97    ///
98    /// Returns `None` if the source holds no font in a supported format, or
99    /// none at `index`. Type 1 fonts require the `type1` feature.
100    pub fn new(source: impl Into<Source>, index: u32) -> Option<Self> {
101        Some(Font(Repr::Default(SharedFont::new(source, index)?)))
102    }
103
104    /// Returns the font's variation axes, which are empty if the font is not
105    /// variable.
106    pub fn axes(&self) -> Axes<'_> {
107        Axes::new(self)
108    }
109
110    /// Returns the named instances defined by the font.
111    pub fn named_instances(&self) -> NamedInstances<'_> {
112        NamedInstances::new(self)
113    }
114
115    /// Returns a builder for another instance of the same font.
116    ///
117    /// The two share everything the location does not change, so deriving one
118    /// instance from another costs no more than reading the tables once.
119    pub fn instance_builder(&self) -> InstanceBuilder {
120        InstanceBuilder {
121            font: self.shared().clone(),
122            coords: CoordStorage::default(),
123            type1_blend: SmallVec::new(),
124        }
125    }
126
127    /// Returns this font at its default location.
128    #[inline]
129    pub fn default_instance(&self) -> Font {
130        Font(Repr::Default(self.shared().clone()))
131    }
132
133    /// Returns the normalized variation coordinates for this font instance.
134    pub fn normalized_coords(&self) -> &[NormalizedCoord] {
135        match &self.0 {
136            Repr::Default(_) => &[],
137            Repr::Varied(varied) => varied.coords.as_slice(),
138        }
139    }
140
141    /// Returns the layout feature variations this instance selects.
142    pub fn feature_variations(&self) -> SelectedFeatureVariations {
143        match self.sfnt_location() {
144            Some(location) => location
145                .feature_vars
146                .load(self.shared(), self.normalized_coords()),
147            // Only an SFNT font has layout tables to vary.
148            None => SelectedFeatureVariations::default(),
149        }
150    }
151
152    /// Returns the number of glyphs in the font.
153    ///
154    /// Fixed for the font: no location varies it.
155    #[inline]
156    pub fn num_glyphs(&self) -> u32 {
157        self.shared().num_glyphs()
158    }
159
160    /// Returns the size of the em square, in font units.
161    ///
162    /// Fixed for the font: no location varies it.
163    #[inline]
164    pub fn units_per_em(&self) -> u16 {
165        self.shared().units_per_em()
166    }
167
168    /// Returns the width, style and weight of the default instance.
169    ///
170    /// For an SFNT font, these come from the OS/2 table, with the `post`
171    /// italic angle for an oblique style. If there is no OS/2 table, they
172    /// come from `head`. These tables do not vary, so every instance of a
173    /// variable font returns the same values. To get the attributes at a
174    /// location, use [`Attributes::from_variations`].
175    ///
176    /// For a Type 1 or standalone CFF font, these come from the `Weight` name
177    /// and `ItalicAngle`.
178    pub fn default_attributes(&self) -> Attributes {
179        Attributes::from_font(self)
180    }
181
182    /// Returns `true` if the font needs its TrueType instructions to draw
183    /// correct contours.
184    ///
185    /// Such fonts are often called "tricky". They are recognized by family name
186    /// or by the checksums of the `cvt`, `fpgm` and `prep` tables, and only
187    /// fonts with `glyf` outlines qualify. The result is computed once and
188    /// cached. See [`is_hint_reliant`](crate::tables::glyf::is_hint_reliant).
189    pub fn is_hint_reliant(&self) -> bool {
190        use core::sync::atomic::Ordering;
191        const UNKNOWN: u8 = 0;
192        const KNOWN: u8 = 1;
193        // Only an SFNT font can have TrueType outlines.
194        let Some(sfnt) = self.shared().sfnt() else {
195            return false;
196        };
197        let cell = &sfnt.hint_reliant;
198        match cell.load(Ordering::Relaxed) {
199            UNKNOWN => {
200                let answer = crate::tables::glyf::is_hint_reliant(&self.tables());
201                cell.store(KNOWN + answer as u8, Ordering::Relaxed);
202                answer
203            }
204            state => state > KNOWN,
205        }
206    }
207
208    /// Returns the font's names and other localized strings.
209    pub fn names(&self) -> Names<'_> {
210        match self.kind() {
211            Kind::Type1(font) => Names::from_type1(font),
212            Kind::Cff(ref font, _) => Names::from_cff(font),
213            _ => Names::from_sfnt(&self.tables()),
214        }
215    }
216
217    /// Returns the name of a glyph, synthesizing `gidNNN` if none is stored.
218    ///
219    /// Returns `None` for a glyph outside the font.
220    pub fn glyph_name(&self, glyph: GlyphId) -> Option<GlyphName> {
221        name::glyph_name(self, glyph)
222    }
223
224    /// Returns the identifier and name of every glyph in the font.
225    ///
226    /// Names come from `post`, then `CFF`, or from Type 1 charstrings. A
227    /// missing name is synthesized as `gidNNN`.
228    pub fn glyph_names(&self) -> impl Iterator<Item = (GlyphId, GlyphName)> + '_ {
229        name::glyph_names(self)
230    }
231
232    /// Returns the glyph named `name`.
233    ///
234    /// Names come from the same sources as [`glyph_names`](Self::glyph_names),
235    /// but a synthesized `gidNNN` name matches nothing. Where several glyphs
236    /// share a name, the first is returned.
237    ///
238    /// The first call sorts the font's names, and later calls search them.
239    pub fn glyph_by_name(&self, name: &str) -> Option<GlyphId> {
240        self.shared()
241            .0
242            .glyph_name_index
243            .get_or_init(|| name::GlyphNameIndex::new(self))
244            .get(name)
245    }
246
247    /// Returns `true` if the font is a CID-keyed Type 1 or standalone CFF font, whose
248    /// glyphs are identified by CID.
249    ///
250    /// A `CFF` table in an SFNT font may be CID-keyed too, but its glyphs
251    /// are identified by glyph index, as in any SFNT font.
252    pub fn is_cid_keyed(&self) -> bool {
253        if let Kind::Type1(font) = self.kind() {
254            return font.is_cid_keyed();
255        }
256        self.shared()
257            .standalone_cff()
258            .is_some_and(|cff| cff.is_cid())
259    }
260
261    /// Returns the largest addressable CID in a CID-keyed font.
262    ///
263    /// Glyphs in a CID-keyed font can be addressed by CID, so one more than
264    /// this value is the number of addressable glyph IDs. Returns `None` if the
265    /// font is not CID-keyed.
266    /// For CID-keyed Type 1, this includes missing slots through `CIDCount - 1`.
267    pub fn max_cid(&self) -> Option<u32> {
268        if let Kind::Type1(font) = self.kind() {
269            return font.max_cid();
270        }
271        Some(self.shared().cid_glyphs()?.len() as u32 - 1)
272    }
273
274    /// Returns the glyph for `cid` in a CID-keyed font.
275    ///
276    /// Where several glyphs have the same CID, the first is returned. Returns
277    /// `None` if the font is not CID-keyed or no glyph has `cid`.
278    ///
279    /// For CFF, the first call builds a table from each CID to its glyph.
280    /// CID-keyed Type 1 fonts use CIDs directly as glyph IDs.
281    pub fn glyph_by_cid(&self, cid: u32) -> Option<GlyphId> {
282        if let Kind::Type1(font) = self.kind() {
283            return font.glyph_by_cid(cid);
284        }
285        let glyph = *self.shared().cid_glyphs()?.get(cid as usize)?;
286        (cid == 0 || glyph != 0).then(|| GlyphId::new(glyph as u32))
287    }
288
289    /// Returns the font's character mappings.
290    pub fn charmap(&self) -> Charmap<'_> {
291        Charmap::new(self)
292    }
293
294    /// Returns the metrics describing the font as a whole, at this
295    /// instance's location.
296    pub fn metrics(&self) -> &Metrics {
297        match &self.0 {
298            // Nothing varies there, so the font already holds the answer.
299            Repr::Default(font) => font.metrics(),
300            // A Type 1 font's metrics come from dictionaries that no
301            // location changes.
302            Repr::Varied(varied) if matches!(varied.kind, VariedKind::Type1(_)) => {
303                varied.font.metrics()
304            }
305            Repr::Varied(varied) => varied.location.metrics.get_or_init(|| {
306                debug_assert!(!varied.coords.as_slice().is_empty());
307                Metrics::from_sfnt(&varied.font.tables(), varied.coords.as_slice())
308            }),
309        }
310    }
311
312    /// Returns the font's style measurements at this instance's location.
313    ///
314    /// This reads `post` when requested; [`metrics`](Self::metrics) does not.
315    pub fn style_metrics(&self) -> &StyleMetrics {
316        match &self.0 {
317            Repr::Default(font) => font.style_metrics(),
318            Repr::Varied(varied) if matches!(varied.kind, VariedKind::Type1(_)) => {
319                varied.font.style_metrics()
320            }
321            Repr::Varied(varied) => varied
322                .location
323                .style_metrics
324                .get_or_init(|| {
325                    Box::new(StyleMetrics::from_sfnt(
326                        &varied.font.tables(),
327                        varied.coords.as_slice(),
328                    ))
329                })
330                .as_ref(),
331        }
332    }
333
334    /// Returns measurements of individual glyphs, at this instance's
335    /// location.
336    #[inline]
337    pub fn glyph_metrics(&self) -> GlyphMetrics<'_> {
338        GlyphMetrics::new(self, self.metrics(), self.normalized_coords())
339    }
340
341    /// Returns the font's outlines, using the source order in
342    /// [`GlyphSourceOrder::DEFAULT`].
343    pub fn outline_glyphs(&self) -> OutlineGlyphs<'_> {
344        OutlineGlyphs::new(self, GlyphSourceOrder::DEFAULT)
345    }
346
347    /// Returns the font's outlines, using the source order in `order`.
348    ///
349    /// The first of `Glyf`, `Cff2`, `Cff` and `Type1` that the font has
350    /// becomes the base source for every glyph. If `Varc` comes before the
351    /// base source, it applies to the glyphs it covers, and their components
352    /// are drawn from the base source. Sources that are not outlines are
353    /// ignored.
354    pub fn outline_glyphs_with(&self, order: GlyphSourceOrder) -> OutlineGlyphs<'_> {
355        OutlineGlyphs::new(self, order)
356    }
357
358    /// Returns the font's bitmaps, from the first of `sbix`, `CBDT` and
359    /// `EBDT` that the font has.
360    pub fn bitmap_strikes(&self) -> BitmapStrikes<'_> {
361        BitmapStrikes::new(self, GlyphSourceOrder::BITMAPS)
362    }
363
364    /// Returns the font's bitmaps, using the source order in `order`.
365    ///
366    /// The bitmaps come from the first of `Sbix`, `Cbdt` and `Ebdt` in
367    /// `order` that the font has. Sources that are not bitmaps are ignored.
368    pub fn bitmap_strikes_with(&self, order: GlyphSourceOrder) -> BitmapStrikes<'_> {
369        BitmapStrikes::new(self, order)
370    }
371
372    /// Returns the font's color glyphs.
373    pub fn color_glyphs(&self) -> ColorGlyphs<'_> {
374        ColorGlyphs::new(self)
375    }
376
377    /// Returns the font's color palettes.
378    pub fn palettes(&self) -> Palettes<'_> {
379        Palettes::new(self)
380    }
381
382    /// Returns the underlying source of font data.
383    #[inline]
384    pub fn source(&self) -> &Source {
385        self.shared().source()
386    }
387
388    /// Returns the underlying kind of the font.
389    #[inline]
390    pub fn kind(&self) -> Kind<'_> {
391        self.shared().kind()
392    }
393
394    /// Returns an object that provides access to individual font tables.
395    ///
396    /// For non-SFNT fonts, this will return an empty set of tables.
397    #[inline]
398    pub fn tables(&self) -> &Tables {
399        self.shared().tables()
400    }
401}
402
403impl Font {
404    /// Returns the slot for data that Skrifa derives from the font at this
405    /// location.
406    ///
407    /// At the default location, the slot belongs to the shared font.
408    /// Elsewhere, it belongs to the instance.
409    pub(super) fn scaling_data(&self) -> &Once<Box<dyn Any + Send + Sync>> {
410        &self.location_caches().scaling_data
411    }
412
413    /// Returns the caches for this instance's location.
414    ///
415    /// At the default location, the caches belong to the shared font.
416    /// Elsewhere, they belong to the instance.
417    fn location_caches(&self) -> &LocationCaches {
418        match &self.0 {
419            Repr::Default(font) => &font.0.default_location,
420            Repr::Varied(varied) => &varied.location,
421        }
422    }
423
424    /// Returns the SFNT caches for this instance's location, or `None` if
425    /// the font is not an SFNT font.
426    fn sfnt_location(&self) -> Option<&SfntLocation> {
427        match &self.0 {
428            Repr::Default(font) => font.sfnt().map(|sfnt| &sfnt.default_location),
429            Repr::Varied(varied) => match &varied.kind {
430                VariedKind::Sfnt(sfnt) => Some(&sfnt.location),
431                VariedKind::Type1(_) => None,
432            },
433        }
434    }
435
436    /// The state every instance of this font shares.
437    pub(super) fn shared(&self) -> &SharedFont {
438        match &self.0 {
439            Repr::Default(font) => font,
440            Repr::Varied(varied) => &varied.font,
441        }
442    }
443
444    /// Returns the axes of a Type 1 multiple master font, or `None` for any
445    /// other font.
446    pub(crate) fn type1_axes(&self) -> Option<&[VariationAxisRecord]> {
447        self.shared().multiple_master()?;
448        Some(self.shared().type1_axes())
449    }
450
451    /// Returns a Type 1 font drawn at this instance's location.
452    pub(crate) fn type1_instance(&self) -> Option<Type1Instance<'_>> {
453        let Kind::Type1(font) = self.shared().kind() else {
454            return None;
455        };
456        Some(match &self.0 {
457            Repr::Varied(varied) => match &varied.kind {
458                VariedKind::Type1(type1) => font.instance(&type1.weights),
459                VariedKind::Sfnt(_) => font.default_instance(),
460            },
461            Repr::Default(_) => font.default_instance(),
462        })
463    }
464
465    /// Returns the horizontal glyph metrics, from `HMTX` or `hmtx`.
466    #[inline]
467    pub(crate) fn h_metric_records(&self) -> &GlyphMetricRecords<'_> {
468        self.shared().h_metric_records()
469    }
470
471    /// Returns the vertical glyph metrics, from `VMTX` or `vmtx`.
472    #[inline]
473    pub(crate) fn v_metric_records(&self) -> &GlyphMetricRecords<'_> {
474        self.shared().v_metric_records()
475    }
476
477    /// Returns the outline tables.
478    #[inline]
479    pub(crate) fn selected_glyf_loca(&self) -> Option<&(Glyf<'_>, Loca<'_>)> {
480        self.shared().selected_glyf_loca()
481    }
482
483    /// Returns `HVAR`.
484    #[inline]
485    pub(crate) fn hvar(&self) -> Option<&Hvar<'_>> {
486        self.shared().hvar()
487    }
488
489    /// Returns `VVAR`.
490    #[inline]
491    pub(crate) fn vvar(&self) -> Option<&Vvar<'_>> {
492        self.shared().vvar()
493    }
494
495    /// Returns `GVAR`, or `gvar` without it.
496    #[inline]
497    pub(crate) fn selected_gvar(&self) -> Option<&SelectedGvar<'_>> {
498        self.shared().selected_gvar()
499    }
500
501    /// Returns the `gvar` shared tuple scalars at this location, computed
502    /// once.
503    pub(crate) fn gvar_scalars(&self) -> &[Fixed] {
504        self.location_scalars(
505            |sfnt| &sfnt.gvar_scalars,
506            |varied| match varied.font.selected_gvar() {
507                Some(gvar) => scalars_with(gvar.shared_tuple_count() as usize, |out| {
508                    gvar.compute_scalars(varied.coords.as_slice(), out)
509                }),
510                None => Box::new([]),
511            },
512        )
513    }
514
515    /// Returns the `HVAR` region scalars at this location, computed once.
516    pub(crate) fn hvar_scalars(&self) -> &[Fixed] {
517        self.location_scalars(
518            |sfnt| &sfnt.hvar_scalars,
519            |varied| {
520                let store = varied
521                    .font
522                    .hvar()
523                    .and_then(|hvar| hvar.item_variation_store().ok());
524                store_scalars(store.as_ref(), varied.coords.as_slice())
525            },
526        )
527    }
528
529    /// Returns the `VVAR` region scalars at this location, computed once.
530    pub(crate) fn vvar_scalars(&self) -> &[Fixed] {
531        self.location_scalars(
532            |sfnt| &sfnt.vvar_scalars,
533            |varied| {
534                let store = varied
535                    .font
536                    .vvar()
537                    .and_then(|vvar| vvar.item_variation_store().ok());
538                store_scalars(store.as_ref(), varied.coords.as_slice())
539            },
540        )
541    }
542
543    /// Returns the `COLR` region scalars at this location, computed once.
544    pub(crate) fn colr_scalars(&self) -> &[Fixed] {
545        self.location_scalars(
546            |sfnt| &sfnt.colr_scalars,
547            |varied| {
548                let store = varied
549                    .font
550                    .colr_tables()
551                    .and_then(|tables| tables.var_store.as_ref());
552                store_scalars(store, varied.coords.as_slice())
553            },
554        )
555    }
556
557    /// Returns the scalars `cache` selects for this location, filling it
558    /// with `compute` the first time. The default location needs none.
559    fn location_scalars(
560        &self,
561        cache: fn(&VariedSfnt) -> &Once<Box<[Fixed]>>,
562        compute: impl FnOnce(&VariedInstance) -> Box<[Fixed]>,
563    ) -> &[Fixed] {
564        match &self.0 {
565            Repr::Default(_) => &[],
566            Repr::Varied(varied) => match &varied.kind {
567                VariedKind::Sfnt(sfnt) => cache(sfnt).get_or_init(|| compute(varied)),
568                VariedKind::Type1(_) => &[],
569            },
570        }
571    }
572
573    /// Returns the `CFF` charstring outlines from SFNT tables.
574    #[inline]
575    pub(crate) fn cff(&self) -> Option<&CffFontRef<'_>> {
576        self.shared().cff()
577    }
578
579    /// Returns the charstrings for `source`.
580    ///
581    /// For an SFNT font, these come from the `CFF2` or `CFF` table. A
582    /// standalone CFF font provides its own charstrings as `CFF`.
583    pub(crate) fn charstrings(&self, source: OutlineSource) -> Option<&CffFontRef<'_>> {
584        let shared = self.shared();
585        match source {
586            OutlineSource::Cff2 => shared.cff2(),
587            OutlineSource::Cff => shared.cff().or_else(|| shared.standalone_cff()),
588            _ => None,
589        }
590    }
591
592    /// Returns subfont `index` of the charstrings for `source`, parsed at
593    /// this instance's location.
594    ///
595    /// The first [`CACHED_SUBFONTS`] subfonts are parsed once and kept,
596    /// since nearly every glyph in a font shares one of them. A standalone
597    /// CFF font parses them when the font is read. An SFNT font parses each
598    /// once per location, when a glyph first needs it. A subfont past them
599    /// is parsed each time it is asked for, so a font with thousands of
600    /// subfonts costs no more memory than one with eight.
601    pub(crate) fn cff_subfont(&self, source: OutlineSource, index: u16) -> Option<Subfont> {
602        let cff = self.charstrings(source)?;
603        if let Some(subfonts) = self.shared().standalone_cff_subfonts() {
604            return match subfonts.get(usize::from(index)) {
605                Some(subfont) => *subfont,
606                None => cff.subfont(index, &[]).ok(),
607            };
608        }
609        let location = self.sfnt_location()?;
610        let cache = match source {
611            OutlineSource::Cff2 => &location.cff2_subfonts,
612            _ => &location.cff_subfonts,
613        };
614        let coords = self.normalized_coords();
615        let subfonts = cache.get_or_init(|| {
616            let count = (cff.num_subfonts() as usize).min(CACHED_SUBFONTS);
617            (0..count).map(|_| Once::new()).collect()
618        });
619        match subfonts.get(usize::from(index)) {
620            Some(subfont) => *subfont.get_or_init(|| cff.subfont(index, coords).ok()),
621            None => cff.subfont(index, coords).ok(),
622        }
623    }
624
625    /// Returns `true` if the font has glyphs from `source`, one of the
626    /// bitmap tables, `COLR` or `VARC`.
627    ///
628    /// Each source is probed the first time it is asked about and the answer
629    /// kept, so asking loads no table that measuring with it would not.
630    pub(crate) fn has_layered_source(&self, source: GlyphSource) -> bool {
631        use core::sync::atomic::Ordering;
632        let Some(sfnt) = self.shared().sfnt() else {
633            return false;
634        };
635        let shift = 2 * (source as u32 - 1);
636        match (sfnt.glyph_sources.load(Ordering::Relaxed) >> shift) & 3 {
637            SOURCE_ABSENT => return false,
638            SOURCE_PRESENT => return true,
639            _ => {}
640        }
641        let present = match source {
642            GlyphSource::Sbix | GlyphSource::Cbdt | GlyphSource::Ebdt => !self
643                .bitmap_strikes_with(GlyphSourceOrder::new(&[source]))
644                .is_empty(),
645            GlyphSource::Colr => !self.color_glyphs().is_empty(),
646            GlyphSource::Varc => self.varc_outlines().is_some(),
647            _ => return false,
648        };
649        let state = if present {
650            SOURCE_PRESENT
651        } else {
652            SOURCE_ABSENT
653        };
654        sfnt.glyph_sources
655            .fetch_or(state << shift, Ordering::Relaxed);
656        present
657    }
658
659    /// Returns `true` if the font has glyphs from any bitmap table, `COLR`
660    /// or `VARC` that `order` lists.
661    ///
662    /// Reads the cached results once and probes only the sources not yet
663    /// checked.
664    pub(crate) fn has_layered_source_in(&self, order: GlyphSourceOrder) -> bool {
665        let Some(sfnt) = self.shared().sfnt() else {
666            return false;
667        };
668        let known = sfnt
669            .glyph_sources
670            .load(core::sync::atomic::Ordering::Relaxed);
671        order.iter().any(|source| {
672            if !matches!(
673                source,
674                GlyphSource::Sbix
675                    | GlyphSource::Cbdt
676                    | GlyphSource::Ebdt
677                    | GlyphSource::Colr
678                    | GlyphSource::Varc
679            ) {
680                return false;
681            }
682            match (known >> (2 * (source as u32 - 1))) & 3 {
683                SOURCE_ABSENT => false,
684                SOURCE_PRESENT => true,
685                _ => self.has_layered_source(source),
686            }
687        })
688    }
689
690    /// Returns the probed state of the bitmap, color and composite sources.
691    #[cfg(test)]
692    pub(crate) fn probed_glyph_sources(&self) -> u32 {
693        self.shared().sfnt().map_or(0, |sfnt| {
694            sfnt.glyph_sources
695                .load(core::sync::atomic::Ordering::Relaxed)
696        })
697    }
698
699    /// Returns the variable composites, read once for the font.
700    #[inline]
701    pub(crate) fn varc_outlines(&self) -> Option<&varc::Outlines<'_>> {
702        self.shared().varc_outlines()
703    }
704
705    /// Returns `COLR` with its variation tables, read once for the font.
706    #[inline]
707    pub(crate) fn colr_tables(&self) -> Option<&ColrTables<'_>> {
708        self.shared().colr_tables()
709    }
710
711    /// Returns `CPAL`, read once for the font.
712    #[inline]
713    pub(crate) fn cpal(&self) -> Option<&Cpal<'_>> {
714        self.shared().cpal()
715    }
716
717    /// Returns `sbix`, read once for the font.
718    #[inline]
719    pub(crate) fn sbix(&self) -> Option<&Sbix<'_>> {
720        self.shared().sbix()
721    }
722
723    /// Returns `CBLC` and `CBDT`, read once for the font.
724    #[inline]
725    pub(crate) fn cbdt(&self) -> Option<&(Cblc<'_>, Cbdt<'_>)> {
726        self.shared().cbdt()
727    }
728
729    /// Returns `EBLC` and `EBDT`, read once for the font.
730    #[inline]
731    pub(crate) fn ebdt(&self) -> Option<&(Eblc<'_>, Ebdt<'_>)> {
732        self.shared().ebdt()
733    }
734
735    /// Returns `VORG`.
736    #[inline]
737    pub(crate) fn vorg(&self) -> Option<&Vorg<'_>> {
738        self.shared().vorg()
739    }
740}
741
742impl<'a> OutlineContext<'a> for &'a Font {
743    fn glyph(&self, glyph: GlyphId) -> Option<LocaGlyph<'a>> {
744        let (glyf, loca) = self.selected_glyf_loca()?;
745        loca.get(glyph, glyf)
746    }
747
748    fn glyph_variation_data(&self, glyph: GlyphId) -> Option<GlyphVariationData<'a>> {
749        self.selected_gvar()?.glyph_variation_data(glyph).ok()?
750    }
751
752    fn has_gvar(&self) -> bool {
753        self.selected_gvar().is_some()
754    }
755
756    fn phantom_point_deltas(&self, glyph: GlyphId) -> Option<[Point<Fixed>; PHANTOM_POINT_COUNT]> {
757        let (glyf, loca) = self.selected_glyf_loca()?;
758        self.selected_gvar()?.phantom_point_deltas_with_scalars(
759            glyf,
760            loca,
761            self.normalized_coords(),
762            self.gvar_scalars(),
763            glyph,
764        )
765    }
766
767    fn gvar_scalars(&self) -> &[Fixed] {
768        Font::gvar_scalars(self)
769    }
770
771    fn coords(&self) -> &[F2Dot14] {
772        self.normalized_coords()
773    }
774
775    fn units_per_em(&self) -> u16 {
776        Font::units_per_em(self)
777    }
778
779    fn h_metrics(&self, glyph: GlyphId) -> (i32, i32) {
780        let metrics = self.h_metric_records();
781        (
782            metrics
783                .stated_side_bearing(glyph)
784                .unwrap_or_default()
785                .to_i32(),
786            metrics.stated_advance(self.num_glyphs(), glyph).to_i32(),
787        )
788    }
789
790    fn v_metrics(&self, glyph: GlyphId) -> Option<(i32, i32)> {
791        let metrics = self.v_metric_records();
792        if metrics.is_empty() {
793            return None;
794        }
795        Some((
796            metrics
797                .stated_side_bearing(glyph)
798                .unwrap_or_default()
799                .to_i32(),
800            metrics.stated_advance(self.num_glyphs(), glyph).to_i32(),
801        ))
802    }
803
804    fn h_line_metrics(&self) -> (i32, i32) {
805        self.shared().metrics().h_line().map_or((0, 0), |line| {
806            (line.ascender.to_i32(), line.descender.to_i32())
807        })
808    }
809
810    fn has_hvar(&self) -> bool {
811        self.hvar().is_some()
812    }
813}
814
815/// The underlying type of a font.
816#[derive(Clone)]
817pub enum Kind<'a> {
818    /// An SFNT-based font represented by a set of tables and an index.
819    Sfnt(&'a Tables, u32),
820    /// An Adobe Type 1 font.
821    Type1(&'a Type1Font),
822    /// A standalone CFF font with an associated index.
823    Cff(CffFontRef<'a>, u32),
824}
825
826/// Builder for configuring a font instance.
827pub struct InstanceBuilder {
828    font: SharedFont,
829    coords: CoordStorage,
830    /// The blend coordinates of a Type 1 multiple master location, which
831    /// `coords` holds rounded to 2.14. The weights are computed from these.
832    type1_blend: SmallVec<[Fixed; 4]>,
833}
834
835impl InstanceBuilder {
836    /// Sets the variations for the font instance from an unordered sequence of
837    /// variations in user space.
838    ///
839    /// Omitted axes will be set to their default values. Unsupported axes are
840    /// ignored. If an axis is specified multiple times, the last value is used.
841    ///
842    /// This will overwrite any previous variation settings.
843    pub fn variations<V>(mut self, variations: V) -> Self
844    where
845        V: IntoIterator,
846        V::Item: Into<Variation>,
847    {
848        self.set_variations(variations);
849        self
850    }
851
852    /// Sets the variations for the font instance from an ordered sequence
853    /// of normalized coordinates.
854    ///
855    /// If the number of provided coordinates is less than the number of axes,
856    /// the remaining axes will be set to their default values. If the number
857    /// of provided coordinates is greater than the number of axes, the extra
858    /// coordinates will be ignored.
859    ///
860    /// This will overwrite any previous variation settings.
861    pub fn normalized_coords(mut self, coords: impl IntoIterator<Item = NormalizedCoord>) -> Self {
862        self.set_coords(coords);
863        self
864    }
865
866    /// Sets the variations for the font instance from a named instance.
867    ///
868    /// If the given named instance index is invalid, then variation settings
869    /// will be reset to default.
870    ///
871    /// This will overwrite any previous variation settings.
872    pub fn named_instance(mut self, index: u32) -> Self {
873        self.set_named_instance(index);
874        self
875    }
876
877    /// Sets the variations for the font instance from a named instance, with
878    /// additional overrides.
879    ///
880    /// If the given named instance index is invalid, then it is ignored and
881    /// only overrides are applied.
882    ///
883    /// This will overwrite any previous variation settings.
884    pub fn named_instance_with_overrides<V>(mut self, index: u32, overrides: V) -> Self
885    where
886        V: IntoIterator,
887        V::Item: Into<Variation>,
888    {
889        self.set_named_instance_with_overrides(index, overrides);
890        self
891    }
892
893    /// Builds the font instance.
894    pub fn build(self) -> Font {
895        // An all-default location is just the font, so nothing needs owning.
896        // This is what keeps `VariedInstance::coords` non-empty.
897        if self.coords.as_slice().is_empty() {
898            return Font(Repr::Default(self.font));
899        }
900        let kind = match &self.font.0.kind {
901            KindRepr::Sfnt(_) => VariedKind::Sfnt(VariedSfnt {
902                location: SfntLocation::new(),
903                gvar_scalars: Once::new(),
904                hvar_scalars: Once::new(),
905                colr_scalars: Once::new(),
906                vvar_scalars: Once::new(),
907            }),
908            KindRepr::Type1(type1) => {
909                let Some(mm) = type1.font.multiple_master() else {
910                    return Font(Repr::Default(self.font));
911                };
912                let mut weights = SmallVec::from_elem(Fixed::ZERO, mm.num_masters());
913                mm.blend_to_weights(&self.type1_blend, &mut weights);
914                VariedKind::Type1(VariedType1 { weights })
915            }
916            // A standalone CFF font has no axes, so no coordinates reach
917            // here; it is at its default location.
918            KindRepr::StandaloneCff(_) => return Font(Repr::Default(self.font)),
919        };
920        Font(Repr::Varied(Arc::new(VariedInstance {
921            font: self.font,
922            coords: self.coords,
923            location: LocationCaches::new(),
924            kind,
925        })))
926    }
927}
928
929impl InstanceBuilder {
930    fn set_variations<V>(&mut self, variations: V)
931    where
932        V: IntoIterator,
933        V::Item: Into<Variation>,
934    {
935        if let Some(mm) = self.font.multiple_master() {
936            // Design coordinates, starting from each axis's default.
937            let axes = self.font.type1_axes();
938            let mut design: SmallVec<[Fixed; 4]> =
939                axes.iter().map(|axis| axis.default_value()).collect();
940            let mut named: SmallVec<[bool; 4]> = SmallVec::from_elem(false, design.len());
941            for variation in variations {
942                let variation = variation.into();
943                for ((axis, value), named) in axes.iter().zip(design.iter_mut()).zip(&mut named) {
944                    if axis.axis_tag() == variation.tag {
945                        *value = Fixed::from_f64(variation.value as f64);
946                        *named = true;
947                    }
948                }
949            }
950            let mut blend = SmallVec::from_elem(Fixed::ZERO, design.len());
951            mm.design_to_blend(&design, &mut blend);
952            // An axis no variation names keeps the default blend. Its
953            // default design coordinate doesn't always map back to it.
954            let mut default = SmallVec::<[Fixed; 4]>::from_elem(Fixed::ZERO, design.len());
955            mm.default_blend(&mut default);
956            for ((value, default), named) in blend.iter_mut().zip(default).zip(named) {
957                if !named {
958                    *value = default;
959                }
960            }
961            self.set_type1_blend(blend);
962            return;
963        }
964        let tables = self.font.tables();
965        if let Ok(fvar) = tables.fvar() {
966            set_variations(&fvar, tables.avar().ok(), &mut self.coords, variations);
967        } else {
968            self.coords.clear();
969        }
970    }
971
972    fn set_coords(&mut self, coords: impl IntoIterator<Item = NormalizedCoord>) {
973        if let Some(mm) = self.font.multiple_master() {
974            // Blend coordinates, with the default blend for any not given.
975            let mut blend: SmallVec<[Fixed; 4]> = SmallVec::from_elem(Fixed::ZERO, mm.axes().len());
976            mm.default_blend(&mut blend);
977            for (dst, src) in blend.iter_mut().zip(coords) {
978                *dst = src.to_fixed();
979            }
980            self.set_type1_blend(blend);
981            return;
982        }
983        if let Ok(fvar) = self.font.tables().fvar() {
984            let count = fvar.axis_count() as usize;
985            self.coords.resize(count, NormalizedCoord::ZERO);
986            for (dst, src) in self.coords.as_mut_slice().iter_mut().zip(
987                coords
988                    .into_iter()
989                    .chain(core::iter::repeat(NormalizedCoord::ZERO)),
990            ) {
991                *dst = src;
992            }
993            clear_if_all_zeroes(&mut self.coords);
994        } else {
995            self.coords.clear();
996        }
997    }
998
999    /// Sets the location of a Type 1 multiple master font.
1000    ///
1001    /// Every blend is kept, even all zeros, which is a master rather than
1002    /// the font's default.
1003    ///
1004    /// The weights are computed from `blend` itself. The coordinates are
1005    /// those the weights give back, which rounding in the weights can move
1006    /// from `blend` by the smallest step, as FreeType reports them.
1007    fn set_type1_blend(&mut self, blend: SmallVec<[Fixed; 4]>) {
1008        let font = self.font.clone();
1009        let Some(mm) = font.multiple_master() else {
1010            return;
1011        };
1012        let mut weights: SmallVec<[Fixed; 16]> = SmallVec::from_elem(Fixed::ZERO, mm.num_masters());
1013        mm.blend_to_weights(&blend, &mut weights);
1014        let mut reported: SmallVec<[Fixed; 4]> = SmallVec::from_elem(Fixed::ZERO, blend.len());
1015        mm.weights_to_blend(&weights, &mut reported);
1016        self.coords = reported.iter().map(|value| value.to_f2dot14()).collect();
1017        self.type1_blend = blend;
1018    }
1019
1020    fn set_named_instance(&mut self, index: u32) {
1021        let tables = self.font.tables();
1022        if let Ok(fvar) = tables.fvar() {
1023            set_variations(
1024                &fvar,
1025                tables.avar().ok(),
1026                &mut self.coords,
1027                named_instance_variations(&fvar, index),
1028            );
1029        } else {
1030            self.coords.clear();
1031        }
1032    }
1033
1034    fn set_named_instance_with_overrides<V>(&mut self, index: u32, overrides: V)
1035    where
1036        V: IntoIterator,
1037        V::Item: Into<Variation>,
1038    {
1039        // A Type 1 multiple master font has no named instances, so only the
1040        // overrides apply.
1041        if self.font.multiple_master().is_some() {
1042            self.set_variations(overrides);
1043            return;
1044        }
1045        let tables = self.font.tables();
1046        if let Ok(fvar) = tables.fvar() {
1047            set_variations(
1048                &fvar,
1049                tables.avar().ok(),
1050                &mut self.coords,
1051                named_instance_variations(&fvar, index)
1052                    .chain(overrides.into_iter().map(Into::into)),
1053            );
1054        } else {
1055            self.coords.clear();
1056        }
1057    }
1058}
1059
1060// Helper to extract an iterator of Variation from a named instance index.
1061fn named_instance_variations<'a>(
1062    fvar: &'a Fvar,
1063    index: u32,
1064) -> impl Iterator<Item = Variation> + 'a {
1065    fvar.axis_instance_arrays()
1066        .ok()
1067        .and_then(|arrays| {
1068            let axes = arrays.axes();
1069            arrays.instances().get(index as usize).ok().map(|instance| {
1070                axes.iter()
1071                    .zip(instance.coordinates)
1072                    .map(|(axis, coord)| Variation::new(axis.axis_tag(), coord.get().to_f32()))
1073            })
1074        })
1075        .into_iter()
1076        .flatten()
1077}
1078
1079/// Helper for setting variations.
1080///
1081/// Pulled out into a separate function to avoid borrow checker issues.
1082fn set_variations<V>(fvar: &Fvar, avar: Option<Avar>, coords: &mut CoordStorage, variations: V)
1083where
1084    V: IntoIterator,
1085    V::Item: Into<Variation>,
1086{
1087    coords.resize(fvar.axis_count() as usize, NormalizedCoord::ZERO);
1088    fvar.user_to_normalized(
1089        avar.as_ref(),
1090        variations
1091            .into_iter()
1092            .map(Into::into)
1093            .map(|var| (var.tag, Fixed::from_f64(var.value as _))),
1094        coords.as_mut_slice(),
1095    );
1096    clear_if_all_zeroes(coords);
1097}
1098
1099/// The state every instance of a font shares.
1100///
1101/// Reference counted internally: cloning it costs no more than the count,
1102/// and it is thread safe.
1103#[derive(Clone)]
1104pub(super) struct SharedFont(Arc<SharedFontRepr>);
1105
1106impl SharedFont {
1107    /// Creates a new font from the given source and font index.
1108    ///
1109    /// See [`Font::new`] for how `index` is used.
1110    fn new(source: impl Into<Source>, index: u32) -> Option<Self> {
1111        let source = source.into();
1112        let kind = if let Some(tables) = Tables::new(source.clone(), index) {
1113            Some(KindRepr::Sfnt(SfntCaches::new(Arc::new(tables), index)))
1114        } else if let Source::Blob(blob) = &source {
1115            match Format::new(blob) {
1116                Some(Format::Type1) => Type1Font::new(blob).ok().map(|font| {
1117                    let axes = font
1118                        .multiple_master()
1119                        .map(super::variation::type1_axis_records)
1120                        .unwrap_or_default();
1121                    KindRepr::Type1(Type1Data { font, axes })
1122                }),
1123                Some(Format::Cff(count)) if index < count => {
1124                    let font = Yoke::<CffFontRef<'static>, Arc<Blob>>::try_attach_to_cart(
1125                        Arc::new(blob.clone()),
1126                        |blob| CffFontRef::new_cff(blob, index, None),
1127                    )
1128                    .ok()?;
1129                    // A subfont that cannot be read fails only its own
1130                    // glyphs, not the font.
1131                    let count = font.get().num_subfonts().min(CACHED_SUBFONTS as _);
1132                    let subfonts = (0..count)
1133                        .map(|index| font.get().subfont(index, &[]).ok())
1134                        .collect();
1135                    Some(KindRepr::StandaloneCff(StandaloneCffData {
1136                        font,
1137                        subfonts,
1138                        index,
1139                        unicode_charmap: Once::new(),
1140                        cid_glyphs: Once::new(),
1141                    }))
1142                }
1143                _ => None,
1144            }
1145        } else {
1146            None
1147        };
1148        let kind = kind?;
1149        let repr = SharedFontRepr {
1150            source,
1151            kind,
1152            shaping_data: Once::new(),
1153            glyph_name_index: Once::new(),
1154            default_location: LocationCaches::new(),
1155        };
1156        Some(Self(Arc::new(repr)))
1157    }
1158
1159    /// Returns the underlying source of font data.
1160    fn source(&self) -> &Source {
1161        &self.0.source
1162    }
1163
1164    /// Returns the underlying kind of the font.
1165    pub(super) fn kind(&self) -> Kind<'_> {
1166        match &self.0.kind {
1167            KindRepr::Sfnt(sfnt) => Kind::Sfnt(&sfnt.tables, sfnt.index),
1168            KindRepr::Type1(type1) => Kind::Type1(&type1.font),
1169            KindRepr::StandaloneCff(cff) => Kind::Cff(cff.font.get().clone(), cff.index),
1170        }
1171    }
1172
1173    /// Returns the design space of a Type 1 multiple master font.
1174    fn multiple_master(&self) -> Option<&MultipleMaster> {
1175        match &self.0.kind {
1176            KindRepr::Type1(type1) => type1.font.multiple_master(),
1177            _ => None,
1178        }
1179    }
1180
1181    /// Returns the axes of a Type 1 multiple master font, which is empty
1182    /// for any other font.
1183    fn type1_axes(&self) -> &[VariationAxisRecord] {
1184        match &self.0.kind {
1185            KindRepr::Type1(type1) => &type1.axes,
1186            _ => &[],
1187        }
1188    }
1189
1190    /// Returns the metrics describing the font as a whole, at its default
1191    /// location.
1192    #[inline]
1193    fn metrics(&self) -> &Metrics {
1194        self.0
1195            .default_location
1196            .metrics
1197            .get_or_init(|| match self.kind() {
1198                Kind::Type1(font) => Metrics::from_type1(font),
1199                Kind::Cff(font, _) => Metrics::from_cff(&font),
1200                _ => Metrics::from_sfnt(&self.tables(), &[]),
1201            })
1202    }
1203
1204    /// Returns the style measurements at the font's default location.
1205    fn style_metrics(&self) -> &StyleMetrics {
1206        self.0
1207            .default_location
1208            .style_metrics
1209            .get_or_init(|| {
1210                Box::new(match self.kind() {
1211                    Kind::Type1(font) => StyleMetrics::from_type1(font),
1212                    Kind::Cff(font, _) => StyleMetrics::from_cff(&font),
1213                    _ => StyleMetrics::from_sfnt(&self.tables(), &[]),
1214                })
1215            })
1216            .as_ref()
1217    }
1218
1219    /// Returns the number of glyphs in the font.
1220    ///
1221    /// Fixed for the font: no location varies it.
1222    #[inline]
1223    pub(super) fn num_glyphs(&self) -> u32 {
1224        self.metrics().num_glyphs
1225    }
1226
1227    /// Returns the size of the em square, in font units.
1228    ///
1229    /// Fixed for the font: no location varies it.
1230    #[inline]
1231    fn units_per_em(&self) -> u16 {
1232        self.metrics().units_per_em
1233    }
1234
1235    /// Returns the caches of an SFNT font, or `None` for a font of another
1236    /// kind.
1237    #[inline]
1238    pub(super) fn sfnt(&self) -> Option<&SfntCaches> {
1239        match &self.0.kind {
1240            KindRepr::Sfnt(sfnt) => Some(sfnt),
1241            _ => None,
1242        }
1243    }
1244
1245    /// Returns the tables behind this font, for a cache that holds them.
1246    fn tables_arc(&self) -> Option<&Arc<Tables>> {
1247        self.sfnt().map(|sfnt| &sfnt.tables)
1248    }
1249
1250    /// Returns the selected character maps, parsed once for the font.
1251    pub(super) fn unicode_charmap(&self) -> Option<&SfntUnicodeCharmap<'_>> {
1252        let sfnt = self.sfnt()?;
1253        Some(
1254            sfnt.charmap
1255                .get_or_init(|| {
1256                    TableCache::read(sfnt.tables.clone(), |tables| {
1257                        SfntUnicodeCharmap::read(&tables)
1258                    })
1259                })
1260                .get(),
1261        )
1262    }
1263
1264    /// Returns all selectable cmap subtables, parsed on first use.
1265    pub(super) fn encodings(&self) -> Option<&EncodingTables<'_>> {
1266        let sfnt = self.sfnt()?;
1267        Some(
1268            sfnt.encodings
1269                .get_or_init(|| {
1270                    Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1271                        EncodingTables::read(&tables)
1272                    }))
1273                })
1274                .get(),
1275        )
1276    }
1277
1278    pub(super) fn standalone_cff_unicode_charmap(&self) -> Option<&crate::ps::UnicodeCharmap> {
1279        let KindRepr::StandaloneCff(cff) = &self.0.kind else {
1280            return None;
1281        };
1282        Some(cff.unicode_charmap.get_or_init(|| {
1283            #[cfg(feature = "agl")]
1284            {
1285                let cff = cff.font.get();
1286                if cff.is_cid() {
1287                    return crate::ps::UnicodeCharmap::default();
1288                }
1289                crate::ps::UnicodeCharmap::from_glyph_names(
1290                    cff.charset()
1291                        .into_iter()
1292                        .flat_map(|charset| charset.iter())
1293                        .filter_map(|(glyph, sid)| {
1294                            let name = core::str::from_utf8(cff.string(sid)?).ok()?;
1295                            Some((glyph, name))
1296                        }),
1297                )
1298            }
1299            #[cfg(not(feature = "agl"))]
1300            {
1301                let _ = cff;
1302                crate::ps::UnicodeCharmap::default()
1303            }
1304        }))
1305    }
1306
1307    /// Returns the horizontal glyph metrics, parsed once for the font.
1308    #[inline]
1309    fn h_metric_records(&self) -> &GlyphMetricRecords<'_> {
1310        let Some(sfnt) = self.sfnt() else {
1311            return empty_glyph_metrics();
1312        };
1313        &sfnt
1314            .h_metrics
1315            .get_or_init(|| {
1316                TableCache::read(sfnt.tables.clone(), |tables| {
1317                    MetricsTable(tables.h_glyph_metric_records().unwrap_or_default())
1318                })
1319            })
1320            .get()
1321            .0
1322    }
1323
1324    /// Returns the vertical glyph metrics, parsed once for the font.
1325    ///
1326    /// Read on demand, unlike the horizontal metrics: most text is
1327    /// horizontal and never asks.
1328    #[inline]
1329    fn v_metric_records(&self) -> &GlyphMetricRecords<'_> {
1330        let Some(sfnt) = self.sfnt() else {
1331            return empty_glyph_metrics();
1332        };
1333        &sfnt
1334            .v_metrics
1335            .get_or_init(|| {
1336                TableCache::read(sfnt.tables.clone(), |tables| {
1337                    MetricsTable(tables.v_glyph_metric_records().unwrap_or_default())
1338                })
1339            })
1340            .get()
1341            .0
1342    }
1343
1344    /// Returns the outline tables, parsed once for the font.
1345    ///
1346    /// Outlines and metrics in both directions read these, so they are
1347    /// shared rather than parsed by each.
1348    #[inline]
1349    fn selected_glyf_loca(&self) -> Option<&(Glyf<'_>, Loca<'_>)> {
1350        let sfnt = self.sfnt()?;
1351        sfnt.glyf_loca
1352            .get_or_init(|| TableCache::read(sfnt.tables.clone(), |tables| GlyfLoca::read(&tables)))
1353            .get()
1354            .0
1355            .as_ref()
1356    }
1357
1358    /// Returns `HVAR`, parsed once for the font.
1359    #[inline]
1360    fn hvar(&self) -> Option<&Hvar<'_>> {
1361        let sfnt = self.sfnt()?;
1362        sfnt.hvar
1363            .get_or_init(|| {
1364                TableCache::read(sfnt.tables.clone(), |tables| HvarTable::read(&tables))
1365            })
1366            .get()
1367            .0
1368            .as_ref()
1369    }
1370
1371    /// Returns `VVAR`, parsed once for the font.
1372    #[inline]
1373    fn vvar(&self) -> Option<&Vvar<'_>> {
1374        let sfnt = self.sfnt()?;
1375        sfnt.vvar
1376            .get_or_init(|| {
1377                TableCache::read(sfnt.tables.clone(), |tables| VvarTable::read(&tables))
1378            })
1379            .get()
1380            .0
1381            .as_ref()
1382    }
1383
1384    /// Returns `GVAR`, or `gvar` without it, parsed once for the font.
1385    ///
1386    /// Typically about half a variable font, so nothing should ask for this
1387    /// that another table can answer.
1388    #[inline]
1389    fn selected_gvar(&self) -> Option<&SelectedGvar<'_>> {
1390        let sfnt = self.sfnt()?;
1391        sfnt.gvar
1392            .get_or_init(|| {
1393                TableCache::read(sfnt.tables.clone(), |tables| GvarTable::read(&tables))
1394            })
1395            .get()
1396            .0
1397            .as_ref()
1398    }
1399
1400    /// Returns `VORG`, parsed once for the font.
1401    #[inline]
1402    fn vorg(&self) -> Option<&Vorg<'_>> {
1403        let sfnt = self.sfnt()?;
1404        sfnt.vorg
1405            .get_or_init(|| {
1406                TableCache::read(sfnt.tables.clone(), |tables| VorgTable::read(&tables))
1407            })
1408            .get()
1409            .0
1410            .as_ref()
1411    }
1412
1413    /// Returns the `CFF2` charstring outlines, parsed once for the font.
1414    ///
1415    /// Reading one means running it, so nothing here is parsed per glyph
1416    /// beyond what a charstring itself needs.
1417    #[inline]
1418    fn cff2(&self) -> Option<&CffFontRef<'_>> {
1419        let sfnt = self.sfnt()?;
1420        sfnt.cff2
1421            .get_or_init(|| TableCache::read(sfnt.tables.clone(), |tables| Cff2Font::read(&tables)))
1422            .get()
1423            .0
1424            .as_ref()
1425    }
1426
1427    /// Returns the `CFF` charstring outlines, parsed once for the font.
1428    #[inline]
1429    fn cff(&self) -> Option<&CffFontRef<'_>> {
1430        let sfnt = self.sfnt()?;
1431        sfnt.cff
1432            .get_or_init(|| TableCache::read(sfnt.tables.clone(), |tables| CffFont::read(&tables)))
1433            .get()
1434            .0
1435            .as_ref()
1436    }
1437
1438    fn standalone_cff(&self) -> Option<&CffFontRef<'_>> {
1439        match &self.0.kind {
1440            KindRepr::StandaloneCff(cff) => Some(cff.font.get()),
1441            _ => None,
1442        }
1443    }
1444
1445    /// Returns the glyph for each CID of a standalone CID-keyed font, built
1446    /// once.
1447    ///
1448    /// As in FreeType, the table ends at the largest CID and the first glyph
1449    /// with a CID is kept.
1450    fn cid_glyphs(&self) -> Option<&[u16]> {
1451        let KindRepr::StandaloneCff(data) = &self.0.kind else {
1452            return None;
1453        };
1454        let cff = data.font.get();
1455        if !cff.is_cid() {
1456            return None;
1457        }
1458        let glyphs = data.cid_glyphs.get_or_init(|| {
1459            let num_glyphs = cff.num_glyphs();
1460            let Some(charset) = cff.charset() else {
1461                return Box::new([0]);
1462            };
1463            cid_table(|| {
1464                charset
1465                    .iter()
1466                    .filter(move |(glyph, _)| glyph.to_u32() < num_glyphs)
1467                    .map(|(glyph, cid)| (glyph.to_u32() as u16, cid.to_u16() as usize))
1468            })
1469        });
1470        Some(glyphs)
1471    }
1472
1473    fn standalone_cff_subfonts(&self) -> Option<&[Option<Subfont>]> {
1474        match &self.0.kind {
1475            KindRepr::StandaloneCff(cff) => Some(&cff.subfonts),
1476            _ => None,
1477        }
1478    }
1479
1480    /// Returns the variable composites, read once for the font.
1481    fn varc_outlines(&self) -> Option<&varc::Outlines<'_>> {
1482        let sfnt = self.sfnt()?;
1483        sfnt.varc
1484            .get_or_init(|| {
1485                Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1486                    varc::Outlines::read(&tables)
1487                }))
1488            })
1489            .get()
1490            .as_ref()
1491    }
1492
1493    /// Returns `COLR` with its variation tables, read once for the font.
1494    fn colr_tables(&self) -> Option<&ColrTables<'_>> {
1495        let sfnt = self.sfnt()?;
1496        sfnt.colr
1497            .get_or_init(|| {
1498                Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1499                    ColrTables::read(&tables)
1500                }))
1501            })
1502            .get()
1503            .as_ref()
1504    }
1505
1506    /// Returns `CPAL`, read once for the font.
1507    fn cpal(&self) -> Option<&Cpal<'_>> {
1508        let sfnt = self.sfnt()?;
1509        sfnt.cpal
1510            .get_or_init(|| {
1511                Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1512                    CpalTable::read(&tables)
1513                }))
1514            })
1515            .get()
1516            .0
1517            .as_ref()
1518    }
1519
1520    /// Returns `sbix`, read once for the font.
1521    fn sbix(&self) -> Option<&Sbix<'_>> {
1522        let sfnt = self.sfnt()?;
1523        sfnt.sbix
1524            .get_or_init(|| {
1525                Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1526                    SbixTable::read(&tables)
1527                }))
1528            })
1529            .get()
1530            .0
1531            .as_ref()
1532    }
1533
1534    /// Returns `CBLC` and `CBDT`, read once for the font.
1535    fn cbdt(&self) -> Option<&(Cblc<'_>, Cbdt<'_>)> {
1536        let sfnt = self.sfnt()?;
1537        sfnt.cbdt
1538            .get_or_init(|| {
1539                Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1540                    CbdtTables::read(&tables)
1541                }))
1542            })
1543            .get()
1544            .0
1545            .as_ref()
1546    }
1547
1548    /// Returns `EBLC` and `EBDT`, read once for the font.
1549    fn ebdt(&self) -> Option<&(Eblc<'_>, Ebdt<'_>)> {
1550        let sfnt = self.sfnt()?;
1551        sfnt.ebdt
1552            .get_or_init(|| {
1553                Box::new(TableCache::read(sfnt.tables.clone(), |tables| {
1554                    EbdtTables::read(&tables)
1555                }))
1556            })
1557            .get()
1558            .0
1559            .as_ref()
1560    }
1561
1562    /// Returns an object that provides access to individual font tables.
1563    ///
1564    /// For non-SFNT fonts, this will return an empty set of tables.
1565    fn tables(&self) -> &Tables {
1566        if let KindRepr::Sfnt(sfnt) = &self.0.kind {
1567            &sfnt.tables
1568        } else {
1569            &tables::EMPTY_FONT_TABLES
1570        }
1571    }
1572}
1573
1574/// Builds the table from each CID to its glyph, keeping the first glyph for
1575/// a CID.
1576///
1577/// `cids` yields each glyph and its CID, glyph zero first with CID zero.
1578fn cid_table<I: Iterator<Item = (u16, usize)>>(cids: impl Fn() -> I) -> Box<[u16]> {
1579    let max_cid = cids().map(|(_, cid)| cid).max().unwrap_or(0);
1580    let mut glyphs = alloc::vec![0u16; max_cid + 1];
1581    // Zero marks an empty slot. Glyph zero has CID zero, so that slot is
1582    // already right and no later glyph takes it.
1583    for (glyph, cid) in cids() {
1584        if cid != 0 && glyphs[cid] == 0 {
1585            glyphs[cid] = glyph;
1586        }
1587    }
1588    glyphs.into_boxed_slice()
1589}
1590
1591struct SharedFontRepr {
1592    source: Source,
1593    kind: KindRepr,
1594    // Storage cell for lazily loaded HarfRust shaping data.
1595    shaping_data: Once<Box<dyn Any + Send + Sync>>,
1596    // The glyph names sorted for lookup by name.
1597    glyph_name_index: Once<name::GlyphNameIndex>,
1598    // The caches of the default location, shared by every default instance.
1599    // A varied instance keeps its own.
1600    default_location: LocationCaches,
1601}
1602
1603/// The underlying type of a font.
1604///
1605/// Every variant is stored inline. The SFNT caches are the largest variant,
1606/// so the other variants add no size. Inlining also avoids a pointer
1607/// indirection in the metric lookups for every advance.
1608#[allow(
1609    clippy::large_enum_variant,
1610    reason = "boxing the SFNT caches would put a pointer chase on every advance, to save space only in the rare fonts of the other kinds"
1611)]
1612enum KindRepr {
1613    Sfnt(SfntCaches),
1614    Type1(Type1Data),
1615    StandaloneCff(StandaloneCffData),
1616}
1617
1618/// A Type 1 font and the axes of its design space, if it has one.
1619struct Type1Data {
1620    font: Type1Font,
1621    axes: Box<[VariationAxisRecord]>,
1622}
1623
1624/// Caches for an SFNT font, with each table parsed once per font.
1625pub(super) struct SfntCaches {
1626    tables: Arc<Tables>,
1627    index: u32,
1628    // Whether the font needs its instructions for correct contours: zero
1629    // until asked, then one more than the answer.
1630    hint_reliant: core::sync::atomic::AtomicU8,
1631    // Which of the bitmap, color and composite sources the font has: two
1632    // bits per source, zero until asked, then absent or present. They are
1633    // probed one at a time, as something asks for each.
1634    glyph_sources: core::sync::atomic::AtomicU32,
1635    // The default location's own SFNT caches. A varied instance keeps its
1636    // own.
1637    default_location: SfntLocation,
1638    // The horizontal glyph metrics, parsed once for the font. Held beside
1639    // the tables they borrow, which is what lets them live here at all.
1640    h_metrics: Once<TableCache<MetricsTable<'static>>>,
1641    // The vertical glyph metrics, read only when something measures
1642    // vertically.
1643    v_metrics: Once<TableCache<MetricsTable<'static>>>,
1644    // The outlines, and the tables that vary metrics: `HVAR` and `VVAR` hold
1645    // metric deltas, and `gvar` holds outline deltas, with metric deltas in
1646    // its phantom points. None depends on a location to parse, so every
1647    // instance shares them. Each is read when something first needs it.
1648    glyf_loca: Once<TableCache<GlyfLoca<'static>>>,
1649    hvar: Once<TableCache<HvarTable<'static>>>,
1650    vvar: Once<TableCache<VvarTable<'static>>>,
1651    gvar: Once<TableCache<GvarTable<'static>>>,
1652    // The charstrings of a `CFF2` or `CFF` font, which neither metrics nor
1653    // outlines read unless the font states them this way. Each table has a
1654    // cell of its own, so an order can prefer either of a font with both.
1655    cff2: Once<TableCache<Cff2Font<'static>>>,
1656    cff: Once<TableCache<CffFont<'static>>>,
1657    // Tables that draw glyphs in other ways, read only when something asks
1658    // for that way. Boxed, so a font without them pays a pointer each.
1659    varc: Once<Box<TableCache<Option<varc::Outlines<'static>>>>>,
1660    colr: Once<Box<TableCache<Option<ColrTables<'static>>>>>,
1661    cpal: Once<Box<TableCache<CpalTable<'static>>>>,
1662    sbix: Once<Box<TableCache<SbixTable<'static>>>>,
1663    cbdt: Once<Box<TableCache<CbdtTables<'static>>>>,
1664    ebdt: Once<Box<TableCache<EbdtTables<'static>>>>,
1665    // Where a glyph's vertical origin sits, read only by vertical text.
1666    vorg: Once<TableCache<VorgTable<'static>>>,
1667    // Selected Unicode cmap subtables and their encoding metadata.
1668    charmap: Once<TableCache<SfntUnicodeCharmap<'static>>>,
1669    // Only clients selecting a charmap pay for the dense record array.
1670    encodings: Once<Box<TableCache<EncodingTables<'static>>>>,
1671}
1672
1673impl SfntCaches {
1674    fn new(tables: Arc<Tables>, index: u32) -> Self {
1675        Self {
1676            tables,
1677            index,
1678            hint_reliant: core::sync::atomic::AtomicU8::new(0),
1679            glyph_sources: core::sync::atomic::AtomicU32::new(0),
1680            default_location: SfntLocation::new(),
1681            h_metrics: Once::new(),
1682            v_metrics: Once::new(),
1683            glyf_loca: Once::new(),
1684            hvar: Once::new(),
1685            vvar: Once::new(),
1686            gvar: Once::new(),
1687            cff2: Once::new(),
1688            cff: Once::new(),
1689            varc: Once::new(),
1690            colr: Once::new(),
1691            cpal: Once::new(),
1692            sbix: Once::new(),
1693            cbdt: Once::new(),
1694            ebdt: Once::new(),
1695            vorg: Once::new(),
1696            charmap: Once::new(),
1697            encodings: Once::new(),
1698        }
1699    }
1700}
1701
1702struct StandaloneCffData {
1703    font: Yoke<CffFontRef<'static>, Arc<Blob>>,
1704    /// The first [`CACHED_SUBFONTS`] subfonts, parsed when the font is
1705    /// read; `None` where a private dict could not be.
1706    subfonts: Box<[Option<Subfont>]>,
1707    index: u32,
1708    unicode_charmap: Once<crate::ps::UnicodeCharmap>,
1709    /// The glyph for each CID of a CID-keyed font, zero where none has it.
1710    cid_glyphs: Once<Box<[u16]>>,
1711}
1712
1713/// Caches for one location of a font of any kind.
1714struct LocationCaches {
1715    /// Data that Skrifa derives from the font at this location.
1716    scaling_data: Once<Box<dyn Any + Send + Sync>>,
1717    // Metrics that describe the font as a whole, read once rather than per
1718    // query. Kept apart from the shaping and scaling slots, which each hold
1719    // one thing for one owner.
1720    metrics: Once<Metrics>,
1721    style_metrics: Once<Box<StyleMetrics>>,
1722}
1723
1724impl LocationCaches {
1725    const fn new() -> Self {
1726        Self {
1727            scaling_data: Once::new(),
1728            metrics: Once::new(),
1729            style_metrics: Once::new(),
1730        }
1731    }
1732}
1733
1734/// Caches for one location of an SFNT font.
1735struct SfntLocation {
1736    // Feature variation selection. Zero coordinates can still satisfy
1737    // conditions, so the default location keeps one too.
1738    feature_vars: FeatureVarsStorage,
1739    // CFF private dicts blend at a location, so each location parses its
1740    // own, as glyphs ask.
1741    cff2_subfonts: SubfontCache,
1742    cff_subfonts: SubfontCache,
1743}
1744
1745impl SfntLocation {
1746    fn new() -> Self {
1747        Self {
1748            feature_vars: FeatureVarsStorage::new(),
1749            cff2_subfonts: Once::new(),
1750            cff_subfonts: Once::new(),
1751        }
1752    }
1753}
1754
1755/// What a location away from the default carries.
1756struct VariedInstance {
1757    font: SharedFont,
1758    /// Never empty: an all-default location is [`Repr::Default`].
1759    coords: CoordStorage,
1760    location: LocationCaches,
1761    kind: VariedKind,
1762}
1763
1764/// Caches for a varied instance, by font kind.
1765///
1766/// SFNT fonts and Type 1 multiple master fonts have variation axes.
1767enum VariedKind {
1768    Sfnt(VariedSfnt),
1769    Type1(VariedType1),
1770}
1771
1772/// A Type 1 multiple master font at a location.
1773struct VariedType1 {
1774    /// The weight of each master.
1775    weights: SmallVec<[Fixed; 16]>,
1776}
1777
1778/// Caches for a varied SFNT instance.
1779struct VariedSfnt {
1780    location: SfntLocation,
1781    // The region scalars at the location, for the variation tables that
1782    // state deltas by region. The default location needs none.
1783    gvar_scalars: Once<Box<[Fixed]>>,
1784    hvar_scalars: Once<Box<[Fixed]>>,
1785    vvar_scalars: Once<Box<[Fixed]>>,
1786    colr_scalars: Once<Box<[Fixed]>>,
1787}
1788
1789const MAX_PRECOMPUTED_SCALARS: usize = 128;
1790
1791/// The kept answer for a glyph source the font does not have.
1792const SOURCE_ABSENT: u32 = 1;
1793/// The kept answer for a glyph source the font has.
1794const SOURCE_PRESENT: u32 = 2;
1795
1796/// Returns up to [`MAX_PRECOMPUTED_SCALARS`] scalars from `count`, filled by
1797/// `compute`, which returns how many it wrote.
1798fn scalars_with(count: usize, compute: impl FnOnce(&mut [Fixed]) -> usize) -> Box<[Fixed]> {
1799    let mut scalars = alloc::vec![Fixed::ZERO; count.min(MAX_PRECOMPUTED_SCALARS)];
1800    let written = compute(&mut scalars);
1801    scalars.truncate(written);
1802    scalars.into_boxed_slice()
1803}
1804
1805/// Returns the region scalars of `store` at `coords`, or none without a
1806/// store.
1807fn store_scalars(
1808    store: Option<&crate::tables::variations::ItemVariationStore<'_>>,
1809    coords: &[NormalizedCoord],
1810) -> Box<[Fixed]> {
1811    let Some(store) = store else {
1812        return Box::new([]);
1813    };
1814    let count = store
1815        .variation_region_list()
1816        .ok()
1817        .map_or(0, |regions| regions.variation_regions().len());
1818    scalars_with(count, |out| store.compute_scalars(coords, out))
1819}
1820
1821/// Lazy atomic storage for feature variation selections.
1822///
1823/// We don't want to load the GSUB and GPOS tables unless explicitly requested.
1824struct FeatureVarsStorage {
1825    gsub: AtomicU32,
1826    gpos: AtomicU32,
1827    /// Written before the indices, so it is current once they are.
1828    has_lookup_variations: AtomicBool,
1829}
1830
1831impl Default for FeatureVarsStorage {
1832    fn default() -> Self {
1833        Self::new()
1834    }
1835}
1836
1837impl FeatureVarsStorage {
1838    // Both sentinels sit where no record index reaches: a feature variation
1839    // record is eight bytes, so indexing this high would take a font of tens
1840    // of gigabytes.
1841    /// Nothing has read the tables yet.
1842    const UNCHECKED: u32 = u32::MAX;
1843    /// The tables were read and selected nothing.
1844    const ABSENT: u32 = u32::MAX - 1;
1845
1846    fn new() -> Self {
1847        Self {
1848            gsub: AtomicU32::new(Self::UNCHECKED),
1849            gpos: AtomicU32::new(Self::UNCHECKED),
1850            has_lookup_variations: AtomicBool::new(false),
1851        }
1852    }
1853
1854    fn load(&self, font: &SharedFont, coords: &[NormalizedCoord]) -> SelectedFeatureVariations {
1855        let (gsub, gpos) = (
1856            self.gsub.load(atomic::Ordering::Acquire),
1857            self.gpos.load(atomic::Ordering::Acquire),
1858        );
1859        if gsub != Self::UNCHECKED && gpos != Self::UNCHECKED {
1860            return SelectedFeatureVariations {
1861                gsub: Self::decode(gsub),
1862                gpos: Self::decode(gpos),
1863                has_lookup_variations: self.has_lookup_variations.load(atomic::Ordering::Relaxed),
1864            };
1865        }
1866        // Two threads that race here select the same indices, so the second
1867        // store writes what the first did.
1868        let selected = SelectedFeatureVariations::new(&font.tables(), coords);
1869        self.has_lookup_variations
1870            .store(selected.has_lookup_variations, atomic::Ordering::Relaxed);
1871        self.gsub
1872            .store(Self::encode(selected.gsub), atomic::Ordering::Release);
1873        self.gpos
1874            .store(Self::encode(selected.gpos), atomic::Ordering::Release);
1875        selected
1876    }
1877
1878    /// Returns the index a stored word holds, if it holds one.
1879    fn decode(value: u32) -> Option<u32> {
1880        (value < Self::ABSENT).then_some(value)
1881    }
1882
1883    /// Returns the word that stores a selection.
1884    fn encode(index: Option<u32>) -> u32 {
1885        index.unwrap_or(Self::ABSENT)
1886    }
1887}
1888
1889/// A cache of CFF subfonts at one location, each parsed when a glyph first
1890/// needs it.
1891///
1892/// A `None` cell means the subfont could not be read.
1893type SubfontCache = Once<Box<[Once<Option<Subfont>>]>>;
1894
1895/// The number of CFF subfonts a font keeps once parsed. A subfont past them
1896/// is parsed again whenever a glyph needs it.
1897const CACHED_SUBFONTS: usize = 8;
1898
1899/// Maximum number of coordinates we store inline. Chosen to maximize the
1900/// number of coords without growing the storage: a `SmallVec` is a capacity
1901/// alongside a union of the inline array and the heap pointer, so twelve
1902/// two byte coords are the most that fit in 32 bytes.
1903const MAX_INLINE_COORDS: usize = 12;
1904
1905type CoordStorage = SmallVec<[NormalizedCoord; MAX_INLINE_COORDS]>;
1906
1907/// Empties `coords` if every coordinate is zero. This lets the default
1908/// instance skip variation processing behind a plain `is_empty` check.
1909fn clear_if_all_zeroes(coords: &mut CoordStorage) {
1910    if coords.iter().all(|&c| c == NormalizedCoord::ZERO) {
1911        coords.clear();
1912    }
1913}
1914
1915#[cfg(test)]
1916impl Font {
1917    /// The storage behind a varied instance, for the cache tests.
1918    fn feature_vars(&self) -> &FeatureVarsStorage {
1919        match &self.0 {
1920            Repr::Varied(varied) => &varied.sfnt().location.feature_vars,
1921            Repr::Default(_) => panic!("the default instance keeps no storage of its own"),
1922        }
1923    }
1924}
1925
1926#[cfg(test)]
1927impl VariedInstance {
1928    /// Returns the SFNT caches of the instance, for the cache tests.
1929    fn sfnt(&self) -> &VariedSfnt {
1930        match &self.kind {
1931            VariedKind::Sfnt(sfnt) => sfnt,
1932            VariedKind::Type1(_) => panic!("not an SFNT instance"),
1933        }
1934    }
1935}
1936
1937#[cfg(test)]
1938mod tests {
1939    use super::*;
1940    use crate::ps::Sid;
1941    use crate::tables::glyf::outline::{Outline, Unscaled};
1942    use core::sync::atomic::Ordering;
1943    use types::Tag;
1944
1945    #[test]
1946    fn type1_loading_requires_feature() {
1947        let cid = font_test_data::type1::cid_font(false);
1948        for data in [
1949            font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA,
1950            font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFB,
1951            &cid,
1952        ] {
1953            assert_eq!(
1954                Font::new(data.to_vec(), 0).is_some(),
1955                cfg!(feature = "type1")
1956            );
1957            assert_eq!(
1958                crate::ps::type1::Type1Font::new(data).is_ok(),
1959                cfg!(feature = "type1")
1960            );
1961        }
1962    }
1963
1964    /// Returns where glyph 1 of the synthetic multiple master font starts
1965    /// drawing, which moves with the weight of its second master.
1966    #[cfg(feature = "type1")]
1967    fn type1_mm_start(font: &Font) -> f32 {
1968        use crate::model::glyph::outline::{DrawMemory, DrawOptions, PathElement};
1969        let mut path = alloc::vec::Vec::<PathElement>::new();
1970        font.outline_glyphs()
1971            .get(GlyphId::new(1))
1972            .unwrap()
1973            .draw(&DrawOptions::default(), DrawMemory::Scratch, &mut path)
1974            .unwrap();
1975        match path[0] {
1976            PathElement::MoveTo { x, .. } => x,
1977            _ => panic!("expected a move"),
1978        }
1979    }
1980
1981    // A Type 1 multiple master font has an axis per blend axis, and draws
1982    // and measures at the location an instance is built for.
1983    #[test]
1984    #[cfg(feature = "type1")]
1985    fn type1_multiple_master_instances() {
1986        use crate::ps::type1::multiple_master_tests::{pfa_with_blend, ONE_AXIS};
1987        let font = Font::new(pfa_with_blend(ONE_AXIS), 0).unwrap();
1988        let axes = font.axes();
1989        assert_eq!(axes.len(), 1);
1990        let axis = axes.get(0).unwrap();
1991        assert_eq!(axis.tag(), Tag::new(b"wght"));
1992        // The default is the font's own blend: a weight of 0.25 on the
1993        // second master, at design 300.
1994        assert_eq!(
1995            (axis.min_value(), axis.default_value(), axis.max_value()),
1996            (100.0, 300.0, 900.0)
1997        );
1998        let name = font.names().get(axis.name()).unwrap();
1999        assert_eq!(name.english_or_first().unwrap().name(), "Weight");
2000        assert!(font.named_instances().is_empty());
2001        assert!(font.normalized_coords().is_empty());
2002        assert_eq!(type1_mm_start(&font), 150.0);
2003        // The normalized coordinates are the blend, from 0 to 1. The first
2004        // master is all zeros, and stays a location of its own.
2005        for (design, blend, start) in [
2006            (900.0, 1.0, 300.0),
2007            (500.0, 0.5, 200.0),
2008            (100.0, 0.0, 100.0),
2009        ] {
2010            let instance = font
2011                .instance_builder()
2012                .variations([("wght", design)])
2013                .build();
2014            assert_eq!(
2015                instance.normalized_coords(),
2016                [NormalizedCoord::from_f32(blend)],
2017                "{design}"
2018            );
2019            assert_eq!(type1_mm_start(&instance), start, "{design}");
2020            let extents = instance.glyph_metrics().extents(GlyphId::new(1)).unwrap();
2021            assert_eq!(extents.x_bearing, start, "{design}");
2022            let by_blend = font
2023                .instance_builder()
2024                .normalized_coords([NormalizedCoord::from_f32(blend)])
2025                .build();
2026            assert_eq!(type1_mm_start(&by_blend), start, "{design}");
2027        }
2028    }
2029
2030    // A variation naming no axis leaves the default instance alone, even
2031    // where the default design coordinate doesn't map back to the default
2032    // blend.
2033    #[test]
2034    #[cfg(feature = "type1")]
2035    fn type1_multiple_master_ignores_unknown_axes() {
2036        use crate::ps::type1::multiple_master_tests::pfa_with_blend;
2037        let font = Font::new(
2038            pfa_with_blend(
2039                "/BlendAxisTypes [/Weight] def /BlendDesignPositions [[0] [1]] def                  /BlendDesignMap [[[0 0] [500 0.5] [1000 1]]] def                  /WeightVector [0.25 0.75] def",
2040            ),
2041            0,
2042        )
2043        .unwrap();
2044        assert_eq!(type1_mm_start(&font), 250.0);
2045        let instance = font.instance_builder().variations([("XXXX", 42.0)]).build();
2046        assert_eq!(type1_mm_start(&instance), 250.0);
2047    }
2048
2049    // Design maps spanning every design coordinate give axes whose values
2050    // saturate.
2051    #[test]
2052    #[cfg(feature = "type1")]
2053    fn type1_multiple_master_widest_axes() {
2054        use crate::ps::type1::multiple_master_tests::pfa_with_blend;
2055        let font = Font::new(
2056            pfa_with_blend(
2057                "/BlendAxisTypes [/Weight] def /BlendDesignPositions [[0] [1]] def                  /BlendDesignMap [[[-2147483648 0] [2147483647 1]]] def                  /WeightVector [0.5 0.5] def",
2058            ),
2059            0,
2060        )
2061        .unwrap();
2062        let axis = font.axes().get(0).unwrap();
2063        assert_eq!(
2064            (axis.min_value(), axis.default_value(), axis.max_value()),
2065            (-32768.0, 0.0, 32767.0)
2066        );
2067    }
2068
2069    // A Type 1 font's metrics don't vary, so an instance reports the
2070    // font's own.
2071    #[test]
2072    #[cfg(feature = "type1")]
2073    fn type1_multiple_master_instances_keep_metrics() {
2074        use crate::ps::type1::multiple_master_tests::{pfa_with_blend, ONE_AXIS};
2075        let font = Font::new(
2076            pfa_with_blend(&format!(
2077                "{ONE_AXIS} /FontBBox [-10 -200 600 800] def \
2078                 /ItalicAngle -12 def /UnderlinePosition -100 def \
2079                 /UnderlineThickness 50 def"
2080            )),
2081            0,
2082        )
2083        .unwrap();
2084        let instance = font
2085            .instance_builder()
2086            .variations([("wght", 900.0)])
2087            .build();
2088        assert!(!instance.normalized_coords().is_empty());
2089        assert_eq!(instance.metrics().num_glyphs, 2);
2090        assert_eq!(instance.metrics(), font.metrics());
2091        assert!(instance.style_metrics().underline.is_some());
2092        assert_eq!(instance.style_metrics(), font.style_metrics());
2093    }
2094
2095    // Type 1 has no named instances, but the overrides still apply.
2096    #[test]
2097    #[cfg(feature = "type1")]
2098    fn type1_multiple_master_named_instance_overrides() {
2099        use crate::ps::type1::multiple_master_tests::{pfa_with_blend, ONE_AXIS};
2100        let font = Font::new(pfa_with_blend(ONE_AXIS), 0).unwrap();
2101        let instance = font
2102            .instance_builder()
2103            .named_instance_with_overrides(0, [("wght", 900.0)])
2104            .build();
2105        assert_eq!(type1_mm_start(&instance), 300.0);
2106    }
2107
2108    // The index selects a font where the data can hold several, and is
2109    // ignored where it cannot.
2110    #[test]
2111    fn new_uses_the_index_as_documented() {
2112        assert!(Font::new(font_test_data::TINOS_SUBSET, 0).is_some());
2113        assert!(Font::new(font_test_data::TINOS_SUBSET, 1).is_none());
2114        let count = crate::FileRef::new(font_test_data::ttc::TTC)
2115            .ok()
2116            .and_then(|file| match file {
2117                crate::FileRef::Collection(collection) => Some(collection.len()),
2118                _ => None,
2119            })
2120            .unwrap();
2121        assert!(count > 1);
2122        assert!(Font::new(font_test_data::ttc::TTC, count - 1).is_some());
2123        assert!(Font::new(font_test_data::ttc::TTC, count).is_none());
2124        #[cfg(feature = "type1")]
2125        assert!(Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA, 7).is_some());
2126        let sfnt = crate::FontRef::new(font_test_data::NOTO_SANS_JP_CFF).unwrap();
2127        let cff = sfnt.cff().unwrap().offset_data().as_bytes().to_vec();
2128        assert!(Font::new(cff.clone(), 0).is_some());
2129        assert!(Font::new(cff, 1).is_none());
2130    }
2131
2132    // A standalone CID-keyed font finds each glyph by the CID its charset
2133    // gives it.
2134    #[test]
2135    fn cid_keyed_fonts_map_cids_to_glyphs() {
2136        let sfnt = crate::FontRef::new(font_test_data::NOTO_SANS_JP_CFF).unwrap();
2137        let font = Font::new(sfnt.cff().unwrap().offset_data().as_bytes(), 0).unwrap();
2138        assert!(font.is_cid_keyed());
2139        let charset = font.shared().standalone_cff().unwrap().charset().unwrap();
2140        let max = charset
2141            .iter()
2142            .map(|(_, cid)| cid.to_u16() as u32)
2143            .max()
2144            .unwrap();
2145        assert_eq!(font.max_cid(), Some(max));
2146        for cid in 0..=max + 1 {
2147            let expected = charset
2148                .glyph_id(Sid::new(cid as u16))
2149                .filter(|glyph| glyph.to_u32() < font.num_glyphs());
2150            assert_eq!(font.glyph_by_cid(cid), expected, "cid {cid}");
2151        }
2152        assert_eq!(font.glyph_by_cid(0x10000), None);
2153    }
2154
2155    // A later glyph that claims a CID already taken, CID zero included,
2156    // leaves the first glyph in place.
2157    #[test]
2158    fn the_first_glyph_keeps_its_cid() {
2159        let cids = [(0u16, 0usize), (1, 2), (2, 0), (3, 2), (4, 1)];
2160        assert_eq!(&*cid_table(|| cids.into_iter()), &[0, 4, 1]);
2161    }
2162
2163    #[test]
2164    fn other_fonts_have_no_cids() {
2165        for font in [
2166            // A CID-keyed `CFF` table in an SFNT font.
2167            Font::new(font_test_data::NOTO_SANS_JP_CFF, 0).unwrap(),
2168            Font::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED, 0).unwrap(),
2169            Font::new(font_test_data::VAZIRMATN_VAR, 0).unwrap(),
2170            #[cfg(feature = "type1")]
2171            Font::new(font_test_data::type1::NOTO_SERIF_REGULAR_SUBSET_PFA, 0).unwrap(),
2172        ] {
2173            assert!(!font.is_cid_keyed());
2174            assert_eq!(font.glyph_by_cid(1), None);
2175            assert_eq!(font.max_cid(), None);
2176        }
2177    }
2178
2179    #[test]
2180    fn standalone_cff_with_a_bad_private_dict_still_opens() {
2181        let sfnt = crate::FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
2182        let mut raw = sfnt.cff().unwrap().offset_data().as_bytes().to_vec();
2183        let private = CffFontRef::new_cff(&raw, 0, None)
2184            .unwrap()
2185            .sid_private_dict_range()
2186            .unwrap();
2187        // A Subrs offset of -1, which no private dict can resolve.
2188        let damage = [29u8, 0xff, 0xff, 0xff, 0xff, 19];
2189        assert!(private.len() >= damage.len());
2190        raw[private.start..private.start + damage.len()].copy_from_slice(&damage);
2191        let font = Font::new(raw, 0).unwrap();
2192        let subfonts = font.shared().standalone_cff_subfonts().unwrap();
2193        assert!(subfonts.len() == 1 && subfonts[0].is_none());
2194        assert!(font.num_glyphs() > 1);
2195        // Every glyph of the font is in that one subfont, so none draws or
2196        // measures.
2197        let outlines = font.outline_glyphs();
2198        assert_eq!(outlines.source(), Some(OutlineSource::Cff));
2199        for glyph in 0..font.num_glyphs() {
2200            let glyph = GlyphId::new(glyph);
2201            assert!(outlines.get(glyph).is_none());
2202            assert_eq!(font.glyph_metrics().h_advance(glyph), 0.0);
2203            assert!(font.glyph_metrics().extents(glyph).is_none());
2204        }
2205    }
2206
2207    #[test]
2208    fn standalone_cff_uses_selected_font_data() {
2209        let sfnt = crate::FontRef::new(font_test_data::NOTO_SERIF_DISPLAY_TRIMMED).unwrap();
2210        let raw = sfnt.cff().unwrap().offset_data().as_bytes();
2211        let direct = CffFontRef::new_cff(raw, 0, None).unwrap();
2212        let font = Font::new(raw.to_vec(), 0).unwrap();
2213        assert!(matches!(font.kind(), Kind::Cff(_, 0)));
2214        assert!(Font::new(raw.to_vec(), 1).is_none());
2215        assert_eq!(font.num_glyphs(), direct.num_glyphs());
2216        assert_eq!(font.units_per_em(), direct.upem() as u16);
2217        let bbox = direct.metadata().unwrap().bbox();
2218        assert_eq!(font.metrics().bounds.x_min, bbox.x_min.to_f48dot16());
2219        assert_eq!(font.metrics().bounds.y_max, bbox.y_max.to_f48dot16());
2220        assert_eq!(
2221            font.style_metrics().italic_angle,
2222            Some(direct.metadata().unwrap().italic_angle())
2223        );
2224        assert_eq!(
2225            font.shared().standalone_cff_subfonts().unwrap().len(),
2226            direct.num_subfonts() as usize
2227        );
2228        assert!(font.tables().cff().is_err());
2229        assert!(font.cff().is_none());
2230        let metadata = direct.metadata().unwrap();
2231        assert_eq!(metadata.version(), Some("2.9"));
2232        assert_eq!(
2233            metadata.notice(),
2234            Some("Noto is a trademark of Google LLC.")
2235        );
2236        assert!(metadata.copyright().unwrap().starts_with("Copyright 2022"));
2237        for (id, expected) in [
2238            (types::NameId::COPYRIGHT_NOTICE, metadata.copyright()),
2239            (types::NameId::FAMILY_NAME, metadata.family_name()),
2240            (types::NameId::SUBFAMILY_NAME, metadata.weight()),
2241            (types::NameId::FULL_NAME, metadata.full_name()),
2242            (types::NameId::VERSION_STRING, metadata.version()),
2243            (types::NameId::POSTSCRIPT_NAME, metadata.name()),
2244            (types::NameId::TRADEMARK, metadata.notice()),
2245        ] {
2246            let entries: Vec<_> = font
2247                .names()
2248                .get(id)
2249                .map(|name| name.iter().collect())
2250                .unwrap_or_default();
2251            assert_eq!(entries.len(), usize::from(expected.is_some()));
2252            if let Some(expected) = expected {
2253                assert_eq!(entries[0].name(), expected);
2254                assert!(entries[0].language().is_none());
2255                assert!(entries[0].sfnt_record().is_none());
2256            }
2257        }
2258        assert!(font
2259            .glyph_metrics()
2260            .extents_exact(GlyphId::new(1))
2261            .is_some());
2262        assert_eq!(font.glyph_name(GlyphId::new(1)).unwrap().as_str(), "i");
2263        #[cfg(feature = "agl")]
2264        assert_eq!(font.charmap().map_unicode('i'), Some(GlyphId::new(1)));
2265        let native = font
2266            .charmap()
2267            .encodings()
2268            .find(|encoding| encoding.kind() != super::super::charmap::EncodingKind::Unicode)
2269            .unwrap();
2270        // A standalone CFF encoding names no record in either mapping table.
2271        for encoding in font.charmap().encodings() {
2272            assert_eq!(encoding.sfnt_index(), None);
2273            assert_eq!(encoding.sfnt_ids(), None);
2274        }
2275        assert_eq!(
2276            font.charmap().map_code(native, b'i' as u32),
2277            direct.encoding().unwrap().map(b'i')
2278        );
2279        assert!(font
2280            .charmap()
2281            .codes(native)
2282            .any(|(code, glyph)| code == b'i' as u32 && glyph == GlyphId::new(1)));
2283
2284        let names: Vec<_> = font.glyph_names().collect();
2285        assert_eq!(names.len(), font.num_glyphs() as usize);
2286        for (glyph, name) in names.iter().take(8) {
2287            assert_eq!(font.glyph_name(*glyph).unwrap().as_str(), name.as_str());
2288            let subfont = direct
2289                .subfont(direct.subfont_index(*glyph).unwrap(), &[])
2290                .unwrap();
2291            let width = direct.evaluate_width(&subfont, *glyph, &[]).unwrap();
2292            assert_eq!(
2293                font.glyph_metrics().h_advance_exact(*glyph),
2294                width.map(|width| width.to_f48dot16()).unwrap_or_default(),
2295            );
2296        }
2297        assert_eq!(
2298            font.glyph_metrics()
2299                .h_advance_exact(GlyphId::new(font.num_glyphs())),
2300            types::F48Dot16::ZERO
2301        );
2302        assert_eq!(
2303            font.default_instance()
2304                .glyph_name(GlyphId::new(1))
2305                .unwrap()
2306                .as_str(),
2307            font.glyph_name(GlyphId::new(1)).unwrap().as_str()
2308        );
2309    }
2310
2311    #[cfg(feature = "std")]
2312    #[test]
2313    fn variation_scalars_are_lazy_bounded_and_shared() {
2314        let font = Font::new(font_test_data::VAZIRMATN_VAR, 0).unwrap();
2315        let instance = font
2316            .instance_builder()
2317            .normalized_coords([NormalizedCoord::from_f32(-0.75)])
2318            .build();
2319        let Repr::Varied(varied) = &instance.0 else {
2320            panic!("expected a varied instance");
2321        };
2322        assert!(varied.sfnt().gvar_scalars.get().is_none());
2323        assert!(varied.sfnt().hvar_scalars.get().is_none());
2324
2325        let gvar_scalars = instance.gvar_scalars();
2326        assert!(!gvar_scalars.is_empty());
2327        let gvar = instance.selected_gvar().unwrap();
2328        assert_eq!(
2329            gvar_scalars.len(),
2330            (gvar.shared_tuple_count() as usize).min(MAX_PRECOMPUTED_SCALARS)
2331        );
2332        assert!(varied.sfnt().hvar_scalars.get().is_none());
2333        let mut expected = alloc::vec![Fixed::ZERO; gvar_scalars.len()];
2334        let count = gvar.compute_scalars(instance.normalized_coords(), &mut expected);
2335        assert_eq!(gvar_scalars, &expected[..count]);
2336
2337        let hvar_scalars = instance.hvar_scalars();
2338        assert!(!hvar_scalars.is_empty());
2339        let hvar = instance.hvar().unwrap();
2340        let regions = hvar
2341            .item_variation_store()
2342            .unwrap()
2343            .variation_region_list()
2344            .unwrap();
2345        assert_eq!(
2346            hvar_scalars.len(),
2347            regions
2348                .variation_regions()
2349                .len()
2350                .min(MAX_PRECOMPUTED_SCALARS)
2351        );
2352        expected.resize(hvar_scalars.len(), Fixed::ZERO);
2353        let count = hvar.compute_scalars(instance.normalized_coords(), &mut expected);
2354        assert_eq!(hvar_scalars, &expected[..count]);
2355        let clone = instance.clone();
2356        assert!(core::ptr::eq(gvar_scalars, clone.gvar_scalars()));
2357        assert!(core::ptr::eq(hvar_scalars, clone.hvar_scalars()));
2358        assert!(font.gvar_scalars().is_empty());
2359        assert!(font.hvar_scalars().is_empty());
2360    }
2361
2362    #[cfg(feature = "std")]
2363    #[test]
2364    fn vvar_scalars_are_lazy_bounded_and_shared() {
2365        let font = Font::new(font_test_data::MPLUS1CODE_VERTICAL_SUBSET, 0).unwrap();
2366        let instance = font
2367            .instance_builder()
2368            .normalized_coords([NormalizedCoord::from_f32(-0.75)])
2369            .build();
2370        let Repr::Varied(varied) = &instance.0 else {
2371            panic!("expected a varied instance");
2372        };
2373        assert!(varied.sfnt().vvar_scalars.get().is_none());
2374
2375        let scalars = instance.vvar_scalars();
2376        assert!(!scalars.is_empty());
2377        let vvar = instance.vvar().unwrap();
2378        let regions = vvar
2379            .item_variation_store()
2380            .unwrap()
2381            .variation_region_list()
2382            .unwrap();
2383        assert_eq!(
2384            scalars.len(),
2385            regions
2386                .variation_regions()
2387                .len()
2388                .min(MAX_PRECOMPUTED_SCALARS)
2389        );
2390        let mut expected = alloc::vec![Fixed::ZERO; scalars.len()];
2391        let count = vvar.compute_scalars(instance.normalized_coords(), &mut expected);
2392        assert_eq!(scalars, &expected[..count]);
2393        assert!(core::ptr::eq(scalars, instance.clone().vvar_scalars()));
2394        assert!(font.vvar_scalars().is_empty());
2395    }
2396
2397    #[test]
2398    fn font_outline_context_uses_stated_vertical_metrics() {
2399        let data = font_test_data::MPLUS1CODE_VERTICAL_SUBSET;
2400        let font = Font::new(data, 0).unwrap();
2401        let direct = crate::FontRef::new(data).unwrap();
2402        let gid = GlyphId::new(1);
2403        let glyph = direct
2404            .loca(None)
2405            .unwrap()
2406            .get_glyf(gid, &direct.glyf().unwrap())
2407            .unwrap()
2408            .unwrap();
2409        let tsb = direct.vmtx().unwrap().side_bearing(gid).unwrap();
2410        let context = &font;
2411        let mut outline = Outline::<Unscaled>::new();
2412        let loaded = outline.load_with(&context, gid, &Unscaled, None).unwrap();
2413        assert_eq!(
2414            loaded.phantom_points()[2].y,
2415            glyph.y_max() as i32 + tsb as i32
2416        );
2417    }
2418
2419    #[test]
2420    fn outline_context_uses_unvaried_h_line_metrics() {
2421        let font = Font::new(MVAR_FONT, 0).unwrap();
2422        let far = font
2423            .instance_builder()
2424            .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2425            .build();
2426        let line = font.shared().metrics().h_line().unwrap();
2427        assert_ne!(Some(line), font.metrics().typo_line);
2428        let expected = (line.ascender.to_i32(), line.descender.to_i32());
2429        assert_ne!(far.metrics().h_line(), font.metrics().h_line());
2430        assert_eq!((&font).h_line_metrics(), expected);
2431        assert_eq!((&far).h_line_metrics(), expected);
2432    }
2433
2434    #[test]
2435    fn named_instances() {
2436        let font = Font::new(font_test_data::CANTARELL_VF_TRIMMED, 0).unwrap();
2437        let cases = [
2438            // (named instance index, expected weight value)
2439            (0, 100.0),
2440            (1, 300.0),
2441            (2, 400.0),
2442            (3, 700.0),
2443            (4, 800.0),
2444        ];
2445        for (index, weight) in cases {
2446            let named_instance = font.instance_builder().named_instance(index).build();
2447            let var_instance = font
2448                .instance_builder()
2449                .variations([("wght", weight)])
2450                .build();
2451            assert_eq!(
2452                named_instance.normalized_coords(),
2453                var_instance.normalized_coords(),
2454                "index={index}"
2455            );
2456        }
2457        // Out of bounds index should give us the default instance.
2458        let invalid_instance = font.instance_builder().named_instance(5).build();
2459        assert!(
2460            invalid_instance.normalized_coords().is_empty(),
2461            "out of bounds index should give default instance"
2462        );
2463    }
2464
2465    #[test]
2466    fn named_instance_with_overrides_override_named_value() {
2467        let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2468        let actual = font
2469            .instance_builder()
2470            .named_instance_with_overrides(3, [("FILL", 1.0)])
2471            .build();
2472        let expected = font
2473            .instance_builder()
2474            .variations([
2475                ("FILL", 1.0),
2476                ("GRAD", 0.0),
2477                ("opsz", 24.0),
2478                ("wght", 400.0),
2479            ])
2480            .build();
2481        assert_eq!(actual.normalized_coords(), expected.normalized_coords());
2482    }
2483
2484    #[test]
2485    fn named_instance_with_overrides_invalid_index_uses_overrides_only() {
2486        let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2487        let actual = font
2488            .instance_builder()
2489            .named_instance_with_overrides(999, [("FILL", 1.0), ("ZZZZ", 123.0)])
2490            .build();
2491        let expected = font
2492            .instance_builder()
2493            .variations([("FILL", 1.0), ("ZZZZ", 123.0)])
2494            .build();
2495        assert_eq!(actual.normalized_coords(), expected.normalized_coords());
2496        assert_eq!(actual.normalized_coords().len(), 4);
2497    }
2498
2499    #[test]
2500    fn named_instance_with_overrides_overwrites_previous_settings() {
2501        let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2502        let actual = font
2503            .instance_builder()
2504            .variations([("FILL", 0.0), ("wght", 100.0)])
2505            .named_instance_with_overrides(5, [("GRAD", -25.0)])
2506            .build();
2507        let expected = font
2508            .instance_builder()
2509            .variations([
2510                ("FILL", 0.0),
2511                ("GRAD", -25.0),
2512                ("opsz", 24.0),
2513                ("wght", 600.0),
2514            ])
2515            .build();
2516        assert_eq!(actual.normalized_coords(), expected.normalized_coords());
2517    }
2518
2519    #[test]
2520    fn feature_variations() {
2521        let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2522        let cases = [
2523            // (fill, [GSUB feature variation index, GPOS feature variation index])
2524            (0.0, [None, None]),
2525            (0.5, [None, None]),
2526            (0.98, [None, None]),
2527            (0.99, [Some(0), None]),
2528            (1.0, [Some(0), None]),
2529        ];
2530        for (fill, [gsub, gpos]) in cases {
2531            let instance = font.instance_builder().variations([("FILL", fill)]).build();
2532            let feature_vars = instance.feature_variations();
2533            let actual = [feature_vars.gsub, feature_vars.gpos];
2534            assert_eq!(actual, [gsub, gpos], "fill={fill}");
2535        }
2536    }
2537
2538    #[test]
2539    fn default_instance_evaluates_and_caches_feature_variations() {
2540        let source = crate::FontRef::new(font_test_data::MATERIAL_SYMBOLS_SUBSET).unwrap();
2541        let tables = super::super::TableFunction::new(Arc::new(move |tag| {
2542            if tag == Tag::new(b"GSUB") {
2543                // GSUB 1.1 followed by one feature-variation record whose
2544                // axis-zero range matches exactly the default location.
2545                return Some(super::super::Blob::from(vec![
2546                    0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 16,
2547                    0, 0, 0, 0, 0, 1, 0, 0, 0, 6, 0, 1, 0, 0, 0, 0, 0, 0,
2548                ]));
2549            }
2550            if tag == Tag::new(b"GPOS") {
2551                return None;
2552            }
2553            source
2554                .data_for_tag(tag)
2555                .map(|data| super::super::Blob::from(data.as_bytes().to_vec()))
2556        }));
2557        let font = Font::new(tables, 0).unwrap();
2558        assert_eq!(
2559            font.shared()
2560                .sfnt()
2561                .unwrap()
2562                .default_location
2563                .feature_vars
2564                .gsub
2565                .load(Ordering::Acquire),
2566            FeatureVarsStorage::UNCHECKED
2567        );
2568        let expected = SelectedFeatureVariations {
2569            gsub: Some(0),
2570            gpos: None,
2571            has_lookup_variations: false,
2572        };
2573        assert_eq!(font.feature_variations(), expected);
2574        assert_eq!(
2575            font.shared()
2576                .sfnt()
2577                .unwrap()
2578                .default_location
2579                .feature_vars
2580                .gsub
2581                .load(Ordering::Acquire),
2582            0
2583        );
2584        assert_eq!(font.default_instance().feature_variations(), expected);
2585        let default = font
2586            .instance_builder()
2587            .normalized_coords([NormalizedCoord::ZERO; 4])
2588            .build();
2589        assert!(default.normalized_coords().is_empty());
2590        assert_eq!(default.feature_variations(), expected);
2591        let varied = font
2592            .instance_builder()
2593            .normalized_coords([NormalizedCoord::from_f32(0.5); 4])
2594            .build();
2595        assert_eq!(
2596            varied.feature_variations(),
2597            SelectedFeatureVariations::default()
2598        );
2599        assert_eq!(font.feature_variations(), expected);
2600    }
2601
2602    #[test]
2603    fn feature_variation_cache_marks_both_absent() {
2604        let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2605        let instance = font.instance_builder().variations([("FILL", 0.5)]).build();
2606        let storage = instance.feature_vars();
2607        assert_eq!(
2608            storage.gsub.load(Ordering::Acquire),
2609            FeatureVarsStorage::UNCHECKED
2610        );
2611        assert_eq!(
2612            storage.gpos.load(Ordering::Acquire),
2613            FeatureVarsStorage::UNCHECKED
2614        );
2615        assert_eq!(
2616            instance.feature_variations(),
2617            SelectedFeatureVariations::default()
2618        );
2619        assert_eq!(
2620            storage.gsub.load(Ordering::Acquire),
2621            FeatureVarsStorage::ABSENT
2622        );
2623        assert_eq!(
2624            storage.gpos.load(Ordering::Acquire),
2625            FeatureVarsStorage::ABSENT
2626        );
2627    }
2628
2629    #[test]
2630    fn feature_variation_cache_is_thread_safe_and_stable() {
2631        let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2632        let instance = font.instance_builder().variations([("FILL", 1.0)]).build();
2633        std::thread::scope(|scope| {
2634            for _ in 0..8 {
2635                scope.spawn(|| {
2636                    for _ in 0..64 {
2637                        let vars = instance.feature_variations();
2638                        assert_eq!(
2639                            vars,
2640                            SelectedFeatureVariations {
2641                                gsub: Some(0),
2642                                gpos: None,
2643                                has_lookup_variations: false,
2644                            }
2645                        );
2646                    }
2647                });
2648            }
2649        });
2650        let storage = instance.feature_vars();
2651        assert_eq!(storage.gsub.load(Ordering::Acquire), 0);
2652        assert_eq!(
2653            storage.gpos.load(Ordering::Acquire),
2654            FeatureVarsStorage::ABSENT
2655        );
2656    }
2657
2658    #[test]
2659    fn variations_last_value_wins_and_unknown_axis_ignored() {
2660        let font = Font::new(font_test_data::CANTARELL_VF_TRIMMED, 0).unwrap();
2661        let expected = font
2662            .instance_builder()
2663            .variations([("wght", 700.0)])
2664            .build();
2665        let repeated_axis = font
2666            .instance_builder()
2667            .variations([("wght", 100.0), ("wght", 700.0)])
2668            .build();
2669        assert_eq!(
2670            repeated_axis.normalized_coords(),
2671            expected.normalized_coords()
2672        );
2673        let unknown_axis = font
2674            .instance_builder()
2675            .variations([("wght", 700.0), ("ZZZZ", 123.0)])
2676            .build();
2677        assert_eq!(
2678            unknown_axis.normalized_coords(),
2679            expected.normalized_coords()
2680        );
2681    }
2682
2683    #[test]
2684    fn later_variation_call_overwrites_previous() {
2685        let font = Font::new(font_test_data::CANTARELL_VF_TRIMMED, 0).unwrap();
2686        let overwritten = font
2687            .instance_builder()
2688            .variations([("wght", 700.0)])
2689            .variations([("wght", 100.0)])
2690            .build();
2691        let expected = font
2692            .instance_builder()
2693            .variations([("wght", 100.0)])
2694            .build();
2695        assert_eq!(
2696            overwritten.normalized_coords(),
2697            expected.normalized_coords()
2698        );
2699    }
2700
2701    #[test]
2702    fn normalized_coords_empty_resets_to_default_instance() {
2703        let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2704        let instance = font.instance_builder().normalized_coords([]).build();
2705        assert!(instance.normalized_coords().is_empty());
2706    }
2707
2708    #[test]
2709    fn normalized_coords_truncates_and_pads() {
2710        let font = Font::new(font_test_data::MATERIAL_SYMBOLS_SUBSET, 0).unwrap();
2711        let axis_count = font.tables().fvar().unwrap().axis_count() as usize;
2712        let values = [0.25, -0.5, 1.0, 0.75, -0.25].map(NormalizedCoord::from_f32);
2713        let instance = font.instance_builder().normalized_coords(values).build();
2714        let coords = instance.normalized_coords();
2715        assert_eq!(coords.len(), axis_count);
2716        let copied = values.len().min(axis_count);
2717        assert_eq!(&coords[..copied], &values[..copied]);
2718        assert!(coords[copied..]
2719            .iter()
2720            .all(|&coord| coord == NormalizedCoord::ZERO));
2721    }
2722
2723    /// Twelve axes, and an `MVAR` that varies its heights.
2724    const MVAR_FONT: &[u8] = font_test_data::AMSTELVAR_AVAR2_A;
2725
2726    #[test]
2727    fn ordinary_metrics_do_not_read_post() {
2728        let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
2729        let logged = asked.clone();
2730        let source: Arc<dyn Fn(Tag) -> Option<Blob> + Send + Sync> = Arc::new(move |tag| {
2731            logged.lock().unwrap().push(tag);
2732            let font = crate::FontRef::new(font_test_data::TINOS_SUBSET).ok()?;
2733            font.table_data(tag)
2734                .map(|data| Blob::from(data.as_bytes().to_vec()))
2735        });
2736        let font = Font::new(source, 0).unwrap();
2737        asked.lock().unwrap().clear();
2738        let _ = font.metrics();
2739        assert!(!asked.lock().unwrap().contains(&Tag::new(b"post")));
2740        let _ = font.style_metrics();
2741        assert!(asked.lock().unwrap().contains(&Tag::new(b"post")));
2742        assert!(core::ptr::eq(font.style_metrics(), font.style_metrics()));
2743    }
2744
2745    #[test]
2746    fn an_instance_varies_its_metrics() {
2747        let font = Font::new(MVAR_FONT, 0).unwrap();
2748        let far = font
2749            .instance_builder()
2750            .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2751            .build();
2752        assert!(!far.normalized_coords().is_empty());
2753        assert_ne!(far.metrics(), font.metrics());
2754    }
2755
2756    #[test]
2757    fn an_instance_varies_and_shares_its_style_metrics() {
2758        let font = Font::new(MVAR_FONT, 0).unwrap();
2759        let far = font
2760            .instance_builder()
2761            .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2762            .build();
2763        assert_ne!(
2764            far.style_metrics().strike_through,
2765            font.style_metrics().strike_through
2766        );
2767        assert!(core::ptr::eq(
2768            far.style_metrics(),
2769            far.clone().style_metrics()
2770        ));
2771    }
2772
2773    #[test]
2774    fn an_instance_at_the_default_location_shares_the_font_metrics() {
2775        // Nothing varies there, so there is no second copy to compute.
2776        let font = Font::new(MVAR_FONT, 0).unwrap();
2777        let default = font.instance_builder().build();
2778        assert!(core::ptr::eq(default.metrics(), font.metrics()));
2779    }
2780
2781    #[test]
2782    fn clones_of_an_instance_share_one_set_of_metrics() {
2783        let font = Font::new(MVAR_FONT, 0).unwrap();
2784        let far = font
2785            .instance_builder()
2786            .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2787            .build();
2788        let shared = far.clone();
2789        // The location is resolved once, not once per holder.
2790        assert!(core::ptr::eq(far.metrics(), shared.metrics()));
2791    }
2792
2793    #[test]
2794    fn the_fixed_numbers_do_not_resolve_a_location() {
2795        // Both are properties of the font, so reaching them through an
2796        // instance must not read `MVAR` the way its whole-font metrics do.
2797        let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
2798        let logged = asked.clone();
2799        let source: Arc<dyn Fn(Tag) -> Option<crate::model::Blob> + Send + Sync> =
2800            Arc::new(move |tag: Tag| {
2801                logged.lock().unwrap().push(tag);
2802                let font = crate::FontRef::new(MVAR_FONT).ok()?;
2803                Some(crate::model::Blob::from(
2804                    font.table_data(tag)?.as_bytes().to_vec(),
2805                ))
2806            });
2807        let font = Font::new(source, 0).unwrap();
2808        let far = font
2809            .instance_builder()
2810            .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2811            .build();
2812        asked.lock().unwrap().clear();
2813
2814        assert_eq!(far.num_glyphs(), font.num_glyphs());
2815        assert_eq!(far.units_per_em(), font.units_per_em());
2816        assert!(
2817            !asked.lock().unwrap().contains(&Tag::new(b"MVAR")),
2818            "reading a fixed number resolved the location"
2819        );
2820
2821        // And the varied metrics still do.
2822        let _ = far.metrics();
2823        assert!(asked.lock().unwrap().contains(&Tag::new(b"MVAR")));
2824    }
2825
2826    #[test]
2827    fn a_default_instance_is_only_its_font() {
2828        // Nothing about the default location needs owning, so building one
2829        // shares the font rather than allocating beside it.
2830        let font = Font::new(MVAR_FONT, 0).unwrap();
2831        for instance in [
2832            font.default_instance(),
2833            font.instance_builder().build(),
2834            // An all-default location collapses to no coordinates, so this
2835            // reaches the same place.
2836            font.instance_builder()
2837                .normalized_coords([NormalizedCoord::from_f32(0.0); 12])
2838                .build(),
2839        ] {
2840            assert!(matches!(instance.0, Repr::Default(_)));
2841            assert!(instance.normalized_coords().is_empty());
2842            assert!(core::ptr::eq(instance.metrics(), font.metrics()));
2843        }
2844    }
2845
2846    #[test]
2847    fn a_location_away_from_the_default_is_owned() {
2848        let font = Font::new(MVAR_FONT, 0).unwrap();
2849        let far = font
2850            .instance_builder()
2851            .normalized_coords([NormalizedCoord::from_f32(1.0); 12])
2852            .build();
2853        assert!(matches!(far.0, Repr::Varied(_)));
2854        assert_eq!(far.normalized_coords().len(), 12);
2855    }
2856}