f-office-fonts 0.3.0

Font database, metrics and outlines.
Documentation
//! Standard ligatures from the `GSUB` table.

use std::collections::HashMap;

use skrifa::raw::tables::gsub::{
    ExtensionSubtable, Gsub, LigatureSubst, LigatureSubstFormat1, SubstitutionLookup,
};
use skrifa::raw::tables::layout::{FeatureList, LangSys, ScriptList};
use skrifa::raw::types::{BigEndian, Tag};
use skrifa::raw::{ReadError, TableProvider};

use crate::{FontDb, FontId};

/// One ligature in a sequence of glyphs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Ligature {
    /// The index of the first glyph that the ligature replaces.
    pub start: usize,
    /// The number of glyphs that it replaces, at least 2.
    pub len: usize,
    /// The ligature glyph.
    pub glyph: u32,
}

/// One ligature lookup: the first glyph of a sequence maps to the rest of each sequence that
/// starts with it and the ligature of that sequence, in the order of the font.
type Lookup = HashMap<u32, Vec<(Vec<u32>, u32)>>;

/// The ligature lookups of the `liga` feature, in lookup order.
#[derive(Debug, Default)]
pub(crate) struct Lookups(Vec<Lookup>);

impl Lookups {
    /// Reads the lookups of the `liga` feature of the default language of the Latin script, or
    /// of the default script when the font has no Latin script. 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| liga_lookups(&gsub))
            .unwrap_or_default()
    }

    /// The glyph sequences that the lookups join, each with its first glyph, in lookup order.
    fn sequences(&self) -> Vec<Vec<u32>> {
        let mut found = Vec::new();
        for lookup in &self.0 {
            let mut firsts: Vec<&u32> = lookup.keys().collect();
            firsts.sort_unstable();
            for &first in firsts {
                for (rest, _) in lookup.get(&first).map_or(&[][..], Vec::as_slice) {
                    found.push(std::iter::once(first).chain(rest.iter().copied()).collect());
                }
            }
        }
        found
    }

    /// Applies each lookup in turn to the whole sequence, as `GSUB` does. A later lookup can
    /// join the glyphs that an earlier one made.
    ///
    /// Each lookup walks the items once: the read index goes past each item that it keeps and
    /// past all the items of each ligature that it makes, and the write index, which is never
    /// after it, keeps the item or the ligature in place.
    fn apply(&self, glyphs: &[u32]) -> Vec<Ligature> {
        // Each item is a glyph with the number of original glyphs that it stands for.
        let mut items: Vec<(u32, usize)> = glyphs.iter().map(|&g| (g, 1)).collect();
        for lookup in &self.0 {
            let (mut read, mut write) = (0, 0);
            while let Some(&item) = items.get(read) {
                let (kept, taken) = match matching(lookup, &items, read) {
                    Some((rest, glyph)) => {
                        let joined = items.get(read..=read + rest).unwrap_or_default();
                        ((glyph, joined.iter().map(|&(_, n)| n).sum()), rest + 1)
                    }
                    None => (item, 1),
                };
                if let Some(slot) = items.get_mut(write) {
                    *slot = kept;
                }
                write += 1;
                read += taken;
            }
            items.truncate(write);
        }
        let mut found = Vec::new();
        let mut start = 0;
        for (glyph, len) in items {
            if len > 1 {
                found.push(Ligature { start, len, glyph });
            }
            start += len;
        }
        found
    }
}

/// The first ligature of `lookup` whose glyphs follow at `index`, with the number of glyphs
/// after the first that it takes.
fn matching(lookup: &Lookup, items: &[(u32, usize)], index: usize) -> Option<(usize, u32)> {
    let (first, _) = items.get(index)?;
    let following = items.get(index + 1..)?;
    lookup.get(first)?.iter().find_map(|(rest, glyph)| {
        let fits = rest.len() <= following.len()
            && rest
                .iter()
                .zip(following)
                .all(|(want, (have, _))| want == have);
        fits.then_some((rest.len(), *glyph))
    })
}

pub(crate) const LATIN: Tag = Tag::new(b"latn");
pub(crate) const DEFAULT: Tag = Tag::new(b"DFLT");
const LIGA: Tag = Tag::new(b"liga");

fn liga_lookups(gsub: &Gsub<'_>) -> Result<Lookups, ReadError> {
    let indices = feature_lookups(
        &gsub.script_list()?,
        &gsub.feature_list()?,
        LIGA,
        &[LATIN, DEFAULT],
    )?;
    let list = gsub.lookup_list()?;
    let mut lookups = Vec::new();
    for index in indices {
        let mut map = Lookup::new();
        for subtable in ligature_subtables(&list.lookups().get(usize::from(index))?)? {
            read_subtable(&subtable, &mut map)?;
        }
        if !map.is_empty() {
            lookups.push(map);
        }
    }
    Ok(Lookups(lookups))
}

/// The indices of the lookups of a feature in the default language of the first of `scripts`
/// that the table has, in lookup order. A `GSUB` or `GPOS` table gives the lists.
pub(crate) fn feature_lookups(
    scripts: &ScriptList<'_>,
    features: &FeatureList<'_>,
    tag: Tag,
    order: &[Tag],
) -> Result<Vec<u16>, ReadError> {
    let Some(lang_sys) = default_lang_sys(scripts, order)? else {
        return Ok(Vec::new());
    };
    let mut indices: Vec<u16> = Vec::new();
    for index in lang_sys.feature_indices() {
        let Some(record) = features.feature_records().get(usize::from(index.get())) else {
            continue;
        };
        if record.feature_tag() == tag {
            let feature = record.feature(features.offset_data())?;
            indices.extend(feature.lookup_list_indices().iter().map(BigEndian::get));
        }
    }
    indices.sort_unstable();
    indices.dedup();
    Ok(indices)
}

/// The default language system of the first of `order` that the script list has.
fn default_lang_sys<'a>(
    scripts: &ScriptList<'a>,
    order: &[Tag],
) -> Result<Option<LangSys<'a>>, ReadError> {
    let records = scripts.script_records();
    let record = order
        .iter()
        .find_map(|tag| records.iter().find(|r| r.script_tag() == *tag));
    let Some(record) = record else {
        return Ok(None);
    };
    record
        .script(scripts.offset_data())?
        .default_lang_sys()
        .transpose()
}

/// The ligature subtables of a lookup, inside extension subtables too. Other lookup types
/// have none.
fn ligature_subtables<'a>(
    lookup: &SubstitutionLookup<'a>,
) -> Result<Vec<LigatureSubstFormat1<'a>>, ReadError> {
    let mut found = Vec::new();
    match lookup {
        SubstitutionLookup::Ligature(lookup) => {
            for subtable in lookup.subtables().iter() {
                if let LigatureSubst::Format1(table) = subtable? {
                    found.push(table);
                }
            }
        }
        SubstitutionLookup::Extension(lookup) => {
            for subtable in lookup.subtables().iter() {
                if let ExtensionSubtable::Ligature(extension) = subtable?
                    && let LigatureSubst::Format1(table) = extension.extension()?
                {
                    found.push(table);
                }
            }
        }
        _ => {}
    }
    Ok(found)
}

/// Adds the ligatures of one subtable after those of the earlier subtables of the same lookup,
/// because the subtables of a lookup are tried in order until one applies.
fn read_subtable(table: &LigatureSubstFormat1<'_>, map: &mut Lookup) -> Result<(), ReadError> {
    let sets = table.ligature_sets();
    for (index, first) in table.coverage()?.iter().enumerate() {
        let ligatures = map.entry(first.to_u32()).or_default();
        for ligature in sets.get(index)?.ligatures().iter() {
            let ligature = ligature?;
            let rest = ligature
                .component_glyph_ids()
                .iter()
                .map(|g| g.get().to_u32())
                .collect();
            ligatures.push((rest, ligature.ligature_glyph().to_u32()));
        }
    }
    Ok(())
}

impl FontDb {
    /// Returns the standard ligatures (`liga`) of a sequence of glyphs from one face, in order
    /// and without overlaps. The lookups come from the default language of the Latin script,
    /// or of the default script, and apply in lookup order. Lookup flags are not read, so a
    /// mark between two glyphs keeps them apart.
    ///
    /// Returns none for an unknown face or a font without a `GSUB` table.
    #[must_use]
    pub fn ligatures(&self, id: FontId, glyphs: &[u32]) -> Vec<Ligature> {
        self.ligature_lookups(id)
            .map_or_else(Vec::new, |lookups| lookups.apply(glyphs))
    }

    /// Returns the glyph sequences that the standard ligatures of a face join, as
    /// [`FontDb::ligatures`] reads them, each with its first glyph.
    pub(crate) fn ligature_sequences(&self, id: FontId) -> Vec<Vec<u32>> {
        self.ligature_lookups(id)
            .map_or_else(Vec::new, Lookups::sequences)
    }

    /// The standard ligature lookups of a face, read once; `None` for an unknown face or a
    /// file that did not load.
    fn ligature_lookups(&self, id: FontId) -> Option<&Lookups> {
        let face = self.face(id)?;
        let font = face.font()?;
        Some(
            face.ligatures
                .get_or_init(|| Lookups::read(font.tables().gsub())),
        )
    }
}

#[cfg(test)]
mod tests;