Skip to main content

read_fonts/tables/
morx.rs

1//! The [morx (Extended Glyph Metamorphosis)](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6morx.html) table.
2
3use super::aat::{safe_read_array_to_end, ExtendedStateTable, LookupU16, StateTableParts};
4
5include!("../../generated/generated_morx.rs");
6
7impl VarSize for Chain<'_> {
8    type Size = u32;
9
10    fn read_len_at(data: FontData, pos: usize) -> Option<usize> {
11        // Size in a chain is second field beyond 4 byte `defaultFlags`
12        data.read_at::<u32>(pos.checked_add(u32::RAW_BYTE_LEN)?)
13            .ok()
14            .map(|size| size as usize)
15    }
16}
17
18impl VarSize for Subtable<'_> {
19    type Size = u32;
20
21    fn read_len_at(data: FontData, pos: usize) -> Option<usize> {
22        // The default implementation assumes that the length field itself
23        // is not included in the total size which is not true of this
24        // table.
25        data.read_at::<u32>(pos).ok().map(|size| size as usize)
26    }
27}
28
29impl<'a> Subtable<'a> {
30    /// If true, this subtable will process glyphs in logical order (or reverse
31    /// logical order, depending on the value of bit 0x80000000).
32    #[inline]
33    pub fn is_logical(&self) -> bool {
34        self.coverage() & 0x10000000 != 0
35    }
36
37    /// If true, this subtable will be applied to both horizontal and vertical
38    /// text (i.e. the state of bit 0x80000000 is ignored).
39    #[inline]
40    pub fn is_all_directions(&self) -> bool {
41        self.coverage() & 0x20000000 != 0
42    }
43
44    /// If true, this subtable will process glyphs in descending order.
45    /// Otherwise, it will process the glyphs in ascending order.
46    #[inline]
47    pub fn is_backwards(&self) -> bool {
48        self.coverage() & 0x40000000 != 0
49    }
50
51    /// If true, this subtable will only be applied to vertical text.
52    /// Otherwise, this subtable will only be applied to horizontal
53    /// text.
54    #[inline]
55    pub fn is_vertical(&self) -> bool {
56        self.coverage() & 0x80000000 != 0
57    }
58
59    /// Returns an enum representing the actual subtable data.
60    pub fn kind(&self) -> Result<SubtableKind<'a>, ReadError> {
61        SubtableKind::read_with_args(FontData::new(self.data()), self.coverage())
62    }
63}
64
65/// The various `morx` subtable formats.
66#[derive(Clone)]
67pub enum SubtableKind<'a> {
68    Rearrangement(ExtendedStateTable<'a>),
69    Contextual(ContextualSubtable<'a>),
70    Ligature(LigatureSubtable<'a>),
71    NonContextual(LookupU16<'a>),
72    Insertion(InsertionSubtable<'a>),
73}
74
75impl ReadArgs for SubtableKind<'_> {
76    type Args = u32;
77}
78
79impl<'a> FontRead<'a> for SubtableKind<'a> {
80    fn read_with_args(data: FontData<'a>, args: Self::Args) -> Result<Self, ReadError> {
81        // Format is low byte of coverage
82        let format = args & 0xFF;
83        match format {
84            0 => Ok(Self::Rearrangement(ExtendedStateTable::read(data)?)),
85            1 => Ok(Self::Contextual(ContextualSubtable::read(data)?)),
86            2 => Ok(Self::Ligature(LigatureSubtable::read(data)?)),
87            // 3 is reserved
88            4 => Ok(Self::NonContextual(LookupU16::read(data)?)),
89            5 => Ok(Self::Insertion(InsertionSubtable::read(data)?)),
90            _ => Err(ReadError::InvalidFormat(format as _)),
91        }
92    }
93}
94
95/// Pre-resolved, lifetime-free description of a `morx` subtable's layout,
96/// captured once with [SubtableKind::parts] and replayed cheaply with
97/// [SubtableKind::from_parts] to avoid re-reading headers on every
98/// application.
99#[derive(Clone, Copy, Debug, Default)]
100pub struct SubtableParts {
101    /// Low byte of coverage: the subtable format (0/1/2/4/5).
102    pub format: u8,
103    pub state: StateTableParts,
104    /// Format-dependent extra offsets read after the state table header:
105    /// contextual: [lookups_offset, 0, 0]; ligature: [lig_action, component,
106    /// ligature]; insertion: [glyphs_offset, 0, 0]; others unused.
107    pub extra: [u32; 3],
108}
109
110impl<'a> SubtableKind<'a> {
111    /// Captures the offsets needed to rebuild this subtable kind from the
112    /// same data with [SubtableKind::from_parts].
113    pub fn parts(data: FontData<'a>, coverage: u32) -> Result<SubtableParts, ReadError> {
114        let format = (coverage & 0xFF) as u8;
115        let mut parts = SubtableParts {
116            format,
117            ..Default::default()
118        };
119        if format == 4 {
120            // Non-contextual: a bare lookup table, no state header.
121            return Ok(parts);
122        }
123        parts.state = StateTableParts::read(data)?;
124        let mut cursor = data.cursor();
125        cursor.advance_by(ExtendedStateTable::<()>::HEADER_LEN);
126        match format {
127            1 | 5 => {
128                parts.extra[0] = cursor.read::<u32>()?;
129            }
130            2 => {
131                parts.extra[0] = cursor.read::<u32>()?;
132                parts.extra[1] = cursor.read::<u32>()?;
133                parts.extra[2] = cursor.read::<u32>()?;
134            }
135            _ => {}
136        }
137        Ok(parts)
138    }
139
140    /// Rebuilds the subtable kind from `data` and offsets previously
141    /// captured with [SubtableKind::parts] on the same data.
142    #[inline]
143    pub fn from_parts(data: FontData<'a>, parts: &SubtableParts) -> Result<Self, ReadError> {
144        match parts.format {
145            0 => Ok(Self::Rearrangement(ExtendedStateTable::from_parts(
146                data,
147                &parts.state,
148            )?)),
149            1 => {
150                let state_table = ExtendedStateTable::from_parts(data, &parts.state)?;
151                let offset = parts.extra[0] as usize;
152                let end = data.len();
153                let offsets_data = FontData::new(data.read_array(offset..end)?);
154                let raw_offsets: &[BigEndian<Offset32>] = safe_read_array_to_end(&offsets_data, 0)?;
155                Ok(Self::Contextual(ContextualSubtable {
156                    state_table,
157                    lookup_offsets: raw_offsets,
158                    lookup_data: offsets_data,
159                }))
160            }
161            2 => Ok(Self::Ligature(LigatureSubtable {
162                state_table: ExtendedStateTable::from_parts(data, &parts.state)?,
163                ligature_actions: safe_read_array_to_end(&data, parts.extra[0] as usize)?,
164                components: safe_read_array_to_end(&data, parts.extra[1] as usize)?,
165                ligatures: safe_read_array_to_end(&data, parts.extra[2] as usize)?,
166            })),
167            4 => Ok(Self::NonContextual(LookupU16::read(data)?)),
168            5 => Ok(Self::Insertion(InsertionSubtable {
169                state_table: ExtendedStateTable::from_parts(data, &parts.state)?,
170                glyphs: safe_read_array_to_end(&data, parts.extra[0] as usize)?,
171            })),
172            _ => Err(ReadError::InvalidFormat(parts.format as _)),
173        }
174    }
175}
176
177/// Contextual glyph substitution subtable.
178#[derive(Clone)]
179pub struct ContextualSubtable<'a> {
180    pub state_table: ExtendedStateTable<'a, ContextualEntryData>,
181    // The lookups are kept as raw offsets so the subtable stays covariant
182    // over its lifetime.
183    lookup_offsets: &'a [BigEndian<Offset32>],
184    lookup_data: FontData<'a>,
185}
186
187impl<'a> ContextualSubtable<'a> {
188    /// Returns the substitution lookup at `index`, as selected by an action
189    /// in the state table, or `None` if it can't be read.
190    pub fn lookup(&self, index: usize) -> Option<LookupU16<'a>> {
191        self.lookup_offsets
192            .get(index)?
193            .get()
194            .resolve(self.lookup_data)
195            .ok()
196    }
197}
198
199impl ReadArgs for ContextualSubtable<'_> {
200    type Args = ();
201}
202
203impl<'a> FontRead<'a> for ContextualSubtable<'a> {
204    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
205        let state_table = ExtendedStateTable::read(data)?;
206        let mut cursor = data.cursor();
207        cursor.advance_by(ExtendedStateTable::<()>::HEADER_LEN);
208        let offset = cursor.read::<u32>()? as usize;
209        let end = data.len();
210        let offsets_data = FontData::new(data.read_array(offset..end)?);
211        let raw_offsets: &[BigEndian<Offset32>] = safe_read_array_to_end(&offsets_data, 0)?;
212        Ok(Self {
213            state_table,
214            lookup_offsets: raw_offsets,
215            lookup_data: offsets_data,
216        })
217    }
218}
219
220/// Ligature glyph substitution subtable.
221#[derive(Clone)]
222pub struct LigatureSubtable<'a> {
223    pub state_table: ExtendedStateTable<'a, BigEndian<u16>>,
224    /// Contains the set of ligature stack actions, one for each state.
225    pub ligature_actions: &'a [BigEndian<u32>],
226    /// Array of component indices which are summed to determine the index
227    /// of the final ligature glyph.
228    pub components: &'a [BigEndian<u16>],
229    /// Output ligature glyphs.
230    pub ligatures: &'a [BigEndian<GlyphId16>],
231}
232
233impl ReadArgs for LigatureSubtable<'_> {
234    type Args = ();
235}
236
237impl<'a> FontRead<'a> for LigatureSubtable<'a> {
238    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
239        let state_table = ExtendedStateTable::read(data)?;
240        let mut cursor = data.cursor();
241        cursor.advance_by(ExtendedStateTable::<()>::HEADER_LEN);
242        // None of these arrays have associated sizes, so we just read until
243        // the end of the data.
244        let lig_action_offset = cursor.read::<u32>()? as usize;
245        let component_offset = cursor.read::<u32>()? as usize;
246        let ligature_offset = cursor.read::<u32>()? as usize;
247        let ligature_actions = safe_read_array_to_end(&data, lig_action_offset)?;
248        let components = safe_read_array_to_end(&data, component_offset)?;
249        let ligatures = safe_read_array_to_end(&data, ligature_offset)?;
250        Ok(Self {
251            state_table,
252            ligature_actions,
253            components,
254            ligatures,
255        })
256    }
257}
258
259/// Insertion glyph substitution subtable.
260#[derive(Clone)]
261pub struct InsertionSubtable<'a> {
262    pub state_table: ExtendedStateTable<'a, InsertionEntryData>,
263    /// Insertion glyph table. The index and count of glyphs to insert is
264    /// determined by the state machine.
265    pub glyphs: &'a [BigEndian<GlyphId16>],
266}
267
268impl ReadArgs for InsertionSubtable<'_> {
269    type Args = ();
270}
271
272impl<'a> FontRead<'a> for InsertionSubtable<'a> {
273    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
274        let state_table = ExtendedStateTable::read(data)?;
275        let mut cursor = data.cursor();
276        cursor.advance_by(ExtendedStateTable::<()>::HEADER_LEN);
277        let glyphs_offset = cursor.read::<u32>()? as usize;
278        let glyphs = safe_read_array_to_end(&data, glyphs_offset)?;
279        Ok(Self {
280            state_table,
281            glyphs,
282        })
283    }
284}
285
286#[cfg(test)]
287// Literal bytes are grouped according to layout in the spec
288// for readabiity
289#[allow(clippy::unusual_byte_groupings)]
290mod tests {
291    use super::*;
292    use crate::{FontRef, TableProvider};
293
294    #[test]
295    fn parse_chain_flags_features() {
296        let font = FontRef::new(font_test_data::morx::FOUR).unwrap();
297        let morx = font.morx().unwrap();
298        let chain = morx.chains().iter().next().unwrap().unwrap();
299        assert_eq!(chain.default_flags(), 1);
300        let feature = chain.features()[0];
301        assert_eq!(feature.feature_type(), 4);
302        assert_eq!(feature.feature_settings(), 0);
303        assert_eq!(feature.enable_flags(), 1);
304        assert_eq!(feature.disable_flags(), 0xFFFFFFFF);
305    }
306
307    #[test]
308    fn parse_rearrangement() {
309        let font = FontRef::new(font_test_data::morx::FOUR).unwrap();
310        let morx = font.morx().unwrap();
311        let chain = morx.chains().iter().next().unwrap().unwrap();
312        let subtable = chain.subtables().iter().next().unwrap().unwrap();
313        assert_eq!(subtable.coverage(), 0x20_0000_00);
314        // Rearrangement is just a state table
315        let SubtableKind::Rearrangement(_kind) = subtable.kind().unwrap() else {
316            panic!("expected rearrangement subtable!");
317        };
318    }
319
320    #[test]
321    fn parse_contextual() {
322        let font = FontRef::new(font_test_data::morx::EIGHTEEN).unwrap();
323        let morx = font.morx().unwrap();
324        let chain = morx.chains().iter().next().unwrap().unwrap();
325        let subtable = chain.subtables().iter().next().unwrap().unwrap();
326        assert_eq!(subtable.coverage(), 0x20_0000_01);
327        let SubtableKind::Contextual(kind) = subtable.kind().unwrap() else {
328            panic!("expected contextual subtable!");
329        };
330        let lookup = kind.lookup(0).unwrap();
331        let expected = [None, None, Some(7u16), Some(8), Some(9), Some(10), Some(11)];
332        let values = (0..7).map(|gid| lookup.value(gid).ok()).collect::<Vec<_>>();
333        assert_eq!(values, &expected);
334    }
335
336    /// Parsed subtables can be kept beside the data they borrow, which
337    /// needs them to be covariant.
338    #[test]
339    fn subtable_kind_is_covariant() {
340        fn shorten<'a>(kind: SubtableKind<'static>) -> SubtableKind<'a> {
341            kind
342        }
343        let _ = shorten;
344    }
345
346    #[test]
347    fn parse_ligature() {
348        let font = FontRef::new(font_test_data::morx::FORTY_ONE).unwrap();
349        let morx = font.morx().unwrap();
350        let chain = morx.chains().iter().next().unwrap().unwrap();
351        let subtable = chain.subtables().iter().next().unwrap().unwrap();
352        assert_eq!(subtable.coverage(), 0x20_0000_02);
353        let SubtableKind::Ligature(kind) = subtable.kind().unwrap() else {
354            panic!("expected ligature subtable!");
355        };
356        let expected_actions = [0x3FFFFFFE, 0xBFFFFFFE];
357        // Note, we limit the number of elements because the arrays do not
358        // have specified lengths in the table
359        let actions = kind
360            .ligature_actions
361            .iter()
362            .take(2)
363            .map(|action| action.get())
364            .collect::<Vec<_>>();
365        assert_eq!(actions, &expected_actions);
366        let expected_components = [0u16, 1, 0, 0];
367        // See above explanation for the limit
368        let components = kind
369            .components
370            .iter()
371            .take(4)
372            .map(|comp| comp.get())
373            .collect::<Vec<_>>();
374        assert_eq!(components, &expected_components);
375        let expected_ligatures = [GlyphId16::new(5), GlyphId16::new(6)];
376        let ligatures = kind
377            .ligatures
378            .iter()
379            .map(|gid| gid.get())
380            .collect::<Vec<_>>();
381        assert_eq!(ligatures, &expected_ligatures);
382    }
383
384    #[test]
385    fn parse_non_contextual() {
386        let font = FontRef::new(font_test_data::morx::ONE).unwrap();
387        let morx = font.morx().unwrap();
388        let chain = morx.chains().iter().next().unwrap().unwrap();
389        let subtable = chain.subtables().iter().next().unwrap().unwrap();
390        assert_eq!(subtable.coverage(), 0x20_0000_04);
391        let SubtableKind::NonContextual(kind) = subtable.kind().unwrap() else {
392            panic!("expected non-contextual subtable!");
393        };
394        let expected_values = [None, None, Some(5u16), None, Some(7)];
395        let values = (0..5).map(|gid| kind.value(gid).ok()).collect::<Vec<_>>();
396        assert_eq!(values, &expected_values);
397    }
398
399    #[test]
400    fn parse_insertion() {
401        let font = FontRef::new(font_test_data::morx::THIRTY_FOUR).unwrap();
402        let morx = font.morx().unwrap();
403        let chain = morx.chains().iter().next().unwrap().unwrap();
404        let subtable = chain.subtables().iter().next().unwrap().unwrap();
405        assert_eq!(subtable.coverage(), 0x20_0000_05);
406        let SubtableKind::Insertion(kind) = subtable.kind().unwrap() else {
407            panic!("expected insertion subtable!");
408        };
409        let mut expected_glyphs = vec![];
410        for _ in 0..9 {
411            for gid in [3, 2] {
412                expected_glyphs.push(GlyphId16::new(gid));
413            }
414        }
415        assert_eq!(kind.glyphs, &expected_glyphs);
416    }
417}