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");
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KerningSource {
Gpos,
KernTable,
}
impl FontDb {
#[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,
}
}
#[must_use]
pub fn kerning(&self, id: FontId, left: u32, right: u32) -> i32 {
self.kerning_from(id, left, right, self.kerning_source(id))
}
#[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)
}
}
}
#[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(_))
})
})
}
}
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)
}
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)
}
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 {
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
}
}
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),
_ => {}
}
}
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)));
}
}
}
}
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);
}
}
}
}
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,
}
}