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");
type Lookup = HashMap<u32, Substitute>;
#[derive(Debug)]
enum Substitute {
Single(u32),
Alternates(Vec<u32>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ScriptLevel {
Script,
ScriptOfScript,
}
impl ScriptLevel {
fn alternate(self) -> usize {
match self {
Self::Script => 0,
Self::ScriptOfScript => 1,
}
}
}
#[derive(Debug, Default)]
pub(crate) struct ScriptGlyphs(Vec<Lookup>);
impl ScriptGlyphs {
pub(crate) fn read(gsub: Result<Gsub<'_>, ReadError>) -> Self {
gsub.and_then(|gsub| feature(&gsub, SSTY))
.unwrap_or_default()
}
fn read_feature(gsub: Result<Gsub<'_>, ReadError>, tag: Tag) -> Self {
gsub.and_then(|gsub| feature(&gsub, tag))
.unwrap_or_default()
}
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(¤t) {
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))
}
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();
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())));
}
}
_ => {}
}
Ok(())
}
fn read_alternates(table: &AlternateSubst<'_>, map: &mut Lookup) -> Result<(), ReadError> {
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 {
#[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)
}
#[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)
}
#[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;