Skip to main content

f_office_fonts/
ligature.rs

1//! Standard ligatures from the `GSUB` table.
2
3use std::collections::HashMap;
4
5use skrifa::raw::tables::gsub::{
6    ExtensionSubtable, Gsub, LigatureSubst, LigatureSubstFormat1, SubstitutionLookup,
7};
8use skrifa::raw::tables::layout::{FeatureList, LangSys, ScriptList};
9use skrifa::raw::types::{BigEndian, Tag};
10use skrifa::raw::{ReadError, TableProvider};
11
12use crate::{FontDb, FontId};
13
14/// One ligature in a sequence of glyphs.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct Ligature {
17    /// The index of the first glyph that the ligature replaces.
18    pub start: usize,
19    /// The number of glyphs that it replaces, at least 2.
20    pub len: usize,
21    /// The ligature glyph.
22    pub glyph: u32,
23}
24
25/// One ligature lookup: the first glyph of a sequence maps to the rest of each sequence that
26/// starts with it and the ligature of that sequence, in the order of the font.
27type Lookup = HashMap<u32, Vec<(Vec<u32>, u32)>>;
28
29/// The ligature lookups of the `liga` feature, in lookup order.
30#[derive(Debug, Default)]
31pub(crate) struct Lookups(Vec<Lookup>);
32
33impl Lookups {
34    /// Reads the lookups of the `liga` feature of the default language of the Latin script, or
35    /// of the default script when the font has no Latin script. A font without a `GSUB` table
36    /// or with a malformed one has none.
37    pub(crate) fn read(gsub: Result<Gsub<'_>, ReadError>) -> Self {
38        gsub.and_then(|gsub| liga_lookups(&gsub))
39            .unwrap_or_default()
40    }
41
42    /// The glyph sequences that the lookups join, each with its first glyph, in lookup order.
43    fn sequences(&self) -> Vec<Vec<u32>> {
44        let mut found = Vec::new();
45        for lookup in &self.0 {
46            let mut firsts: Vec<&u32> = lookup.keys().collect();
47            firsts.sort_unstable();
48            for &first in firsts {
49                for (rest, _) in lookup.get(&first).map_or(&[][..], Vec::as_slice) {
50                    found.push(std::iter::once(first).chain(rest.iter().copied()).collect());
51                }
52            }
53        }
54        found
55    }
56
57    /// Applies each lookup in turn to the whole sequence, as `GSUB` does. A later lookup can
58    /// join the glyphs that an earlier one made.
59    ///
60    /// Each lookup walks the items once: the read index goes past each item that it keeps and
61    /// past all the items of each ligature that it makes, and the write index, which is never
62    /// after it, keeps the item or the ligature in place.
63    fn apply(&self, glyphs: &[u32]) -> Vec<Ligature> {
64        // Each item is a glyph with the number of original glyphs that it stands for.
65        let mut items: Vec<(u32, usize)> = glyphs.iter().map(|&g| (g, 1)).collect();
66        for lookup in &self.0 {
67            let (mut read, mut write) = (0, 0);
68            while let Some(&item) = items.get(read) {
69                let (kept, taken) = match matching(lookup, &items, read) {
70                    Some((rest, glyph)) => {
71                        let joined = items.get(read..=read + rest).unwrap_or_default();
72                        ((glyph, joined.iter().map(|&(_, n)| n).sum()), rest + 1)
73                    }
74                    None => (item, 1),
75                };
76                if let Some(slot) = items.get_mut(write) {
77                    *slot = kept;
78                }
79                write += 1;
80                read += taken;
81            }
82            items.truncate(write);
83        }
84        let mut found = Vec::new();
85        let mut start = 0;
86        for (glyph, len) in items {
87            if len > 1 {
88                found.push(Ligature { start, len, glyph });
89            }
90            start += len;
91        }
92        found
93    }
94}
95
96/// The first ligature of `lookup` whose glyphs follow at `index`, with the number of glyphs
97/// after the first that it takes.
98fn matching(lookup: &Lookup, items: &[(u32, usize)], index: usize) -> Option<(usize, u32)> {
99    let (first, _) = items.get(index)?;
100    let following = items.get(index + 1..)?;
101    lookup.get(first)?.iter().find_map(|(rest, glyph)| {
102        let fits = rest.len() <= following.len()
103            && rest
104                .iter()
105                .zip(following)
106                .all(|(want, (have, _))| want == have);
107        fits.then_some((rest.len(), *glyph))
108    })
109}
110
111pub(crate) const LATIN: Tag = Tag::new(b"latn");
112pub(crate) const DEFAULT: Tag = Tag::new(b"DFLT");
113const LIGA: Tag = Tag::new(b"liga");
114
115fn liga_lookups(gsub: &Gsub<'_>) -> Result<Lookups, ReadError> {
116    let indices = feature_lookups(
117        &gsub.script_list()?,
118        &gsub.feature_list()?,
119        LIGA,
120        &[LATIN, DEFAULT],
121    )?;
122    let list = gsub.lookup_list()?;
123    let mut lookups = Vec::new();
124    for index in indices {
125        let mut map = Lookup::new();
126        for subtable in ligature_subtables(&list.lookups().get(usize::from(index))?)? {
127            read_subtable(&subtable, &mut map)?;
128        }
129        if !map.is_empty() {
130            lookups.push(map);
131        }
132    }
133    Ok(Lookups(lookups))
134}
135
136/// The indices of the lookups of a feature in the default language of the first of `scripts`
137/// that the table has, in lookup order. A `GSUB` or `GPOS` table gives the lists.
138pub(crate) fn feature_lookups(
139    scripts: &ScriptList<'_>,
140    features: &FeatureList<'_>,
141    tag: Tag,
142    order: &[Tag],
143) -> Result<Vec<u16>, ReadError> {
144    let Some(lang_sys) = default_lang_sys(scripts, order)? else {
145        return Ok(Vec::new());
146    };
147    let mut indices: Vec<u16> = Vec::new();
148    for index in lang_sys.feature_indices() {
149        let Some(record) = features.feature_records().get(usize::from(index.get())) else {
150            continue;
151        };
152        if record.feature_tag() == tag {
153            let feature = record.feature(features.offset_data())?;
154            indices.extend(feature.lookup_list_indices().iter().map(BigEndian::get));
155        }
156    }
157    indices.sort_unstable();
158    indices.dedup();
159    Ok(indices)
160}
161
162/// The default language system of the first of `order` that the script list has.
163fn default_lang_sys<'a>(
164    scripts: &ScriptList<'a>,
165    order: &[Tag],
166) -> Result<Option<LangSys<'a>>, ReadError> {
167    let records = scripts.script_records();
168    let record = order
169        .iter()
170        .find_map(|tag| records.iter().find(|r| r.script_tag() == *tag));
171    let Some(record) = record else {
172        return Ok(None);
173    };
174    record
175        .script(scripts.offset_data())?
176        .default_lang_sys()
177        .transpose()
178}
179
180/// The ligature subtables of a lookup, inside extension subtables too. Other lookup types
181/// have none.
182fn ligature_subtables<'a>(
183    lookup: &SubstitutionLookup<'a>,
184) -> Result<Vec<LigatureSubstFormat1<'a>>, ReadError> {
185    let mut found = Vec::new();
186    match lookup {
187        SubstitutionLookup::Ligature(lookup) => {
188            for subtable in lookup.subtables().iter() {
189                if let LigatureSubst::Format1(table) = subtable? {
190                    found.push(table);
191                }
192            }
193        }
194        SubstitutionLookup::Extension(lookup) => {
195            for subtable in lookup.subtables().iter() {
196                if let ExtensionSubtable::Ligature(extension) = subtable?
197                    && let LigatureSubst::Format1(table) = extension.extension()?
198                {
199                    found.push(table);
200                }
201            }
202        }
203        _ => {}
204    }
205    Ok(found)
206}
207
208/// Adds the ligatures of one subtable after those of the earlier subtables of the same lookup,
209/// because the subtables of a lookup are tried in order until one applies.
210fn read_subtable(table: &LigatureSubstFormat1<'_>, map: &mut Lookup) -> Result<(), ReadError> {
211    let sets = table.ligature_sets();
212    for (index, first) in table.coverage()?.iter().enumerate() {
213        let ligatures = map.entry(first.to_u32()).or_default();
214        for ligature in sets.get(index)?.ligatures().iter() {
215            let ligature = ligature?;
216            let rest = ligature
217                .component_glyph_ids()
218                .iter()
219                .map(|g| g.get().to_u32())
220                .collect();
221            ligatures.push((rest, ligature.ligature_glyph().to_u32()));
222        }
223    }
224    Ok(())
225}
226
227impl FontDb {
228    /// Returns the standard ligatures (`liga`) of a sequence of glyphs from one face, in order
229    /// and without overlaps. The lookups come from the default language of the Latin script,
230    /// or of the default script, and apply in lookup order. Lookup flags are not read, so a
231    /// mark between two glyphs keeps them apart.
232    ///
233    /// Returns none for an unknown face or a font without a `GSUB` table.
234    #[must_use]
235    pub fn ligatures(&self, id: FontId, glyphs: &[u32]) -> Vec<Ligature> {
236        self.ligature_lookups(id)
237            .map_or_else(Vec::new, |lookups| lookups.apply(glyphs))
238    }
239
240    /// Returns the glyph sequences that the standard ligatures of a face join, as
241    /// [`FontDb::ligatures`] reads them, each with its first glyph.
242    pub(crate) fn ligature_sequences(&self, id: FontId) -> Vec<Vec<u32>> {
243        self.ligature_lookups(id)
244            .map_or_else(Vec::new, Lookups::sequences)
245    }
246
247    /// The standard ligature lookups of a face, read once; `None` for an unknown face or a
248    /// file that did not load.
249    fn ligature_lookups(&self, id: FontId) -> Option<&Lookups> {
250        let face = self.face(id)?;
251        let font = face.font()?;
252        Some(
253            face.ligatures
254                .get_or_init(|| Lookups::read(font.tables().gsub())),
255        )
256    }
257}
258
259#[cfg(test)]
260mod tests;