Skip to main content

read_fonts/tables/
hvar.rs

1//! The [HVAR (Horizontal Metrics Variation)](https://docs.microsoft.com/en-us/typography/opentype/spec/hvar) table
2
3use super::variations::{self, DeltaSetIndexMap, ItemVariationStore};
4use types::F48Dot16;
5
6include!("../../generated/generated_hvar.rs");
7
8impl Hvar<'_> {
9    /// Computes the scalar for each variation region at `coords`, in table
10    /// order, and returns how many were written.
11    ///
12    /// See [`ItemVariationStore::compute_scalars`] for what `out` receives.
13    ///
14    /// [`ItemVariationStore::compute_scalars`]: crate::tables::variations::ItemVariationStore::compute_scalars
15    pub fn compute_scalars(&self, coords: &[F2Dot14], out: &mut [Fixed]) -> usize {
16        match self.item_variation_store() {
17            Ok(store) => store.compute_scalars(coords, out),
18            Err(_) => 0,
19        }
20    }
21
22    /// Returns the change a location makes to the advance width of a glyph.
23    ///
24    /// The value carries every bit the item variation store computed. It is
25    /// a caller that decides how to round it into a whole design unit, and
26    /// implementations differ on that.
27    ///
28    /// Returns `None` where the table says nothing readable about the glyph.
29    pub fn advance_delta(&self, glyph_id: GlyphId, coords: &[F2Dot14]) -> Option<F48Dot16> {
30        self.advance_delta_with_scalars(glyph_id, coords, &[])
31    }
32
33    /// Returns the change a location makes to the advance width of a glyph, reusing
34    /// `scalars`.
35    ///
36    /// `scalars` holds one entry per variation region, from
37    /// [`compute_scalars`](Self::compute_scalars).
38    pub fn advance_delta_with_scalars(
39        &self,
40        glyph_id: GlyphId,
41        coords: &[F2Dot14],
42        scalars: &[Fixed],
43    ) -> Option<F48Dot16> {
44        variations::advance_delta_with_scalars(
45            self.advance_width_mapping(),
46            self.item_variation_store(),
47            glyph_id,
48            coords,
49            scalars,
50        )
51    }
52
53    /// Returns the change a location makes to the left side bearing of a glyph.
54    ///
55    /// The value carries every bit the item variation store computed. It is
56    /// a caller that decides how to round it into a whole design unit, and
57    /// implementations differ on that.
58    ///
59    /// Returns `None` where the table says nothing readable about the glyph.
60    pub fn lsb_delta(&self, glyph_id: GlyphId, coords: &[F2Dot14]) -> Option<F48Dot16> {
61        self.lsb_delta_with_scalars(glyph_id, coords, &[])
62    }
63
64    /// Returns the change a location makes to the left side bearing of a glyph, reusing
65    /// `scalars`.
66    ///
67    /// `scalars` holds one entry per variation region, from
68    /// [`compute_scalars`](Self::compute_scalars).
69    pub fn lsb_delta_with_scalars(
70        &self,
71        glyph_id: GlyphId,
72        coords: &[F2Dot14],
73        scalars: &[Fixed],
74    ) -> Option<F48Dot16> {
75        variations::item_delta_with_scalars(
76            self.lsb_mapping(),
77            self.item_variation_store(),
78            glyph_id,
79            coords,
80            scalars,
81        )
82    }
83
84    /// Returns the change a location makes to the right side bearing of a glyph.
85    ///
86    /// The value carries every bit the item variation store computed. It is
87    /// a caller that decides how to round it into a whole design unit, and
88    /// implementations differ on that.
89    ///
90    /// Returns `None` where the table says nothing readable about the glyph.
91    pub fn rsb_delta(&self, glyph_id: GlyphId, coords: &[F2Dot14]) -> Option<F48Dot16> {
92        self.rsb_delta_with_scalars(glyph_id, coords, &[])
93    }
94
95    /// Returns the change a location makes to the right side bearing of a glyph, reusing
96    /// `scalars`.
97    ///
98    /// `scalars` holds one entry per variation region, from
99    /// [`compute_scalars`](Self::compute_scalars).
100    pub fn rsb_delta_with_scalars(
101        &self,
102        glyph_id: GlyphId,
103        coords: &[F2Dot14],
104        scalars: &[Fixed],
105    ) -> Option<F48Dot16> {
106        variations::item_delta_with_scalars(
107            self.rsb_mapping(),
108            self.item_variation_store(),
109            glyph_id,
110            coords,
111            scalars,
112        )
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use crate::{tables::variations::DeltaSetIndexMap, FontRef, TableProvider};
119    use types::{F2Dot14, F48Dot16, GlyphId};
120
121    #[test]
122    fn a_delta_keeps_the_fraction_the_variation_store_computed() {
123        // These locations land between whole design units. Rounding is left
124        // to a caller, and implementations disagree on how, so the value
125        // reported here keeps what the store worked out.
126        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
127        let hvar = font.hvar().unwrap();
128        let gid = GlyphId::new(1);
129        for (coord, expected) in [(-1.0, -113.0), (-0.75, -84.75), (-0.5, -56.5)] {
130            let coords = [F2Dot14::from_f32(coord)];
131            assert_eq!(
132                hvar.advance_delta(gid, &coords),
133                Some(F48Dot16::from_f64(expected)),
134                "at {coord}"
135            );
136        }
137    }
138
139    #[test]
140    fn a_default_location_moves_nothing() {
141        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
142        let hvar = font.hvar().unwrap();
143        let gid = GlyphId::new(1);
144        assert_eq!(hvar.advance_delta(gid, &[]), Some(F48Dot16::ZERO));
145        assert_eq!(hvar.lsb_delta(gid, &[]), Some(F48Dot16::ZERO));
146        assert_eq!(hvar.rsb_delta(gid, &[]), Some(F48Dot16::ZERO));
147    }
148
149    /// A cached scalar has to give the same delta as computing one.
150    ///
151    /// The cache is an optimization, so a full slice and a short one both
152    /// have to agree with the plain call. Regions are dense, so only what
153    /// `compute_scalars` wrote may be passed back; there is no mark for an
154    /// entry it did not reach.
155    #[test]
156    fn a_cached_scalar_changes_nothing() {
157        use types::Fixed;
158
159        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
160        let hvar = font.hvar().unwrap();
161        let coords = [F2Dot14::from_f32(-0.75)];
162
163        let mut buf = [Fixed::ZERO; 32];
164        let written = hvar.compute_scalars(&coords, &mut buf);
165        assert!(written > 0, "the font varies, so something must be written");
166
167        for gid in (0..font.maxp().unwrap().num_glyphs()).map(GlyphId::from) {
168            let plain = hvar.advance_delta(gid, &coords);
169            for (name, scalars) in [
170                ("full", &buf[..written]),
171                ("partial", &buf[..written / 2]),
172                ("empty", &[][..]),
173            ] {
174                assert_eq!(
175                    hvar.advance_delta_with_scalars(gid, &coords, scalars),
176                    plain,
177                    "{name} cache disagreed at {gid}"
178                );
179            }
180        }
181    }
182
183    /// `compute_scalars` reports how many entries it wrote, and writes no
184    /// more than the slice holds.
185    #[test]
186    fn compute_scalars_reports_what_it_wrote() {
187        use types::Fixed;
188        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
189        let hvar = font.hvar().unwrap();
190        let coords = [F2Dot14::from_f32(-0.75)];
191        let mut big = [Fixed::ZERO; 32];
192        let all = hvar.compute_scalars(&coords, &mut big);
193        // A slice too small for the store takes what fits and says so.
194        let mut small = [Fixed::ZERO; 1];
195        assert_eq!(hvar.compute_scalars(&coords, &mut small), all.min(1));
196        assert_eq!(small[0], big[0]);
197        // And nothing is written into an empty slice.
198        assert_eq!(hvar.compute_scalars(&coords, &mut []), 0);
199    }
200
201    #[test]
202    fn a_mapping_the_font_does_not_state_is_absent() {
203        // This font maps advances but neither side bearing.
204        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
205        let hvar = font.hvar().unwrap();
206        let gid = GlyphId::new(1);
207        let coords = [F2Dot14::from_f32(-0.75)];
208        assert!(hvar.advance_delta(gid, &coords).is_some());
209        assert_eq!(hvar.lsb_delta(gid, &coords), None);
210        assert_eq!(hvar.rsb_delta(gid, &coords), None);
211    }
212
213    #[test]
214    fn advance_deltas() {
215        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
216        let hvar = font.hvar().unwrap();
217        let gid_a = GlyphId::new(1);
218        // The odd quarters are what the store computed; the rounded form of
219        // this accessor reported -85 and -56 for them.
220        for (coord, expected) in [
221            (-1.0, -113.0),
222            (-0.75, -84.75),
223            (-0.5, -56.5),
224            (0.0, 0.0),
225            (0.5, 29.5),
226            (1.0, 59.0),
227        ] {
228            assert_eq!(
229                hvar.advance_delta(gid_a, &[F2Dot14::from_f32(coord)]),
230                Some(F48Dot16::from_f64(expected)),
231                "at {coord}"
232            );
233        }
234    }
235
236    #[test]
237    fn advance_deltas_from_hvar_with_truncated_adv_index_map() {
238        let font = FontRef::new(font_test_data::HVAR_WITH_TRUNCATED_ADVANCE_INDEX_MAP).unwrap();
239        let maxp = font.maxp().unwrap();
240        let num_glyphs = maxp.num_glyphs();
241        let hvar = font.hvar().unwrap();
242        let Ok(DeltaSetIndexMap::Format0(adv_index_map)) = hvar.advance_width_mapping().unwrap()
243        else {
244            panic!("Expected DeltaSetIndexMap::Format0 for hvar.advance_width_mapping()");
245        };
246        assert!(adv_index_map.map_count() < num_glyphs);
247        assert_eq!(num_glyphs, 24);
248        assert_eq!(adv_index_map.map_count(), 15);
249        let last_mapped_gid = adv_index_map.map_count() - 1;
250        // We expect the last 10 glyphs to have the same advance width delta as
251        // the last mapped glyph. Crucially, the accessor should answer for
252        // them rather than reporting the glyph as out of bounds.
253        for idx in last_mapped_gid..num_glyphs {
254            let gid = GlyphId::new(idx as _);
255            assert_eq!(
256                hvar.advance_delta(gid, &[F2Dot14::from_f32(1.0)]),
257                Some(F48Dot16::from_f64(100.0))
258            );
259        }
260    }
261}