1use std::collections::{BTreeMap, BTreeSet};
4
5use skrifa::GlyphId;
6use skrifa::font::Font;
7use skrifa::raw::tables::gpos::{
8 ExtensionSubtable, Gpos, PairPos, PairPosFormat2, PositionLookup, PositionLookupList,
9};
10use skrifa::raw::tables::kern::SubtableKind;
11use skrifa::raw::types::Tag;
12use skrifa::raw::{ReadError, TableProvider};
13
14use crate::face::Face;
15use crate::ligature::{DEFAULT, LATIN, feature_lookups};
16use crate::{FontDb, FontId};
17
18const KERN: Tag = Tag::new(b"kern");
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum KerningSource {
23 Gpos,
25 KernTable,
28}
29
30impl FontDb {
31 #[must_use]
36 pub fn kerning_source(&self, id: FontId) -> KerningSource {
37 match self.face(id).and_then(kern_lookups) {
38 Some(lookups) if !lookups.is_empty() => KerningSource::Gpos,
39 _ => KerningSource::KernTable,
40 }
41 }
42
43 #[must_use]
56 pub fn kerning(&self, id: FontId, left: u32, right: u32) -> i32 {
57 self.kerning_from(id, left, right, self.kerning_source(id))
58 }
59
60 #[must_use]
65 pub fn kerning_from(&self, id: FontId, left: u32, right: u32, source: KerningSource) -> i32 {
66 let Some(face) = self.face(id) else {
67 return 0;
68 };
69 let (left, right) = (GlyphId::new(left), GlyphId::new(right));
70 match source {
71 KerningSource::KernTable => kern_table(face, left, right),
72 KerningSource::Gpos => {
73 let Some((font, lookups)) = face.font().zip(kern_lookups(face)) else {
74 return 0;
75 };
76 if lookups.is_empty() {
77 return 0;
78 }
79 font.tables()
80 .gpos()
81 .and_then(|gpos| gpos_kerning(&gpos, lookups, left, right))
82 .unwrap_or(0)
83 }
84 }
85 }
86
87 #[must_use]
90 pub fn has_kern_table(&self, id: FontId) -> bool {
91 let Some(font) = self.face(id).and_then(Face::font) else {
92 return false;
93 };
94 font.tables().kern().is_ok_and(|kern| {
95 kern.subtables().flatten().any(|s| {
96 s.is_horizontal()
97 && !s.is_cross_stream()
98 && !matches!(s.kind(), Ok(SubtableKind::Format1(_)) | Err(_))
99 })
100 })
101 }
102}
103
104fn kern_lookups(face: &Face) -> Option<&[u16]> {
107 let font = face.font()?;
108 let lookups = face
109 .kern_lookups
110 .get_or_init(|| gpos_kern_lookups(font).unwrap_or_default());
111 Some(lookups)
112}
113
114fn gpos_kern_lookups(font: &Font) -> Result<Vec<u16>, ReadError> {
116 let gpos = font.tables().gpos()?;
117 feature_lookups(
118 &gpos.script_list()?,
119 &gpos.feature_list()?,
120 KERN,
121 &[LATIN, DEFAULT],
122 )
123}
124
125fn kern_table(face: &Face, left: GlyphId, right: GlyphId) -> i32 {
126 let Some(Ok(kern)) = face.font().map(|font| font.tables().kern()) else {
127 return 0;
128 };
129 kern.subtables()
130 .flatten()
131 .filter(|s| s.is_horizontal() && !s.is_cross_stream())
132 .filter_map(|s| match s.kind().ok()? {
133 SubtableKind::Format0(t) => t.kerning(left, right),
134 SubtableKind::Format2(t) => t.kerning(left, right),
135 SubtableKind::Format3(t) => t.kerning(left, right),
136 SubtableKind::Format1(_) => None,
137 })
138 .sum()
139}
140
141fn gpos_kerning(
142 gpos: &Gpos<'_>,
143 lookups: &[u16],
144 left: GlyphId,
145 right: GlyphId,
146) -> Result<i32, ReadError> {
147 let list = gpos.lookup_list()?;
148 let mut total = 0;
149 for index in lookups {
150 if let Some(value) = pair_subtables(&list, *index)?
151 .iter()
152 .find_map(|subtable| pair_value(subtable, left, right))
153 {
154 total += value;
155 }
156 }
157 Ok(total)
158}
159
160fn pair_subtables<'a>(
163 list: &PositionLookupList<'a>,
164 index: u16,
165) -> Result<Vec<PairPos<'a>>, ReadError> {
166 Ok(match list.lookups().get(usize::from(index))? {
167 PositionLookup::Pair(lookup) => lookup.subtables().iter().flatten().collect(),
168 PositionLookup::Extension(lookup) => lookup
169 .subtables()
170 .iter()
171 .flatten()
172 .filter_map(|subtable| match subtable {
173 ExtensionSubtable::Pair(pair) => pair.extension().ok(),
174 _ => None,
175 })
176 .collect(),
177 _ => Vec::new(),
178 })
179}
180
181impl FontDb {
182 pub(crate) fn listed_kerning_pairs(
189 &self,
190 id: FontId,
191 glyphs: &BTreeSet<u32>,
192 ) -> BTreeSet<(u32, u32)> {
193 let mut pairs = BTreeSet::new();
194 let Some(face) = self.face(id) else {
195 return pairs;
196 };
197 if let Some((font, lookups)) = face.font().zip(kern_lookups(face)) {
198 let gpos = font.tables().gpos();
199 let list = gpos.and_then(|gpos| gpos.lookup_list());
200 for subtable in list.iter().flat_map(|list| {
201 lookups
202 .iter()
203 .filter_map(|&index| pair_subtables(list, index).ok())
204 .flatten()
205 }) {
206 listed_gpos_pairs(&subtable, glyphs, &mut pairs);
207 }
208 }
209 listed_kern_table_pairs(face, glyphs, &mut pairs);
210 pairs
211 }
212}
213
214fn listed_gpos_pairs(
217 subtable: &PairPos<'_>,
218 glyphs: &BTreeSet<u32>,
219 pairs: &mut BTreeSet<(u32, u32)>,
220) {
221 match subtable {
222 PairPos::Format1(table) => {
223 let (Ok(coverage), sets) = (table.coverage(), table.pair_sets()) else {
224 return;
225 };
226 for (left, set) in coverage.iter().zip(sets.iter()) {
227 let Ok(set) = set else { continue };
228 let rights = set
229 .pair_value_records()
230 .iter()
231 .flatten()
232 .filter(|record| record.value_record1().x_advance().unwrap_or(0) != 0);
233 for record in rights {
234 let pair = (left.to_u32(), GlyphId::from(record.second_glyph()).to_u32());
235 if glyphs.contains(&pair.0) && glyphs.contains(&pair.1) {
236 pairs.insert(pair);
237 }
238 }
239 }
240 }
241 PairPos::Format2(table) => listed_class_pairs(table, glyphs, pairs),
242 _ => {}
244 }
245}
246
247fn listed_class_pairs(
251 table: &PairPosFormat2<'_>,
252 glyphs: &BTreeSet<u32>,
253 pairs: &mut BTreeSet<(u32, u32)>,
254) {
255 let (Ok(coverage), Ok(firsts), Ok(seconds)) =
256 (table.coverage(), table.class_def1(), table.class_def2())
257 else {
258 return;
259 };
260 let mut by_class: BTreeMap<u16, Vec<u32>> = BTreeMap::new();
261 for &glyph in glyphs {
262 if let Ok(class) = u16::try_from(seconds.get(GlyphId::new(glyph))) {
263 by_class.entry(class).or_default().push(glyph);
264 }
265 }
266 for left in coverage
267 .iter()
268 .map(GlyphId::to_u32)
269 .filter(|g| glyphs.contains(g))
270 {
271 let Ok(first) = u16::try_from(firsts.get(GlyphId::new(left))) else {
272 continue;
273 };
274 for (&second, rights) in &by_class {
275 let adjusts = table
276 .value_record_refs(first, second)
277 .is_some_and(|[record, _]| record.x_advance().unwrap_or(0) != 0);
278 if adjusts {
279 pairs.extend(rights.iter().map(|&right| (left, right)));
280 }
281 }
282 }
283}
284
285fn listed_kern_table_pairs(face: &Face, glyphs: &BTreeSet<u32>, pairs: &mut BTreeSet<(u32, u32)>) {
288 let Some(Ok(kern)) = face.font().map(|font| font.tables().kern()) else {
289 return;
290 };
291 let subtables = kern
292 .subtables()
293 .flatten()
294 .filter(|s| s.is_horizontal() && !s.is_cross_stream());
295 for subtable in subtables {
296 let Ok(SubtableKind::Format0(table)) = subtable.kind() else {
297 continue;
298 };
299 for pair in table.pairs() {
300 let found = (
301 u32::from(pair.left().to_u16()),
302 u32::from(pair.right().to_u16()),
303 );
304 if pair.value() != 0 && glyphs.contains(&found.0) && glyphs.contains(&found.1) {
305 pairs.insert(found);
306 }
307 }
308 }
309}
310
311fn pair_value(subtable: &PairPos<'_>, left: GlyphId, right: GlyphId) -> Option<i32> {
314 match subtable {
315 PairPos::Format1(table) => {
316 let index = table.coverage().ok()?.get(left)?;
317 let set = table.pair_sets().get(usize::try_from(index).ok()?).ok()?;
318 let records = set.pair_value_records();
319 let record = records
320 .iter()
321 .flatten()
322 .find(|record| GlyphId::from(record.second_glyph()) == right)?;
323 Some(i32::from(record.value_record1().x_advance().unwrap_or(0)))
324 }
325 PairPos::Format2(table) => {
326 table.coverage().ok()?.get(left)?;
327 let class1 = u16::try_from(table.class_def1().ok()?.get(left)).ok()?;
328 let class2 = u16::try_from(table.class_def2().ok()?.get(right)).ok()?;
329 let [first, _] = table.value_record_refs(class1, class2)?;
330 Some(i32::from(first.x_advance().unwrap_or(0)))
331 }
332 _ => None,
333 }
334}