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};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Ligature {
pub start: usize,
pub len: usize,
pub glyph: u32,
}
type Lookup = HashMap<u32, Vec<(Vec<u32>, u32)>>;
#[derive(Debug, Default)]
pub(crate) struct Lookups(Vec<Lookup>);
impl Lookups {
pub(crate) fn read(gsub: Result<Gsub<'_>, ReadError>) -> Self {
gsub.and_then(|gsub| liga_lookups(&gsub))
.unwrap_or_default()
}
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
}
fn apply(&self, glyphs: &[u32]) -> Vec<Ligature> {
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
}
}
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))
}
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)
}
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()
}
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)
}
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 {
#[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))
}
pub(crate) fn ligature_sequences(&self, id: FontId) -> Vec<Vec<u32>> {
self.ligature_lookups(id)
.map_or_else(Vec::new, Lookups::sequences)
}
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;