f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! Script glyphs from the `ssty` feature (script style) of the `GSUB` table: the glyphs that a
//! math font draws in place of a glyph in a script and in a script of a script; and flattened
//! accents from its `flac` feature, the glyphs that it draws for an accent over a tall base.

use std::collections::HashMap;

use skrifa::raw::tables::gsub::{
    AlternateSubst, AlternateSubstFormat1, ExtensionSubtable, Gsub, SingleSubst, SubstitutionLookup,
};
use skrifa::raw::types::Tag;
use skrifa::raw::{ReadError, TableProvider};

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

const MATH: Tag = Tag::new(b"math");
const SSTY: Tag = Tag::new(b"ssty");
const FLAC: Tag = Tag::new(b"flac");
const DTLS: Tag = Tag::new(b"dtls");

/// One lookup of the `ssty` feature: each glyph that it covers maps to the glyphs that it can
/// take, the alternates of an alternate substitution in the font's order, or the one glyph of a
/// single substitution.
type Lookup = HashMap<u32, Substitute>;

#[derive(Debug)]
enum Substitute {
    /// A single substitution, the same glyph at every level.
    Single(u32),
    /// An alternate substitution: the alternate at the index of the level, from 1.
    Alternates(Vec<u32>),
}

/// The level of a part of an equation that takes the font's script glyphs: a script, or a
/// script of a script. The `ssty` feature takes the value 1 for a script and 2 for a script of
/// a script, which is the index of the alternate, from 1.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ScriptLevel {
    /// A script, in script style.
    Script,
    /// A script of a script, in script-script style.
    ScriptOfScript,
}

impl ScriptLevel {
    /// The index of the alternate that an alternate substitution takes, from 0.
    fn alternate(self) -> usize {
        match self {
            Self::Script => 0,
            Self::ScriptOfScript => 1,
        }
    }
}

/// The lookups of the `ssty` feature, or of the `flac` or `dtls` feature, in lookup order.
#[derive(Debug, Default)]
pub(crate) struct ScriptGlyphs(Vec<Lookup>);

impl ScriptGlyphs {
    /// Reads the single and alternate lookups of the `ssty` feature of the default language of
    /// the math script, or of the default script when the font has no math script, inside
    /// extension lookups too. A font without a `GSUB` table or with a malformed one has none.
    pub(crate) fn read(gsub: Result<Gsub<'_>, ReadError>) -> Self {
        gsub.and_then(|gsub| feature(&gsub, SSTY))
            .unwrap_or_default()
    }

    /// Reads the lookups of the feature `tag`, such as `flac`, as [`Self::read`] reads those of
    /// `ssty`.
    fn read_feature(gsub: Result<Gsub<'_>, ReadError>, tag: Tag) -> Self {
        gsub.and_then(|gsub| feature(&gsub, tag))
            .unwrap_or_default()
    }

    /// The glyph in place of `glyph` at `level`, after each lookup in turn, as `GSUB` applies
    /// them; `None` when no lookup changes it. An alternate substitution takes the alternate of
    /// the level, and changes nothing when it has fewer.
    fn apply(&self, glyph: u32, level: ScriptLevel) -> Option<u32> {
        let index = level.alternate();
        let mut current = glyph;
        for lookup in &self.0 {
            current = match lookup.get(&current) {
                Some(Substitute::Single(substitute)) => *substitute,
                Some(Substitute::Alternates(alternates)) => {
                    alternates.get(index).copied().unwrap_or(current)
                }
                None => current,
            };
        }
        (current != glyph).then_some(current)
    }
}

fn feature(gsub: &Gsub<'_>, tag: Tag) -> Result<ScriptGlyphs, ReadError> {
    let indices = feature_lookups(
        &gsub.script_list()?,
        &gsub.feature_list()?,
        tag,
        &[MATH, DEFAULT],
    )?;
    let list = gsub.lookup_list()?;
    let mut lookups = Vec::new();
    for index in indices {
        let mut map = Lookup::new();
        read_lookup(&list.lookups().get(usize::from(index))?, &mut map)?;
        if !map.is_empty() {
            lookups.push(map);
        }
    }
    Ok(ScriptGlyphs(lookups))
}

/// Adds the substitutions of each single and alternate subtable of a lookup with 16-bit glyph
/// IDs, inside extension subtables too, after those of its earlier subtables, because the
/// subtables of a lookup are tried in order until one applies. Other lookup types add none.
fn read_lookup(lookup: &SubstitutionLookup<'_>, map: &mut Lookup) -> Result<(), ReadError> {
    match lookup {
        SubstitutionLookup::Single(lookup) => {
            for subtable in lookup.subtables().iter() {
                read_single(&subtable?, map)?;
            }
        }
        SubstitutionLookup::Alternate(lookup) => {
            for subtable in lookup.subtables().iter() {
                read_alternates(&subtable?, map)?;
            }
        }
        SubstitutionLookup::Extension(lookup) => {
            for subtable in lookup.subtables().iter() {
                match subtable? {
                    ExtensionSubtable::Single(extension) => {
                        read_single(&extension.extension()?, map)?;
                    }
                    ExtensionSubtable::Alternate(extension) => {
                        read_alternates(&extension.extension()?, map)?;
                    }
                    _ => {}
                }
            }
        }
        _ => {}
    }
    Ok(())
}

fn read_single(table: &SingleSubst<'_>, map: &mut Lookup) -> Result<(), ReadError> {
    match table {
        SingleSubst::Format1(table) => {
            let delta = i64::from(table.delta_glyph_id());
            for glyph in table.coverage()?.iter() {
                let from = glyph.to_u32();
                // The sum is taken modulo 65536, as the specification says.
                let to = (i64::from(from) + delta).rem_euclid(65_536);
                if let Ok(to) = u32::try_from(to) {
                    map.entry(from).or_insert(Substitute::Single(to));
                }
            }
        }
        SingleSubst::Format2(table) => {
            let substitutes = table.substitute_glyph_ids();
            for (glyph, substitute) in table.coverage()?.iter().zip(substitutes) {
                map.entry(glyph.to_u32())
                    .or_insert(Substitute::Single(u32::from(substitute.get().to_u16())));
            }
        }
        // Formats 3 and 4 use 24-bit glyph IDs, which are not implemented here.
        _ => {}
    }
    Ok(())
}

fn read_alternates(table: &AlternateSubst<'_>, map: &mut Lookup) -> Result<(), ReadError> {
    // Format 2 uses 24-bit glyph IDs, which are not implemented here.
    if let AlternateSubst::Format1(table) = table {
        read_alternates_16(table, map)?;
    }
    Ok(())
}

fn read_alternates_16(
    table: &AlternateSubstFormat1<'_>,
    map: &mut Lookup,
) -> Result<(), ReadError> {
    let sets = table.alternate_sets();
    for (index, glyph) in table.coverage()?.iter().enumerate() {
        let alternates = sets
            .get(index)?
            .alternate_glyph_ids()
            .iter()
            .map(|g| u32::from(g.get().to_u16()))
            .collect();
        map.entry(glyph.to_u32())
            .or_insert(Substitute::Alternates(alternates));
    }
    Ok(())
}

impl FontDb {
    /// Returns the script glyph of a glyph: the glyph that the font's `ssty` feature puts in its
    /// place at `level`. The lookups come from the default language of the math script, or of
    /// the default script, and apply in lookup order; an alternate substitution takes the first
    /// alternate for a script and the second for a script of a script.
    ///
    /// Returns `None` for an unknown face, a font without the feature, and a glyph that the
    /// feature does not change.
    #[must_use]
    pub fn script_glyph(&self, id: FontId, glyph: u32, level: ScriptLevel) -> Option<u32> {
        let face = self.face(id)?;
        let font = face.font()?;
        face.script_glyphs
            .get_or_init(|| ScriptGlyphs::read(font.tables().gsub()))
            .apply(glyph, level)
    }

    /// Returns the flattened form of an accent's glyph: the glyph that the font's `flac`
    /// feature puts in its place, over a base taller than the `MATH` table's
    /// `FlattenedAccentBaseHeight`. The lookups come as for [`Self::script_glyph`].
    ///
    /// Returns `None` for an unknown face, a font without the feature, and a glyph that the
    /// feature does not change.
    #[must_use]
    pub fn flattened_accent(&self, id: FontId, glyph: u32) -> Option<u32> {
        let face = self.face(id)?;
        let font = face.font()?;
        face.flattened_accents
            .get_or_init(|| ScriptGlyphs::read_feature(font.tables().gsub(), FLAC))
            .apply(glyph, ScriptLevel::Script)
    }

    /// Returns the dotless form of a letter's glyph: the glyph that the font's `dtls` feature
    /// puts in its place, under an accent. The lookups come as for [`Self::script_glyph`].
    ///
    /// Returns `None` for an unknown face, a font without the feature, and a glyph that the
    /// feature does not change.
    #[must_use]
    pub fn dotless_form(&self, id: FontId, glyph: u32) -> Option<u32> {
        let face = self.face(id)?;
        let font = face.font()?;
        face.dotless_forms
            .get_or_init(|| ScriptGlyphs::read_feature(font.tables().gsub(), DTLS))
            .apply(glyph, ScriptLevel::Script)
    }
}

#[cfg(test)]
mod tests;