Skip to main content

f_office_fonts/
kerning.rs

1//! Pair kerning from the `kern` feature of `GPOS`, or else from the `kern` table.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use skrifa::GlyphId;
6use skrifa::font::Font;
7use skrifa::raw::tables::gpos::{
8    ExtensionSubtable, Gpos, PairPos, PairPosFormat2, PositionLookup, PositionLookupList,
9};
10use skrifa::raw::tables::kern::SubtableKind;
11use skrifa::raw::types::Tag;
12use skrifa::raw::{ReadError, TableProvider};
13
14use crate::face::Face;
15use crate::ligature::{DEFAULT, LATIN, feature_lookups};
16use crate::{FontDb, FontId};
17
18const KERN: Tag = Tag::new(b"kern");
19
20/// Where a face's pair kerning comes from, as [`FontDb::kerning`] reads it.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum KerningSource {
23    /// The `kern` feature of `GPOS`: a GPOS-kerned face, which may have a `kern` table too.
24    Gpos,
25    /// The `kern` table, when the face has one: a face without the `kern` feature of `GPOS`,
26    /// a legacy-kern face when it has the table. An unknown face counts here too.
27    KernTable,
28}
29
30impl FontDb {
31    /// Returns where the pair kerning of a face comes from: [`KerningSource::Gpos`] when its
32    /// `GPOS` table has a `kern` feature for the default language of the Latin script, or of
33    /// the default script, with at least one lookup, and [`KerningSource::KernTable`]
34    /// otherwise.
35    #[must_use]
36    pub fn kerning_source(&self, id: FontId) -> KerningSource {
37        match self.face(id).and_then(kern_lookups) {
38            Some(lookups) if !lookups.is_empty() => KerningSource::Gpos,
39            _ => KerningSource::KernTable,
40        }
41    }
42
43    /// Returns the kerning between two glyphs in font units. A negative value moves the right
44    /// glyph closer.
45    ///
46    /// When the font's `GPOS` table has a `kern` feature for the default language of the Latin
47    /// script, or of the default script, the value is the sum of the horizontal advance
48    /// adjustments that its pair lookups give the left glyph, in lookup order, where the first
49    /// subtable of a lookup that covers the pair applies. Otherwise it is the sum of the
50    /// horizontal subtables of the font's `kern` table.
51    ///
52    /// Returns 0 for an unknown face, a font without either table or a pair that the font does
53    /// not list. Cross-stream and state machine subtables of the `kern` table, the lookup
54    /// flags of `GPOS` and its contextual lookups are ignored.
55    #[must_use]
56    pub fn kerning(&self, id: FontId, left: u32, right: u32) -> i32 {
57        self.kerning_from(id, left, right, self.kerning_source(id))
58    }
59
60    /// Returns the kerning between two glyphs in font units from one kerning source of the
61    /// face, whatever its other source holds: the `kern` feature of `GPOS` as
62    /// [`FontDb::kerning`] reads it, 0 when the face has none, or the sum of the horizontal
63    /// subtables of the `kern` table, 0 when the face has none.
64    #[must_use]
65    pub fn kerning_from(&self, id: FontId, left: u32, right: u32, source: KerningSource) -> i32 {
66        let Some(face) = self.face(id) else {
67            return 0;
68        };
69        let (left, right) = (GlyphId::new(left), GlyphId::new(right));
70        match source {
71            KerningSource::KernTable => kern_table(face, left, right),
72            KerningSource::Gpos => {
73                let Some((font, lookups)) = face.font().zip(kern_lookups(face)) else {
74                    return 0;
75                };
76                if lookups.is_empty() {
77                    return 0;
78                }
79                font.tables()
80                    .gpos()
81                    .and_then(|gpos| gpos_kerning(&gpos, lookups, left, right))
82                    .unwrap_or(0)
83            }
84        }
85    }
86
87    /// Returns whether a face has a `kern` table with a horizontal subtable of pairs (format 0,
88    /// 2 or 3), whatever its `GPOS` table holds.
89    #[must_use]
90    pub fn has_kern_table(&self, id: FontId) -> bool {
91        let Some(font) = self.face(id).and_then(Face::font) else {
92            return false;
93        };
94        font.tables().kern().is_ok_and(|kern| {
95            kern.subtables().flatten().any(|s| {
96                s.is_horizontal()
97                    && !s.is_cross_stream()
98                    && !matches!(s.kind(), Ok(SubtableKind::Format1(_)) | Err(_))
99            })
100        })
101    }
102}
103
104/// The indices of the pair lookups of the `kern` feature of `GPOS` in `face`, read once, or
105/// none; `None` when the face's file did not load.
106fn kern_lookups(face: &Face) -> Option<&[u16]> {
107    let font = face.font()?;
108    let lookups = face
109        .kern_lookups
110        .get_or_init(|| gpos_kern_lookups(font).unwrap_or_default());
111    Some(lookups)
112}
113
114/// The indices of the pair lookups of the `kern` feature of `GPOS`, or none.
115fn gpos_kern_lookups(font: &Font) -> Result<Vec<u16>, ReadError> {
116    let gpos = font.tables().gpos()?;
117    feature_lookups(
118        &gpos.script_list()?,
119        &gpos.feature_list()?,
120        KERN,
121        &[LATIN, DEFAULT],
122    )
123}
124
125fn kern_table(face: &Face, left: GlyphId, right: GlyphId) -> i32 {
126    let Some(Ok(kern)) = face.font().map(|font| font.tables().kern()) else {
127        return 0;
128    };
129    kern.subtables()
130        .flatten()
131        .filter(|s| s.is_horizontal() && !s.is_cross_stream())
132        .filter_map(|s| match s.kind().ok()? {
133            SubtableKind::Format0(t) => t.kerning(left, right),
134            SubtableKind::Format2(t) => t.kerning(left, right),
135            SubtableKind::Format3(t) => t.kerning(left, right),
136            SubtableKind::Format1(_) => None,
137        })
138        .sum()
139}
140
141fn gpos_kerning(
142    gpos: &Gpos<'_>,
143    lookups: &[u16],
144    left: GlyphId,
145    right: GlyphId,
146) -> Result<i32, ReadError> {
147    let list = gpos.lookup_list()?;
148    let mut total = 0;
149    for index in lookups {
150        if let Some(value) = pair_subtables(&list, *index)?
151            .iter()
152            .find_map(|subtable| pair_value(subtable, left, right))
153        {
154            total += value;
155        }
156    }
157    Ok(total)
158}
159
160/// The pair subtables of the lookup at `index`, also those inside extension subtables, in
161/// order; none for a lookup of another type.
162fn pair_subtables<'a>(
163    list: &PositionLookupList<'a>,
164    index: u16,
165) -> Result<Vec<PairPos<'a>>, ReadError> {
166    Ok(match list.lookups().get(usize::from(index))? {
167        PositionLookup::Pair(lookup) => lookup.subtables().iter().flatten().collect(),
168        PositionLookup::Extension(lookup) => lookup
169            .subtables()
170            .iter()
171            .flatten()
172            .filter_map(|subtable| match subtable {
173                ExtensionSubtable::Pair(pair) => pair.extension().ok(),
174                _ => None,
175            })
176            .collect(),
177        _ => Vec::new(),
178    })
179}
180
181impl FontDb {
182    /// Returns the pairs of `glyphs` to which a face's kerning gives a value other than 0 in
183    /// its tables: the pairs of the pair lookups of the `kern` feature of `GPOS`, whatever
184    /// the subtable that covers each pair first, and the pairs of the format 0 subtables of
185    /// the `kern` table. [`FontDb::kerning_from`] then gives each pair's value. A pair outside
186    /// the list has the kerning 0 from both sources, except in a `kern` table subtable of
187    /// format 2 or 3, which this does not list.
188    pub(crate) fn listed_kerning_pairs(
189        &self,
190        id: FontId,
191        glyphs: &BTreeSet<u32>,
192    ) -> BTreeSet<(u32, u32)> {
193        let mut pairs = BTreeSet::new();
194        let Some(face) = self.face(id) else {
195            return pairs;
196        };
197        if let Some((font, lookups)) = face.font().zip(kern_lookups(face)) {
198            let gpos = font.tables().gpos();
199            let list = gpos.and_then(|gpos| gpos.lookup_list());
200            for subtable in list.iter().flat_map(|list| {
201                lookups
202                    .iter()
203                    .filter_map(|&index| pair_subtables(list, index).ok())
204                    .flatten()
205            }) {
206                listed_gpos_pairs(&subtable, glyphs, &mut pairs);
207            }
208        }
209        listed_kern_table_pairs(face, glyphs, &mut pairs);
210        pairs
211    }
212}
213
214/// Adds the pairs of `glyphs` with a horizontal advance adjustment other than 0 in one pair
215/// subtable of `GPOS` to `pairs`.
216fn listed_gpos_pairs(
217    subtable: &PairPos<'_>,
218    glyphs: &BTreeSet<u32>,
219    pairs: &mut BTreeSet<(u32, u32)>,
220) {
221    match subtable {
222        PairPos::Format1(table) => {
223            let (Ok(coverage), sets) = (table.coverage(), table.pair_sets()) else {
224                return;
225            };
226            for (left, set) in coverage.iter().zip(sets.iter()) {
227                let Ok(set) = set else { continue };
228                let rights = set
229                    .pair_value_records()
230                    .iter()
231                    .flatten()
232                    .filter(|record| record.value_record1().x_advance().unwrap_or(0) != 0);
233                for record in rights {
234                    let pair = (left.to_u32(), GlyphId::from(record.second_glyph()).to_u32());
235                    if glyphs.contains(&pair.0) && glyphs.contains(&pair.1) {
236                        pairs.insert(pair);
237                    }
238                }
239            }
240        }
241        PairPos::Format2(table) => listed_class_pairs(table, glyphs, pairs),
242        // The kerning reader takes no value from the other formats.
243        _ => {}
244    }
245}
246
247/// Adds the pairs of `glyphs` that a class-based pair subtable of `GPOS` gives a horizontal
248/// advance adjustment other than 0 to `pairs`. The second glyphs of class 0 are every glyph of
249/// `glyphs` that the second class definition does not name.
250fn listed_class_pairs(
251    table: &PairPosFormat2<'_>,
252    glyphs: &BTreeSet<u32>,
253    pairs: &mut BTreeSet<(u32, u32)>,
254) {
255    let (Ok(coverage), Ok(firsts), Ok(seconds)) =
256        (table.coverage(), table.class_def1(), table.class_def2())
257    else {
258        return;
259    };
260    let mut by_class: BTreeMap<u16, Vec<u32>> = BTreeMap::new();
261    for &glyph in glyphs {
262        if let Ok(class) = u16::try_from(seconds.get(GlyphId::new(glyph))) {
263            by_class.entry(class).or_default().push(glyph);
264        }
265    }
266    for left in coverage
267        .iter()
268        .map(GlyphId::to_u32)
269        .filter(|g| glyphs.contains(g))
270    {
271        let Ok(first) = u16::try_from(firsts.get(GlyphId::new(left))) else {
272            continue;
273        };
274        for (&second, rights) in &by_class {
275            let adjusts = table
276                .value_record_refs(first, second)
277                .is_some_and(|[record, _]| record.x_advance().unwrap_or(0) != 0);
278            if adjusts {
279                pairs.extend(rights.iter().map(|&right| (left, right)));
280            }
281        }
282    }
283}
284
285/// Adds the pairs of `glyphs` of the horizontal format 0 subtables of a face's `kern` table
286/// to `pairs`.
287fn listed_kern_table_pairs(face: &Face, glyphs: &BTreeSet<u32>, pairs: &mut BTreeSet<(u32, u32)>) {
288    let Some(Ok(kern)) = face.font().map(|font| font.tables().kern()) else {
289        return;
290    };
291    let subtables = kern
292        .subtables()
293        .flatten()
294        .filter(|s| s.is_horizontal() && !s.is_cross_stream());
295    for subtable in subtables {
296        let Ok(SubtableKind::Format0(table)) = subtable.kind() else {
297            continue;
298        };
299        for pair in table.pairs() {
300            let found = (
301                u32::from(pair.left().to_u16()),
302                u32::from(pair.right().to_u16()),
303            );
304            if pair.value() != 0 && glyphs.contains(&found.0) && glyphs.contains(&found.1) {
305                pairs.insert(found);
306            }
307        }
308    }
309}
310
311/// The advance adjustment that a pair subtable gives the left glyph, or `None` when the
312/// subtable does not cover the pair.
313fn pair_value(subtable: &PairPos<'_>, left: GlyphId, right: GlyphId) -> Option<i32> {
314    match subtable {
315        PairPos::Format1(table) => {
316            let index = table.coverage().ok()?.get(left)?;
317            let set = table.pair_sets().get(usize::try_from(index).ok()?).ok()?;
318            let records = set.pair_value_records();
319            let record = records
320                .iter()
321                .flatten()
322                .find(|record| GlyphId::from(record.second_glyph()) == right)?;
323            Some(i32::from(record.value_record1().x_advance().unwrap_or(0)))
324        }
325        PairPos::Format2(table) => {
326            table.coverage().ok()?.get(left)?;
327            let class1 = u16::try_from(table.class_def1().ok()?.get(left)).ok()?;
328            let class2 = u16::try_from(table.class_def2().ok()?.get(right)).ok()?;
329            let [first, _] = table.value_record_refs(class1, class2)?;
330            Some(i32::from(first.x_advance().unwrap_or(0)))
331        }
332        _ => None,
333    }
334}