f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! Pair kerning from the `kern` feature of `GPOS`, or else from the `kern` table.

use std::collections::{BTreeMap, BTreeSet};

use skrifa::GlyphId;
use skrifa::font::Font;
use skrifa::raw::tables::gpos::{
    ExtensionSubtable, Gpos, PairPos, PairPosFormat2, PositionLookup, PositionLookupList,
};
use skrifa::raw::tables::kern::SubtableKind;
use skrifa::raw::types::Tag;
use skrifa::raw::{ReadError, TableProvider};

use crate::face::Face;
use crate::ligature::{DEFAULT, LATIN, feature_lookups};
use crate::{FontDb, FontId};

const KERN: Tag = Tag::new(b"kern");

/// Where a face's pair kerning comes from, as [`FontDb::kerning`] reads it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KerningSource {
    /// The `kern` feature of `GPOS`: a GPOS-kerned face, which may have a `kern` table too.
    Gpos,
    /// The `kern` table, when the face has one: a face without the `kern` feature of `GPOS`,
    /// a legacy-kern face when it has the table. An unknown face counts here too.
    KernTable,
}

impl FontDb {
    /// Returns where the pair kerning of a face comes from: [`KerningSource::Gpos`] when its
    /// `GPOS` table has a `kern` feature for the default language of the Latin script, or of
    /// the default script, with at least one lookup, and [`KerningSource::KernTable`]
    /// otherwise.
    #[must_use]
    pub fn kerning_source(&self, id: FontId) -> KerningSource {
        match self.face(id).and_then(kern_lookups) {
            Some(lookups) if !lookups.is_empty() => KerningSource::Gpos,
            _ => KerningSource::KernTable,
        }
    }

    /// Returns the kerning between two glyphs in font units. A negative value moves the right
    /// glyph closer.
    ///
    /// When the font's `GPOS` table has a `kern` feature for the default language of the Latin
    /// script, or of the default script, the value is the sum of the horizontal advance
    /// adjustments that its pair lookups give the left glyph, in lookup order, where the first
    /// subtable of a lookup that covers the pair applies. Otherwise it is the sum of the
    /// horizontal subtables of the font's `kern` table.
    ///
    /// Returns 0 for an unknown face, a font without either table or a pair that the font does
    /// not list. Cross-stream and state machine subtables of the `kern` table, the lookup
    /// flags of `GPOS` and its contextual lookups are ignored.
    #[must_use]
    pub fn kerning(&self, id: FontId, left: u32, right: u32) -> i32 {
        self.kerning_from(id, left, right, self.kerning_source(id))
    }

    /// Returns the kerning between two glyphs in font units from one kerning source of the
    /// face, whatever its other source holds: the `kern` feature of `GPOS` as
    /// [`FontDb::kerning`] reads it, 0 when the face has none, or the sum of the horizontal
    /// subtables of the `kern` table, 0 when the face has none.
    #[must_use]
    pub fn kerning_from(&self, id: FontId, left: u32, right: u32, source: KerningSource) -> i32 {
        let Some(face) = self.face(id) else {
            return 0;
        };
        let (left, right) = (GlyphId::new(left), GlyphId::new(right));
        match source {
            KerningSource::KernTable => kern_table(face, left, right),
            KerningSource::Gpos => {
                let Some((font, lookups)) = face.font().zip(kern_lookups(face)) else {
                    return 0;
                };
                if lookups.is_empty() {
                    return 0;
                }
                font.tables()
                    .gpos()
                    .and_then(|gpos| gpos_kerning(&gpos, lookups, left, right))
                    .unwrap_or(0)
            }
        }
    }

    /// Returns whether a face has a `kern` table with a horizontal subtable of pairs (format 0,
    /// 2 or 3), whatever its `GPOS` table holds.
    #[must_use]
    pub fn has_kern_table(&self, id: FontId) -> bool {
        let Some(font) = self.face(id).and_then(Face::font) else {
            return false;
        };
        font.tables().kern().is_ok_and(|kern| {
            kern.subtables().flatten().any(|s| {
                s.is_horizontal()
                    && !s.is_cross_stream()
                    && !matches!(s.kind(), Ok(SubtableKind::Format1(_)) | Err(_))
            })
        })
    }
}

/// The indices of the pair lookups of the `kern` feature of `GPOS` in `face`, read once, or
/// none; `None` when the face's file did not load.
fn kern_lookups(face: &Face) -> Option<&[u16]> {
    let font = face.font()?;
    let lookups = face
        .kern_lookups
        .get_or_init(|| gpos_kern_lookups(font).unwrap_or_default());
    Some(lookups)
}

/// The indices of the pair lookups of the `kern` feature of `GPOS`, or none.
fn gpos_kern_lookups(font: &Font) -> Result<Vec<u16>, ReadError> {
    let gpos = font.tables().gpos()?;
    feature_lookups(
        &gpos.script_list()?,
        &gpos.feature_list()?,
        KERN,
        &[LATIN, DEFAULT],
    )
}

fn kern_table(face: &Face, left: GlyphId, right: GlyphId) -> i32 {
    let Some(Ok(kern)) = face.font().map(|font| font.tables().kern()) else {
        return 0;
    };
    kern.subtables()
        .flatten()
        .filter(|s| s.is_horizontal() && !s.is_cross_stream())
        .filter_map(|s| match s.kind().ok()? {
            SubtableKind::Format0(t) => t.kerning(left, right),
            SubtableKind::Format2(t) => t.kerning(left, right),
            SubtableKind::Format3(t) => t.kerning(left, right),
            SubtableKind::Format1(_) => None,
        })
        .sum()
}

fn gpos_kerning(
    gpos: &Gpos<'_>,
    lookups: &[u16],
    left: GlyphId,
    right: GlyphId,
) -> Result<i32, ReadError> {
    let list = gpos.lookup_list()?;
    let mut total = 0;
    for index in lookups {
        if let Some(value) = pair_subtables(&list, *index)?
            .iter()
            .find_map(|subtable| pair_value(subtable, left, right))
        {
            total += value;
        }
    }
    Ok(total)
}

/// The pair subtables of the lookup at `index`, also those inside extension subtables, in
/// order; none for a lookup of another type.
fn pair_subtables<'a>(
    list: &PositionLookupList<'a>,
    index: u16,
) -> Result<Vec<PairPos<'a>>, ReadError> {
    Ok(match list.lookups().get(usize::from(index))? {
        PositionLookup::Pair(lookup) => lookup.subtables().iter().flatten().collect(),
        PositionLookup::Extension(lookup) => lookup
            .subtables()
            .iter()
            .flatten()
            .filter_map(|subtable| match subtable {
                ExtensionSubtable::Pair(pair) => pair.extension().ok(),
                _ => None,
            })
            .collect(),
        _ => Vec::new(),
    })
}

impl FontDb {
    /// Returns the pairs of `glyphs` to which a face's kerning gives a value other than 0 in
    /// its tables: the pairs of the pair lookups of the `kern` feature of `GPOS`, whatever
    /// the subtable that covers each pair first, and the pairs of the format 0 subtables of
    /// the `kern` table. [`FontDb::kerning_from`] then gives each pair's value. A pair outside
    /// the list has the kerning 0 from both sources, except in a `kern` table subtable of
    /// format 2 or 3, which this does not list.
    pub(crate) fn listed_kerning_pairs(
        &self,
        id: FontId,
        glyphs: &BTreeSet<u32>,
    ) -> BTreeSet<(u32, u32)> {
        let mut pairs = BTreeSet::new();
        let Some(face) = self.face(id) else {
            return pairs;
        };
        if let Some((font, lookups)) = face.font().zip(kern_lookups(face)) {
            let gpos = font.tables().gpos();
            let list = gpos.and_then(|gpos| gpos.lookup_list());
            for subtable in list.iter().flat_map(|list| {
                lookups
                    .iter()
                    .filter_map(|&index| pair_subtables(list, index).ok())
                    .flatten()
            }) {
                listed_gpos_pairs(&subtable, glyphs, &mut pairs);
            }
        }
        listed_kern_table_pairs(face, glyphs, &mut pairs);
        pairs
    }
}

/// Adds the pairs of `glyphs` with a horizontal advance adjustment other than 0 in one pair
/// subtable of `GPOS` to `pairs`.
fn listed_gpos_pairs(
    subtable: &PairPos<'_>,
    glyphs: &BTreeSet<u32>,
    pairs: &mut BTreeSet<(u32, u32)>,
) {
    match subtable {
        PairPos::Format1(table) => {
            let (Ok(coverage), sets) = (table.coverage(), table.pair_sets()) else {
                return;
            };
            for (left, set) in coverage.iter().zip(sets.iter()) {
                let Ok(set) = set else { continue };
                let rights = set
                    .pair_value_records()
                    .iter()
                    .flatten()
                    .filter(|record| record.value_record1().x_advance().unwrap_or(0) != 0);
                for record in rights {
                    let pair = (left.to_u32(), GlyphId::from(record.second_glyph()).to_u32());
                    if glyphs.contains(&pair.0) && glyphs.contains(&pair.1) {
                        pairs.insert(pair);
                    }
                }
            }
        }
        PairPos::Format2(table) => listed_class_pairs(table, glyphs, pairs),
        // The kerning reader takes no value from the other formats.
        _ => {}
    }
}

/// Adds the pairs of `glyphs` that a class-based pair subtable of `GPOS` gives a horizontal
/// advance adjustment other than 0 to `pairs`. The second glyphs of class 0 are every glyph of
/// `glyphs` that the second class definition does not name.
fn listed_class_pairs(
    table: &PairPosFormat2<'_>,
    glyphs: &BTreeSet<u32>,
    pairs: &mut BTreeSet<(u32, u32)>,
) {
    let (Ok(coverage), Ok(firsts), Ok(seconds)) =
        (table.coverage(), table.class_def1(), table.class_def2())
    else {
        return;
    };
    let mut by_class: BTreeMap<u16, Vec<u32>> = BTreeMap::new();
    for &glyph in glyphs {
        if let Ok(class) = u16::try_from(seconds.get(GlyphId::new(glyph))) {
            by_class.entry(class).or_default().push(glyph);
        }
    }
    for left in coverage
        .iter()
        .map(GlyphId::to_u32)
        .filter(|g| glyphs.contains(g))
    {
        let Ok(first) = u16::try_from(firsts.get(GlyphId::new(left))) else {
            continue;
        };
        for (&second, rights) in &by_class {
            let adjusts = table
                .value_record_refs(first, second)
                .is_some_and(|[record, _]| record.x_advance().unwrap_or(0) != 0);
            if adjusts {
                pairs.extend(rights.iter().map(|&right| (left, right)));
            }
        }
    }
}

/// Adds the pairs of `glyphs` of the horizontal format 0 subtables of a face's `kern` table
/// to `pairs`.
fn listed_kern_table_pairs(face: &Face, glyphs: &BTreeSet<u32>, pairs: &mut BTreeSet<(u32, u32)>) {
    let Some(Ok(kern)) = face.font().map(|font| font.tables().kern()) else {
        return;
    };
    let subtables = kern
        .subtables()
        .flatten()
        .filter(|s| s.is_horizontal() && !s.is_cross_stream());
    for subtable in subtables {
        let Ok(SubtableKind::Format0(table)) = subtable.kind() else {
            continue;
        };
        for pair in table.pairs() {
            let found = (
                u32::from(pair.left().to_u16()),
                u32::from(pair.right().to_u16()),
            );
            if pair.value() != 0 && glyphs.contains(&found.0) && glyphs.contains(&found.1) {
                pairs.insert(found);
            }
        }
    }
}

/// The advance adjustment that a pair subtable gives the left glyph, or `None` when the
/// subtable does not cover the pair.
fn pair_value(subtable: &PairPos<'_>, left: GlyphId, right: GlyphId) -> Option<i32> {
    match subtable {
        PairPos::Format1(table) => {
            let index = table.coverage().ok()?.get(left)?;
            let set = table.pair_sets().get(usize::try_from(index).ok()?).ok()?;
            let records = set.pair_value_records();
            let record = records
                .iter()
                .flatten()
                .find(|record| GlyphId::from(record.second_glyph()) == right)?;
            Some(i32::from(record.value_record1().x_advance().unwrap_or(0)))
        }
        PairPos::Format2(table) => {
            table.coverage().ok()?.get(left)?;
            let class1 = u16::try_from(table.class_def1().ok()?.get(left)).ok()?;
            let class2 = u16::try_from(table.class_def2().ok()?.get(right)).ok()?;
            let [first, _] = table.value_record_refs(class1, class2)?;
            Some(i32::from(first.x_advance().unwrap_or(0)))
        }
        _ => None,
    }
}