Skip to main content

read_fonts/tables/
mvar.rs

1//! The [MVAR (Metrics Variation)](https://docs.microsoft.com/en-us/typography/opentype/spec/mvar) table
2
3use super::variations::{DeltaSetIndex, ItemVariationStore};
4use types::F48Dot16;
5
6/// Four-byte tags used to represent particular metric or other values.
7pub mod tags {
8    use font_types::Tag;
9
10    /// Horizontal ascender.
11    pub const HASC: Tag = Tag::new(b"hasc");
12    /// Horizontal descender.
13    pub const HDSC: Tag = Tag::new(b"hdsc");
14    /// Horizontal line gap.
15    pub const HLGP: Tag = Tag::new(b"hlgp");
16
17    /// Horizontal clipping ascent.
18    pub const HCLA: Tag = Tag::new(b"hcla");
19    /// Horizontal clipping descent.
20    pub const HCLD: Tag = Tag::new(b"hcld");
21
22    /// Vertical ascender.
23    pub const VASC: Tag = Tag::new(b"vasc");
24    /// Vertical descender.
25    pub const VDSC: Tag = Tag::new(b"vdsc");
26    /// Vertical line gap.
27    pub const VLGP: Tag = Tag::new(b"vlgp");
28
29    /// Horizontal caret rise.
30    pub const HCRS: Tag = Tag::new(b"hcrs");
31    /// Horizontal caret run.
32    pub const HCRN: Tag = Tag::new(b"hcrn");
33    /// Horizontal caret offset.
34    pub const HCOF: Tag = Tag::new(b"hcof");
35
36    /// Vertical caret rise.
37    pub const VCRS: Tag = Tag::new(b"vcrs");
38    /// Vertical caret run.
39    pub const VCRN: Tag = Tag::new(b"vcrn");
40    /// Vertical caret offset.
41    pub const VCOF: Tag = Tag::new(b"vcof");
42
43    /// X-height.
44    pub const XHGT: Tag = Tag::new(b"xhgt");
45    /// Cap height.
46    pub const CPHT: Tag = Tag::new(b"cpht");
47
48    /// Subscript em x-offset.
49    pub const SBXO: Tag = Tag::new(b"sbxo");
50    /// Subscript em y-offset.
51    pub const SBYO: Tag = Tag::new(b"sbyo");
52    /// Subscript em x-size.
53    pub const SBXS: Tag = Tag::new(b"sbxs");
54    /// Subscript em y-size.
55    pub const SBYS: Tag = Tag::new(b"sbys");
56
57    /// Superscript em x-offset.
58    pub const SPXO: Tag = Tag::new(b"spxo");
59    /// Superscript em y-offset.
60    pub const SPYO: Tag = Tag::new(b"spyo");
61    /// Superscript em x-size.
62    pub const SPXS: Tag = Tag::new(b"spxs");
63    /// Superscript em y-size.
64    pub const SPYS: Tag = Tag::new(b"spys");
65
66    /// Strikeout size.
67    pub const STRS: Tag = Tag::new(b"strs");
68    /// Strikeout offset.
69    pub const STRO: Tag = Tag::new(b"stro");
70
71    /// Underline size.
72    pub const UNDS: Tag = Tag::new(b"unds");
73    /// Underline offset.
74    pub const UNDO: Tag = Tag::new(b"undo");
75
76    /// GaspRange\[0\]
77    pub const GSP0: Tag = Tag::new(b"gsp0");
78    /// GaspRange\[1\]
79    pub const GSP1: Tag = Tag::new(b"gsp1");
80    /// GaspRange\[2\]
81    pub const GSP2: Tag = Tag::new(b"gsp2");
82    /// GaspRange\[3\]
83    pub const GSP3: Tag = Tag::new(b"gsp3");
84    /// GaspRange\[4\]
85    pub const GSP4: Tag = Tag::new(b"gsp4");
86    /// GaspRange\[5\]
87    pub const GSP5: Tag = Tag::new(b"gsp5");
88    /// GaspRange\[6\]
89    pub const GSP6: Tag = Tag::new(b"gsp6");
90    /// GaspRange\[7\]
91    pub const GSP7: Tag = Tag::new(b"gsp7");
92    /// GaspRange\[8\]
93    pub const GSP8: Tag = Tag::new(b"gsp8");
94    /// GaspRange\[9\]
95    pub const GSP9: Tag = Tag::new(b"gsp9");
96}
97
98include!("../../generated/generated_mvar.rs");
99
100/// `MVAR` at one location, with the variation store resolved once.
101///
102/// Prefer this over [`Mvar::metric_delta`] when reading more than one metric;
103/// that resolves the store on every lookup.
104pub struct MvarInstance<'a> {
105    records: &'a [ValueRecord],
106    ivs: ItemVariationStore<'a>,
107    coords: &'a [F2Dot14],
108}
109
110impl<'a> Mvar<'a> {
111    /// Returns the table at a location.
112    ///
113    /// `None` at the default location, where every delta is zero, and for a
114    /// font whose variation store cannot be read.
115    pub fn at(&self, coords: &'a [F2Dot14]) -> Option<MvarInstance<'a>> {
116        if coords.is_empty() {
117            return None;
118        }
119        Some(MvarInstance {
120            records: self.value_records(),
121            ivs: self.item_variation_store()?.ok()?,
122            coords,
123        })
124    }
125}
126
127impl MvarInstance<'_> {
128    /// Returns the delta for a metric, or `None` for one the font does not
129    /// vary.
130    ///
131    /// Tags are in the [`tags`] module. The delta is in design units, added
132    /// to the value the metric's own table holds, and left unrounded so a
133    /// caller can round it its own way.
134    pub fn get(&self, tag: Tag) -> Option<F48Dot16> {
135        let index = self
136            .records
137            .binary_search_by(|record| record.value_tag().cmp(&tag))
138            .ok()?;
139        let record = &self.records[index];
140        self.ivs.compute_delta(
141            DeltaSetIndex {
142                outer: record.delta_set_outer_index(),
143                inner: record.delta_set_inner_index(),
144            },
145            self.coords,
146        )
147    }
148}
149
150impl Mvar<'_> {
151    /// Returns the metric delta for the specified tag and normalized
152    /// variation coordinates. Possible tags are found in the [tags]
153    /// module.
154    ///
155    /// `None` for a metric the font does not vary, and for one it states
156    /// unreadably.
157    pub fn metric_delta(&self, tag: Tag, coords: &[F2Dot14]) -> Option<Fixed> {
158        use std::cmp::Ordering;
159        let records = self.value_records();
160        let mut lo = 0;
161        let mut hi = records.len();
162        while lo < hi {
163            let i = (lo + hi) / 2;
164            let record = &records[i];
165            match tag.cmp(&record.value_tag()) {
166                Ordering::Less => {
167                    hi = i;
168                }
169                Ordering::Greater => {
170                    lo = i + 1;
171                }
172                Ordering::Equal => {
173                    let ivs = self.item_variation_store()?.ok()?;
174                    return Some(Fixed::from_i32(
175                        ivs.compute_delta(
176                            DeltaSetIndex {
177                                outer: record.delta_set_outer_index(),
178                                inner: record.delta_set_inner_index(),
179                            },
180                            coords,
181                        )?
182                        .to_i32(),
183                    ));
184                }
185            }
186        }
187        None
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::{FontRef, TableProvider};
195    use types::F2Dot14;
196
197    /// Twelve axes, and an `MVAR` varying several metrics.
198    const VAR: &[u8] = font_test_data::AMSTELVAR_AVAR2_A;
199
200    fn far() -> [F2Dot14; 12] {
201        [F2Dot14::from_f32(1.0); 12]
202    }
203
204    #[test]
205    fn the_default_location_has_no_instance() {
206        // Every delta is zero there, so there is nothing to resolve.
207        let font = FontRef::new(VAR).unwrap();
208        assert!(font.mvar().unwrap().at(&[]).is_none());
209    }
210
211    #[test]
212    fn an_instance_agrees_with_the_single_metric_accessor() {
213        let font = FontRef::new(VAR).unwrap();
214        let mvar = font.mvar().unwrap();
215        let coords = far();
216        let instance = mvar.at(&coords).expect("a location away from the default");
217        let mut varied = 0;
218        for record in mvar.value_records() {
219            let tag = record.value_tag();
220            let exact = instance.get(tag).expect("a tag the table states");
221            let rounded = mvar.metric_delta(tag, &coords).unwrap();
222            assert_eq!(exact.to_i32(), rounded.to_i32(), "{tag}");
223            varied += (exact != F48Dot16::ZERO) as u32;
224        }
225        assert!(varied > 0, "no metric moved at the far end of every axis");
226    }
227
228    #[test]
229    fn a_tag_the_font_does_not_state_is_absent() {
230        let font = FontRef::new(VAR).unwrap();
231        let mvar = font.mvar().unwrap();
232        let coords = far();
233        let instance = mvar.at(&coords).unwrap();
234        assert!(instance.get(Tag::new(b"zzzz")).is_none());
235    }
236
237    #[test]
238    fn an_instance_keeps_a_fraction_the_single_accessor_drops() {
239        // `metric_delta` reports whole design units; the instance reports
240        // what the variation store computed.
241        let font = FontRef::new(VAR).unwrap();
242        let mvar = font.mvar().unwrap();
243        let coords = [F2Dot14::from_f32(0.37); 12];
244        let instance = mvar.at(&coords).unwrap();
245        let fractional = mvar
246            .value_records()
247            .iter()
248            .filter_map(|record| instance.get(record.value_tag()))
249            .any(|delta| delta.to_bits() & 0xFFFF != 0);
250        assert!(fractional, "no metric delta carried a fraction");
251    }
252}