Skip to main content

f_office_fonts/
script_glyphs.rs

1//! Script glyphs from the `ssty` feature (script style) of the `GSUB` table: the glyphs that a
2//! math font draws in place of a glyph in a script and in a script of a script; and flattened
3//! accents from its `flac` feature, the glyphs that it draws for an accent over a tall base.
4
5use std::collections::HashMap;
6
7use skrifa::raw::tables::gsub::{
8    AlternateSubst, AlternateSubstFormat1, ExtensionSubtable, Gsub, SingleSubst, SubstitutionLookup,
9};
10use skrifa::raw::types::Tag;
11use skrifa::raw::{ReadError, TableProvider};
12
13use crate::ligature::{DEFAULT, feature_lookups};
14use crate::{FontDb, FontId};
15
16const MATH: Tag = Tag::new(b"math");
17const SSTY: Tag = Tag::new(b"ssty");
18const FLAC: Tag = Tag::new(b"flac");
19const DTLS: Tag = Tag::new(b"dtls");
20
21/// One lookup of the `ssty` feature: each glyph that it covers maps to the glyphs that it can
22/// take, the alternates of an alternate substitution in the font's order, or the one glyph of a
23/// single substitution.
24type Lookup = HashMap<u32, Substitute>;
25
26#[derive(Debug)]
27enum Substitute {
28    /// A single substitution, the same glyph at every level.
29    Single(u32),
30    /// An alternate substitution: the alternate at the index of the level, from 1.
31    Alternates(Vec<u32>),
32}
33
34/// The level of a part of an equation that takes the font's script glyphs: a script, or a
35/// script of a script. The `ssty` feature takes the value 1 for a script and 2 for a script of
36/// a script, which is the index of the alternate, from 1.
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
38pub enum ScriptLevel {
39    /// A script, in script style.
40    Script,
41    /// A script of a script, in script-script style.
42    ScriptOfScript,
43}
44
45impl ScriptLevel {
46    /// The index of the alternate that an alternate substitution takes, from 0.
47    fn alternate(self) -> usize {
48        match self {
49            Self::Script => 0,
50            Self::ScriptOfScript => 1,
51        }
52    }
53}
54
55/// The lookups of the `ssty` feature, or of the `flac` or `dtls` feature, in lookup order.
56#[derive(Debug, Default)]
57pub(crate) struct ScriptGlyphs(Vec<Lookup>);
58
59impl ScriptGlyphs {
60    /// Reads the single and alternate lookups of the `ssty` feature of the default language of
61    /// the math script, or of the default script when the font has no math script, inside
62    /// extension lookups too. A font without a `GSUB` table or with a malformed one has none.
63    pub(crate) fn read(gsub: Result<Gsub<'_>, ReadError>) -> Self {
64        gsub.and_then(|gsub| feature(&gsub, SSTY))
65            .unwrap_or_default()
66    }
67
68    /// Reads the lookups of the feature `tag`, such as `flac`, as [`Self::read`] reads those of
69    /// `ssty`.
70    fn read_feature(gsub: Result<Gsub<'_>, ReadError>, tag: Tag) -> Self {
71        gsub.and_then(|gsub| feature(&gsub, tag))
72            .unwrap_or_default()
73    }
74
75    /// The glyph in place of `glyph` at `level`, after each lookup in turn, as `GSUB` applies
76    /// them; `None` when no lookup changes it. An alternate substitution takes the alternate of
77    /// the level, and changes nothing when it has fewer.
78    fn apply(&self, glyph: u32, level: ScriptLevel) -> Option<u32> {
79        let index = level.alternate();
80        let mut current = glyph;
81        for lookup in &self.0 {
82            current = match lookup.get(&current) {
83                Some(Substitute::Single(substitute)) => *substitute,
84                Some(Substitute::Alternates(alternates)) => {
85                    alternates.get(index).copied().unwrap_or(current)
86                }
87                None => current,
88            };
89        }
90        (current != glyph).then_some(current)
91    }
92}
93
94fn feature(gsub: &Gsub<'_>, tag: Tag) -> Result<ScriptGlyphs, ReadError> {
95    let indices = feature_lookups(
96        &gsub.script_list()?,
97        &gsub.feature_list()?,
98        tag,
99        &[MATH, DEFAULT],
100    )?;
101    let list = gsub.lookup_list()?;
102    let mut lookups = Vec::new();
103    for index in indices {
104        let mut map = Lookup::new();
105        read_lookup(&list.lookups().get(usize::from(index))?, &mut map)?;
106        if !map.is_empty() {
107            lookups.push(map);
108        }
109    }
110    Ok(ScriptGlyphs(lookups))
111}
112
113/// Adds the substitutions of each single and alternate subtable of a lookup with 16-bit glyph
114/// IDs, inside extension subtables too, after those of its earlier subtables, because the
115/// subtables of a lookup are tried in order until one applies. Other lookup types add none.
116fn read_lookup(lookup: &SubstitutionLookup<'_>, map: &mut Lookup) -> Result<(), ReadError> {
117    match lookup {
118        SubstitutionLookup::Single(lookup) => {
119            for subtable in lookup.subtables().iter() {
120                read_single(&subtable?, map)?;
121            }
122        }
123        SubstitutionLookup::Alternate(lookup) => {
124            for subtable in lookup.subtables().iter() {
125                read_alternates(&subtable?, map)?;
126            }
127        }
128        SubstitutionLookup::Extension(lookup) => {
129            for subtable in lookup.subtables().iter() {
130                match subtable? {
131                    ExtensionSubtable::Single(extension) => {
132                        read_single(&extension.extension()?, map)?;
133                    }
134                    ExtensionSubtable::Alternate(extension) => {
135                        read_alternates(&extension.extension()?, map)?;
136                    }
137                    _ => {}
138                }
139            }
140        }
141        _ => {}
142    }
143    Ok(())
144}
145
146fn read_single(table: &SingleSubst<'_>, map: &mut Lookup) -> Result<(), ReadError> {
147    match table {
148        SingleSubst::Format1(table) => {
149            let delta = i64::from(table.delta_glyph_id());
150            for glyph in table.coverage()?.iter() {
151                let from = glyph.to_u32();
152                // The sum is taken modulo 65536, as the specification says.
153                let to = (i64::from(from) + delta).rem_euclid(65_536);
154                if let Ok(to) = u32::try_from(to) {
155                    map.entry(from).or_insert(Substitute::Single(to));
156                }
157            }
158        }
159        SingleSubst::Format2(table) => {
160            let substitutes = table.substitute_glyph_ids();
161            for (glyph, substitute) in table.coverage()?.iter().zip(substitutes) {
162                map.entry(glyph.to_u32())
163                    .or_insert(Substitute::Single(u32::from(substitute.get().to_u16())));
164            }
165        }
166        // Formats 3 and 4 use 24-bit glyph IDs, which are not implemented here.
167        _ => {}
168    }
169    Ok(())
170}
171
172fn read_alternates(table: &AlternateSubst<'_>, map: &mut Lookup) -> Result<(), ReadError> {
173    // Format 2 uses 24-bit glyph IDs, which are not implemented here.
174    if let AlternateSubst::Format1(table) = table {
175        read_alternates_16(table, map)?;
176    }
177    Ok(())
178}
179
180fn read_alternates_16(
181    table: &AlternateSubstFormat1<'_>,
182    map: &mut Lookup,
183) -> Result<(), ReadError> {
184    let sets = table.alternate_sets();
185    for (index, glyph) in table.coverage()?.iter().enumerate() {
186        let alternates = sets
187            .get(index)?
188            .alternate_glyph_ids()
189            .iter()
190            .map(|g| u32::from(g.get().to_u16()))
191            .collect();
192        map.entry(glyph.to_u32())
193            .or_insert(Substitute::Alternates(alternates));
194    }
195    Ok(())
196}
197
198impl FontDb {
199    /// Returns the script glyph of a glyph: the glyph that the font's `ssty` feature puts in its
200    /// place at `level`. The lookups come from the default language of the math script, or of
201    /// the default script, and apply in lookup order; an alternate substitution takes the first
202    /// alternate for a script and the second for a script of a script.
203    ///
204    /// Returns `None` for an unknown face, a font without the feature, and a glyph that the
205    /// feature does not change.
206    #[must_use]
207    pub fn script_glyph(&self, id: FontId, glyph: u32, level: ScriptLevel) -> Option<u32> {
208        let face = self.face(id)?;
209        let font = face.font()?;
210        face.script_glyphs
211            .get_or_init(|| ScriptGlyphs::read(font.tables().gsub()))
212            .apply(glyph, level)
213    }
214
215    /// Returns the flattened form of an accent's glyph: the glyph that the font's `flac`
216    /// feature puts in its place, over a base taller than the `MATH` table's
217    /// `FlattenedAccentBaseHeight`. The lookups come as for [`Self::script_glyph`].
218    ///
219    /// Returns `None` for an unknown face, a font without the feature, and a glyph that the
220    /// feature does not change.
221    #[must_use]
222    pub fn flattened_accent(&self, id: FontId, glyph: u32) -> Option<u32> {
223        let face = self.face(id)?;
224        let font = face.font()?;
225        face.flattened_accents
226            .get_or_init(|| ScriptGlyphs::read_feature(font.tables().gsub(), FLAC))
227            .apply(glyph, ScriptLevel::Script)
228    }
229
230    /// Returns the dotless form of a letter's glyph: the glyph that the font's `dtls` feature
231    /// puts in its place, under an accent. The lookups come as for [`Self::script_glyph`].
232    ///
233    /// Returns `None` for an unknown face, a font without the feature, and a glyph that the
234    /// feature does not change.
235    #[must_use]
236    pub fn dotless_form(&self, id: FontId, glyph: u32) -> Option<u32> {
237        let face = self.face(id)?;
238        let font = face.font()?;
239        face.dotless_forms
240            .get_or_init(|| ScriptGlyphs::read_feature(font.tables().gsub(), DTLS))
241            .apply(glyph, ScriptLevel::Script)
242    }
243}
244
245#[cfg(test)]
246mod tests;