f_office_fonts/
ligature.rs1use std::collections::HashMap;
4
5use skrifa::raw::tables::gsub::{
6 ExtensionSubtable, Gsub, LigatureSubst, LigatureSubstFormat1, SubstitutionLookup,
7};
8use skrifa::raw::tables::layout::{FeatureList, LangSys, ScriptList};
9use skrifa::raw::types::{BigEndian, Tag};
10use skrifa::raw::{ReadError, TableProvider};
11
12use crate::{FontDb, FontId};
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct Ligature {
17 pub start: usize,
19 pub len: usize,
21 pub glyph: u32,
23}
24
25type Lookup = HashMap<u32, Vec<(Vec<u32>, u32)>>;
28
29#[derive(Debug, Default)]
31pub(crate) struct Lookups(Vec<Lookup>);
32
33impl Lookups {
34 pub(crate) fn read(gsub: Result<Gsub<'_>, ReadError>) -> Self {
38 gsub.and_then(|gsub| liga_lookups(&gsub))
39 .unwrap_or_default()
40 }
41
42 fn sequences(&self) -> Vec<Vec<u32>> {
44 let mut found = Vec::new();
45 for lookup in &self.0 {
46 let mut firsts: Vec<&u32> = lookup.keys().collect();
47 firsts.sort_unstable();
48 for &first in firsts {
49 for (rest, _) in lookup.get(&first).map_or(&[][..], Vec::as_slice) {
50 found.push(std::iter::once(first).chain(rest.iter().copied()).collect());
51 }
52 }
53 }
54 found
55 }
56
57 fn apply(&self, glyphs: &[u32]) -> Vec<Ligature> {
64 let mut items: Vec<(u32, usize)> = glyphs.iter().map(|&g| (g, 1)).collect();
66 for lookup in &self.0 {
67 let (mut read, mut write) = (0, 0);
68 while let Some(&item) = items.get(read) {
69 let (kept, taken) = match matching(lookup, &items, read) {
70 Some((rest, glyph)) => {
71 let joined = items.get(read..=read + rest).unwrap_or_default();
72 ((glyph, joined.iter().map(|&(_, n)| n).sum()), rest + 1)
73 }
74 None => (item, 1),
75 };
76 if let Some(slot) = items.get_mut(write) {
77 *slot = kept;
78 }
79 write += 1;
80 read += taken;
81 }
82 items.truncate(write);
83 }
84 let mut found = Vec::new();
85 let mut start = 0;
86 for (glyph, len) in items {
87 if len > 1 {
88 found.push(Ligature { start, len, glyph });
89 }
90 start += len;
91 }
92 found
93 }
94}
95
96fn matching(lookup: &Lookup, items: &[(u32, usize)], index: usize) -> Option<(usize, u32)> {
99 let (first, _) = items.get(index)?;
100 let following = items.get(index + 1..)?;
101 lookup.get(first)?.iter().find_map(|(rest, glyph)| {
102 let fits = rest.len() <= following.len()
103 && rest
104 .iter()
105 .zip(following)
106 .all(|(want, (have, _))| want == have);
107 fits.then_some((rest.len(), *glyph))
108 })
109}
110
111pub(crate) const LATIN: Tag = Tag::new(b"latn");
112pub(crate) const DEFAULT: Tag = Tag::new(b"DFLT");
113const LIGA: Tag = Tag::new(b"liga");
114
115fn liga_lookups(gsub: &Gsub<'_>) -> Result<Lookups, ReadError> {
116 let indices = feature_lookups(
117 &gsub.script_list()?,
118 &gsub.feature_list()?,
119 LIGA,
120 &[LATIN, DEFAULT],
121 )?;
122 let list = gsub.lookup_list()?;
123 let mut lookups = Vec::new();
124 for index in indices {
125 let mut map = Lookup::new();
126 for subtable in ligature_subtables(&list.lookups().get(usize::from(index))?)? {
127 read_subtable(&subtable, &mut map)?;
128 }
129 if !map.is_empty() {
130 lookups.push(map);
131 }
132 }
133 Ok(Lookups(lookups))
134}
135
136pub(crate) fn feature_lookups(
139 scripts: &ScriptList<'_>,
140 features: &FeatureList<'_>,
141 tag: Tag,
142 order: &[Tag],
143) -> Result<Vec<u16>, ReadError> {
144 let Some(lang_sys) = default_lang_sys(scripts, order)? else {
145 return Ok(Vec::new());
146 };
147 let mut indices: Vec<u16> = Vec::new();
148 for index in lang_sys.feature_indices() {
149 let Some(record) = features.feature_records().get(usize::from(index.get())) else {
150 continue;
151 };
152 if record.feature_tag() == tag {
153 let feature = record.feature(features.offset_data())?;
154 indices.extend(feature.lookup_list_indices().iter().map(BigEndian::get));
155 }
156 }
157 indices.sort_unstable();
158 indices.dedup();
159 Ok(indices)
160}
161
162fn default_lang_sys<'a>(
164 scripts: &ScriptList<'a>,
165 order: &[Tag],
166) -> Result<Option<LangSys<'a>>, ReadError> {
167 let records = scripts.script_records();
168 let record = order
169 .iter()
170 .find_map(|tag| records.iter().find(|r| r.script_tag() == *tag));
171 let Some(record) = record else {
172 return Ok(None);
173 };
174 record
175 .script(scripts.offset_data())?
176 .default_lang_sys()
177 .transpose()
178}
179
180fn ligature_subtables<'a>(
183 lookup: &SubstitutionLookup<'a>,
184) -> Result<Vec<LigatureSubstFormat1<'a>>, ReadError> {
185 let mut found = Vec::new();
186 match lookup {
187 SubstitutionLookup::Ligature(lookup) => {
188 for subtable in lookup.subtables().iter() {
189 if let LigatureSubst::Format1(table) = subtable? {
190 found.push(table);
191 }
192 }
193 }
194 SubstitutionLookup::Extension(lookup) => {
195 for subtable in lookup.subtables().iter() {
196 if let ExtensionSubtable::Ligature(extension) = subtable?
197 && let LigatureSubst::Format1(table) = extension.extension()?
198 {
199 found.push(table);
200 }
201 }
202 }
203 _ => {}
204 }
205 Ok(found)
206}
207
208fn read_subtable(table: &LigatureSubstFormat1<'_>, map: &mut Lookup) -> Result<(), ReadError> {
211 let sets = table.ligature_sets();
212 for (index, first) in table.coverage()?.iter().enumerate() {
213 let ligatures = map.entry(first.to_u32()).or_default();
214 for ligature in sets.get(index)?.ligatures().iter() {
215 let ligature = ligature?;
216 let rest = ligature
217 .component_glyph_ids()
218 .iter()
219 .map(|g| g.get().to_u32())
220 .collect();
221 ligatures.push((rest, ligature.ligature_glyph().to_u32()));
222 }
223 }
224 Ok(())
225}
226
227impl FontDb {
228 #[must_use]
235 pub fn ligatures(&self, id: FontId, glyphs: &[u32]) -> Vec<Ligature> {
236 self.ligature_lookups(id)
237 .map_or_else(Vec::new, |lookups| lookups.apply(glyphs))
238 }
239
240 pub(crate) fn ligature_sequences(&self, id: FontId) -> Vec<Vec<u32>> {
243 self.ligature_lookups(id)
244 .map_or_else(Vec::new, Lookups::sequences)
245 }
246
247 fn ligature_lookups(&self, id: FontId) -> Option<&Lookups> {
250 let face = self.face(id)?;
251 let font = face.font()?;
252 Some(
253 face.ligatures
254 .get_or_init(|| Lookups::read(font.tables().gsub())),
255 )
256 }
257}
258
259#[cfg(test)]
260mod tests;