Skip to main content

read_fonts/tables/
hmtx.rs

1//! The [hmtx (Horizontal Metrics)](https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx) table
2
3include!("../../generated/generated_hmtx.rs");
4
5use crate::{table_provider::prefer_extended, TableProvider};
6
7macro_rules! impl_hmtx_lookup {
8    ($table:ident) => {
9        impl $table<'_> {
10            /// Returns the advance width for the given glyph identifier.
11            pub fn advance(&self, glyph_id: GlyphId) -> Option<u16> {
12                advance(self.h_metrics(), glyph_id)
13            }
14
15            /// Returns the left side bearing for the given glyph identifier.
16            pub fn side_bearing(&self, glyph_id: GlyphId) -> Option<i16> {
17                side_bearing(self.h_metrics(), self.left_side_bearings(), glyph_id)
18            }
19        }
20    };
21}
22
23impl_hmtx_lookup!(Hmtx);
24impl_hmtx_lookup!(HmtxExtended);
25
26pub(crate) fn advance(metrics: &[LongMetric], glyph_id: GlyphId) -> Option<u16> {
27    metrics
28        .get(glyph_id.to_u32() as usize)
29        .or_else(|| metrics.last())
30        .map(|metric| metric.advance())
31}
32
33pub(crate) fn side_bearing(
34    metrics: &[LongMetric],
35    side_bearings: &[BigEndian<i16>],
36    glyph_id: GlyphId,
37) -> Option<i16> {
38    let ix = glyph_id.to_u32() as usize;
39    metrics
40        .get(ix)
41        .map(|metric| metric.side_bearing())
42        .or_else(|| {
43            side_bearings
44                .get(ix.saturating_sub(metrics.len()))
45                .map(|sb| sb.get())
46        })
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52    use crate::{FontRef, TableProvider};
53    use font_test_data::{be_buffer, bebuffer::BeBuffer};
54
55    /// Test case where "long metric" array is short
56    #[test]
57    fn trimmed_advances() {
58        let font = FontRef::new(font_test_data::CBDT).unwrap();
59        let hmtx = font.hmtx().unwrap();
60        assert!(
61            !hmtx.left_side_bearings().is_empty(),
62            "if this fails then the test is no longer accurate"
63        );
64        let expected_lsbs = [100, 0, 100, 0];
65        for (i, lsb) in expected_lsbs.into_iter().enumerate() {
66            let gid = GlyphId::new(i as _);
67            // All glyphs have 800 advance width
68            assert_eq!(hmtx.advance(gid), Some(800));
69            assert_eq!(hmtx.side_bearing(gid), Some(lsb));
70        }
71    }
72
73    #[test]
74    fn missing_left_side_bearings() {
75        let hmtx_data = be_buffer! {
76            500u16, 50u16, // advance width + lsb, glyph 0
77            600u16, 60u16 // advance width + lsb, glyph 1
78        };
79
80        let hmtx = Hmtx::read(hmtx_data.data().into(), 2).unwrap();
81
82        assert_eq!(hmtx.advance(GlyphId::new(0)), Some(500));
83        assert_eq!(hmtx.side_bearing(GlyphId::new(0)), Some(50));
84
85        assert_eq!(hmtx.advance(GlyphId::new(1)), Some(600));
86        assert_eq!(hmtx.side_bearing(GlyphId::new(1)), Some(60));
87
88        assert_eq!(hmtx.advance(GlyphId::new(2)), Some(600));
89        assert_eq!(hmtx.side_bearing(GlyphId::new(2)), None);
90
91        assert_eq!(hmtx.advance(GlyphId::new(3)), Some(600));
92        assert_eq!(hmtx.side_bearing(GlyphId::new(3)), None);
93    }
94
95    #[test]
96    fn metrics() {
97        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
98        let hmtx = font.hmtx().unwrap();
99        let expected = [(908, 100), (1336, 29), (1336, 29), (633, 57)];
100        for (i, (advance, lsb)) in expected.into_iter().enumerate() {
101            let gid = GlyphId::new(i as _);
102            assert_eq!(hmtx.advance(gid), Some(advance));
103            assert_eq!(hmtx.side_bearing(gid), Some(lsb));
104        }
105    }
106}
107
108/// Unvaried per-glyph records from HMTX/hmtx or VMTX/vmtx.
109///
110/// Both tables hold the same records, so one type reads either, and which
111/// direction it describes is fixed when it is read.
112///
113/// Obtain these through [`TableProvider::h_glyph_metric_records`] or
114/// [`TableProvider::v_glyph_metric_records`]. Uppercase tables are selected
115/// independently of the outlines, with the original tables used if they are
116/// absent.
117/// Nothing here depends on a location, so every location shares one parse.
118#[derive(Clone, Default)]
119pub struct GlyphMetricRecords<'a> {
120    pub(crate) metrics: &'a [LongMetric],
121    /// Bare side bearings after the last long metric.
122    pub(crate) bearings: &'a [BigEndian<i16>],
123}
124
125/// The records of one table, whichever the font would select.
126macro_rules! glyph_metric_records_from {
127    ($($table:ty => $metrics:ident, $bearings:ident;)*) => {
128        $(
129            impl<'a> From<$table> for GlyphMetricRecords<'a> {
130                fn from(table: $table) -> Self {
131                    Self {
132                        metrics: table.$metrics(),
133                        bearings: table.$bearings(),
134                    }
135                }
136            }
137        )*
138    };
139}
140
141glyph_metric_records_from! {
142    Hmtx<'a> => h_metrics, left_side_bearings;
143    HmtxExtended<'a> => h_metrics, left_side_bearings;
144    super::vmtx::Vmtx<'a> => v_metrics, top_side_bearings;
145    super::vmtx::VmtxExtended<'a> => v_metrics, top_side_bearings;
146}
147
148impl<'a> GlyphMetricRecords<'a> {
149    pub(crate) fn read_horizontal(
150        tables: &(impl TableProvider<'a> + ?Sized),
151    ) -> Result<Self, ReadError> {
152        prefer_extended(
153            tables.hmtx_extended().map(Self::from),
154            Tag::new(b"HMTX"),
155            || tables.hmtx().map(Self::from),
156        )
157    }
158
159    pub(crate) fn read_vertical(
160        tables: &(impl TableProvider<'a> + ?Sized),
161    ) -> Result<Self, ReadError> {
162        prefer_extended(
163            tables.vmtx_extended().map(Self::from),
164            Tag::new(b"VMTX"),
165            || tables.vmtx().map(Self::from),
166        )
167    }
168
169    /// Returns the paired advance and side-bearing records.
170    pub fn long_metrics(&self) -> &'a [LongMetric] {
171        self.metrics
172    }
173
174    /// Returns the side bearings after the last long metric record.
175    pub fn side_bearings(&self) -> &'a [BigEndian<i16>] {
176        self.bearings
177    }
178
179    /// Returns the unvaried advance, repeating the last record when needed.
180    /// This does not check the font's glyph count.
181    pub fn advance(&self, glyph: GlyphId) -> Option<u16> {
182        advance(self.metrics, glyph)
183    }
184
185    /// Returns the unvaried leading side bearing for a glyph.
186    pub fn side_bearing(&self, glyph: GlyphId) -> Option<i16> {
187        side_bearing(self.metrics, self.bearings, glyph)
188    }
189}