1use super::coverage::{Coverage, CoverageArray};
7use super::{read_be, Offsets, SubtableDigests, Uints, Values};
8use crate::budget::{Budget, Exhausted};
9use crate::buffer::{GlyphInfo, GlyphPropsFlags};
10use crate::hint::Likely;
11use crate::ot::apply::{
12 ligate_input, match_always, match_backtrack, match_glyph, match_input, match_lookahead,
13 ApplyContext, MaySkip, SkippingIterator, WouldApplyContext,
14};
15use crate::ot::layout::MAX_NESTING_LEVEL;
16use crate::ot::map::OtMap;
17use crate::set_digest::SetDigest;
18#[cfg(feature = "tracing")]
19use alloc::string::String;
20use read_fonts::tables::gsub::{
21 AlternateSubstFormat1, AlternateSubstFormat2, LigatureSubstFormat1, LigatureSubstFormat2,
22 MultipleSubstFormat1, MultipleSubstFormat2, ReverseChainSingleSubstFormat1,
23 ReverseChainSingleSubstFormat2, SingleSubstFormat1, SingleSubstFormat2, SingleSubstFormat3,
24 SingleSubstFormat4,
25};
26use read_fonts::types::GlyphId;
27use read_fonts::FontData;
28
29const NARROW: usize = 2;
31const WIDE: usize = 3;
33
34fn counted_glyphs(data: FontData, width: usize) -> Option<Uints> {
37 let count = usize::from(data.read_at::<u16>(0).ok()?);
38 Uints::at(data, 2, count, width)
39}
40
41pub(crate) struct SingleSubst1 {
43 delta: i32,
44 mask: u32,
45}
46
47impl SingleSubst1 {
48 pub fn new(table: &SingleSubstFormat1) -> Option<Self> {
49 Some(Self {
50 delta: table.delta_glyph_id().into(),
51 mask: 0xFFFF,
52 })
53 }
54
55 pub fn new_wide(table: &SingleSubstFormat3) -> Option<Self> {
56 Some(Self {
57 delta: table.delta_glyph_id().to_i32(),
58 mask: 0xFF_FFFF,
59 })
60 }
61
62 pub fn apply(&self, ctx: &mut ApplyContext, _index: u32) -> Option<()> {
63 let glyph = ctx.buffer.cur(0)?.glyph_id;
64 let substitute = (glyph as i32).wrapping_add(self.delta) as u32 & self.mask;
65 message!(
66 ctx,
67 "replacing glyph at {} (single substitution)",
68 ctx.buffer.message_idx()
69 );
70 ctx.replace_glyph(substitute.into());
71 message!(
72 ctx,
73 "replaced glyph at {} (single substitution)",
74 ctx.buffer.message_idx() - 1
75 );
76 Some(())
77 }
78}
79
80impl SubtableDigests<'_> for SingleSubst1 {}
81
82pub(crate) struct SingleSubst2<'a> {
84 substitutes: Uints<'a>,
85}
86
87impl<'a> SingleSubst2<'a> {
88 pub fn new(table: &SingleSubstFormat2<'a>) -> Option<Self> {
89 let range = table.substitute_glyph_ids_byte_range();
90 Some(Self {
91 substitutes: Uints::new(table.offset_data(), range, NARROW)?,
92 })
93 }
94
95 pub fn new_wide(table: &SingleSubstFormat4<'a>) -> Option<Self> {
96 let range = table.substitute_glyph_ids_byte_range();
97 Some(Self {
98 substitutes: Uints::new(table.offset_data(), range, WIDE)?,
99 })
100 }
101
102 pub fn apply(&self, ctx: &mut ApplyContext, index: u32) -> Option<()> {
103 let substitute = self.substitutes.get(index as usize)?;
104 message!(
105 ctx,
106 "replacing glyph at {} (single substitution)",
107 ctx.buffer.message_idx()
108 );
109 ctx.replace_glyph(substitute.into());
110 message!(
111 ctx,
112 "replaced glyph at {} (single substitution)",
113 ctx.buffer.message_idx() - 1
114 );
115 Some(())
116 }
117}
118
119impl<'a> SubtableDigests<'a> for SingleSubst2<'a> {}
120
121pub(crate) struct MultipleSubst1<'a> {
123 sequences: Offsets<'a>,
124 glyph_width: u8,
125}
126
127impl<'a> MultipleSubst1<'a> {
128 pub fn new(table: &MultipleSubstFormat1<'a>) -> Option<Self> {
129 let range = table.sequence_offsets_byte_range();
130 Some(Self {
131 sequences: Offsets::new(table.offset_data(), range, NARROW),
132 glyph_width: NARROW as u8,
133 })
134 }
135
136 pub fn new_wide(table: &MultipleSubstFormat2<'a>) -> Option<Self> {
137 let range = table.sequence_offsets_byte_range();
138 Some(Self {
139 sequences: Offsets::new(table.offset_data(), range, WIDE),
140 glyph_width: WIDE as u8,
141 })
142 }
143
144 pub fn apply(&self, ctx: &mut ApplyContext, index: u32) -> Option<()> {
145 let data = self.sequences.data(index as usize)?;
146 let substitutes = counted_glyphs(data, self.glyph_width.into())?;
147 match substitutes.len() {
148 0 => {
151 message!(
152 ctx,
153 "deleting glyph at {} (multiple substitution)",
154 ctx.buffer.message_idx()
155 );
156 ctx.buffer.delete_glyph();
157 message!(
158 ctx,
159 "deleted glyph at {} (multiple substitution)",
160 ctx.buffer.message_idx()
161 );
162 }
163 1 => {
166 message!(
167 ctx,
168 "replacing glyph at {} (multiple substitution)",
169 ctx.buffer.message_idx()
170 );
171 ctx.replace_glyph(substitutes.first()?.into());
172 message!(
173 ctx,
174 "replaced glyph at {} (multiple substitution)",
175 ctx.buffer.message_idx() - 1
176 );
177 }
178 _ => {
179 message!(ctx, "multiplying glyph at {}", ctx.buffer.message_idx());
180 let class = if ctx.buffer.cur(0)?.is_ligature() {
181 GlyphPropsFlags::BASE_GLYPH
182 } else {
183 GlyphPropsFlags::empty()
184 };
185 let lig_id = ctx.buffer.cur(0)?.lig_id();
186 for (component, substitute) in substitutes.iter().enumerate() {
187 if lig_id == 0 {
190 ctx.buffer
192 .cur_mut(0)?
193 .set_lig_props_for_component(component as u8);
194 }
195 ctx.output_glyph_for_component(substitute.into(), class);
196 }
197 ctx.buffer.skip_glyph();
198 #[cfg(feature = "tracing")]
199 if ctx.buffer.messaging() && ctx.buffer.successful {
200 let count = substitutes.len();
201 let end = ctx.buffer.message_idx();
202 let mut msg = String::from("multiplied glyphs at ");
203 for i in (end - count)..end {
204 if i > (end - count) {
205 msg.push(',');
206 }
207 use core::fmt::Write;
208 let _ = write!(msg, "{i}");
209 }
210 ctx.buffer.message(ctx.font, &msg);
211 }
212 }
213 }
214 Some(())
215 }
216}
217
218impl<'a> SubtableDigests<'a> for MultipleSubst1<'a> {}
219
220pub(crate) struct AlternateSubst1<'a> {
222 alternate_sets: Offsets<'a>,
223 glyph_width: u8,
224}
225
226impl<'a> AlternateSubst1<'a> {
227 pub fn new(table: &AlternateSubstFormat1<'a>) -> Option<Self> {
228 let range = table.alternate_set_offsets_byte_range();
229 Some(Self {
230 alternate_sets: Offsets::new(table.offset_data(), range, NARROW),
231 glyph_width: NARROW as u8,
232 })
233 }
234
235 pub fn new_wide(table: &AlternateSubstFormat2<'a>) -> Option<Self> {
236 let range = table.alternate_set_offsets_byte_range();
237 Some(Self {
238 alternate_sets: Offsets::new(table.offset_data(), range, WIDE),
239 glyph_width: WIDE as u8,
240 })
241 }
242
243 pub fn apply(&self, ctx: &mut ApplyContext, index: u32) -> Option<()> {
244 let data = self.alternate_sets.data(index as usize)?;
245 apply_alternate_set(ctx, counted_glyphs(data, self.glyph_width.into())?)
246 }
247}
248
249impl<'a> SubtableDigests<'a> for AlternateSubst1<'a> {}
250
251fn apply_alternate_set(ctx: &mut ApplyContext, alternates: Uints) -> Option<()> {
252 if alternates.is_empty() {
253 return None;
254 }
255 let glyph_mask = ctx.buffer.cur(0)?.mask;
256 let lookup_mask = ctx.lookup_mask();
257 let mut alt_index = (lookup_mask & glyph_mask) >> lookup_mask.trailing_zeros();
259 if alt_index == OtMap::MAX_VALUE && ctx.random {
261 ctx.buffer.unsafe_to_break(Some(0), Some(ctx.buffer.len));
263 alt_index = ctx.random_number() % alternates.len() as u32 + 1;
264 }
265 let index = u16::try_from(alt_index).ok()?.checked_sub(1)?;
266 message!(
267 ctx,
268 "replacing glyph at {} (alternate substitution)",
269 ctx.buffer.message_idx()
270 );
271 ctx.replace_glyph(alternates.get(index as usize)?.into());
272 message!(
273 ctx,
274 "replaced glyph at {} (alternate substitution)",
275 ctx.buffer.message_idx() - 1
276 );
277 Some(())
278}
279
280struct Ligature<'a, const W: usize> {
283 glyph: u32,
284 components: Values<'a, W>,
285}
286
287impl<'a, const W: usize> Ligature<'a, W> {
288 #[inline(always)]
290 fn read(data: FontData<'a>) -> Option<Self> {
291 let glyph = read_be::<W>(data.as_bytes(), 0)?;
292 let count = usize::from(data.read_at::<u16>(W).ok()?);
293 Some(Self {
294 glyph,
295 components: Values::at(data, W + 2, count.saturating_sub(1))?,
296 })
297 }
298}
299
300struct LigatureSet<'a, const W: usize> {
303 data: FontData<'a>,
304 offsets: Values<'a, W>,
305}
306
307impl<'a, const W: usize> LigatureSet<'a, W> {
308 #[inline(always)]
309 fn read(data: FontData<'a>) -> Option<Self> {
310 let count = usize::from(data.read_at::<u16>(0).ok()?);
311 Some(Self {
312 data,
313 offsets: Values::at(data, 2, count)?,
314 })
315 }
316
317 fn len(&self) -> usize {
318 self.offsets.len()
319 }
320
321 #[inline(always)]
323 fn iter(&self) -> impl Iterator<Item = Ligature<'a, W>> + '_ {
324 self.offsets.iter().filter_map(|offset| {
325 if offset == 0 {
326 return None;
327 }
328 Ligature::read(self.data.split_off(offset as usize)?)
329 })
330 }
331}
332
333pub(crate) struct LigatureSubst1<'a> {
335 seconds: SetDigest,
337 ligature_sets: Offsets<'a>,
338 width: u8,
339}
340
341impl<'a> LigatureSubst1<'a> {
342 pub fn new(table: &LigatureSubstFormat1<'a>, budget: &Budget) -> Result<Self, Exhausted> {
343 let range = table.ligature_set_offsets_byte_range();
344 Self::from_sets(
345 Offsets::new(table.offset_data(), range, NARROW),
346 NARROW,
347 budget,
348 )
349 }
350
351 pub fn new_wide(table: &LigatureSubstFormat2<'a>, budget: &Budget) -> Result<Self, Exhausted> {
352 let range = table.ligature_set_offsets_byte_range();
353 Self::from_sets(Offsets::new(table.offset_data(), range, WIDE), WIDE, budget)
354 }
355
356 fn from_sets(
357 ligature_sets: Offsets<'a>,
358 width: usize,
359 budget: &Budget,
360 ) -> Result<Self, Exhausted> {
361 let seconds = if width == WIDE {
362 collect_seconds::<WIDE>(&ligature_sets, budget)?
363 } else {
364 collect_seconds::<NARROW>(&ligature_sets, budget)?
365 };
366 Ok(Self {
367 seconds,
368 ligature_sets,
369 width: width as u8,
370 })
371 }
372
373 pub fn apply(&self, ctx: &mut ApplyContext, index: u32) -> Option<()> {
376 let data = self.ligature_sets.data(index as usize)?;
377 if usize::from(self.width) == WIDE {
378 apply_ligature_set(ctx, &LigatureSet::<WIDE>::read(data)?, &self.seconds)
379 } else {
380 apply_ligature_set(ctx, &LigatureSet::<NARROW>::read(data)?, &self.seconds)
381 }
382 }
383
384 pub fn would_apply(&self, ctx: &WouldApplyContext, coverage: &Coverage) -> bool {
385 let Some(data) = coverage
386 .get(ctx.glyphs[0])
387 .and_then(|index| self.ligature_sets.data(index as usize))
388 else {
389 return false;
390 };
391 if usize::from(self.width) == WIDE {
392 set_would_apply(LigatureSet::<WIDE>::read(data), ctx)
393 } else {
394 set_would_apply(LigatureSet::<NARROW>::read(data), ctx)
395 }
396 }
397}
398
399fn set_would_apply<const W: usize>(set: Option<LigatureSet<W>>, ctx: &WouldApplyContext) -> bool {
400 set.is_some_and(|set| {
401 set.iter()
402 .any(|ligature| ligature_would_apply(&ligature, ctx))
403 })
404}
405
406impl<'a> SubtableDigests<'a> for LigatureSubst1<'a> {
407 const CACHES_COVERAGE: bool = true;
408
409 fn digest_second(&self, _budget: &Budget) -> Result<SetDigest, Exhausted> {
410 Ok(self.seconds.clone())
411 }
412}
413
414fn collect_seconds<const W: usize>(
417 sets: &Offsets,
418 budget: &Budget,
419) -> Result<SetDigest, Exhausted> {
420 let mut seconds = SetDigest::new();
421 budget.work(sets.len())?;
422 for index in 0..sets.len() {
423 let Some(set) = sets.data(index).and_then(LigatureSet::<W>::read) else {
424 continue;
425 };
426 budget.work(set.len())?;
427 for ligature in set.iter() {
428 let Some(second) = ligature.components.first() else {
429 return Ok(SetDigest::full());
430 };
431 seconds.add(second);
432 }
433 }
434 Ok(seconds)
435}
436
437fn ligature_would_apply<const W: usize>(ligature: &Ligature<W>, ctx: &WouldApplyContext) -> bool {
438 let components = &ligature.components;
439 ctx.glyphs.len() == components.len() + 1
440 && components
441 .iter()
442 .zip(&ctx.glyphs[1..])
443 .all(|(component, glyph)| GlyphId::new(component) == *glyph)
444}
445
446fn apply_ligature_set<const W: usize>(
448 ctx: &mut ApplyContext,
449 set: &LigatureSet<W>,
450 seconds: &SetDigest,
451) -> Option<()> {
452 let mut second = None;
455 let mut unsafe_to = 0;
456 if set.len() > 1 {
457 let mut iter = SkippingIterator::with_match_fn(ctx, true, Some(match_always));
458 if iter.reset(iter.buffer.idx).is_none() {
459 iter.buffer.index_failed();
460 }
461 if iter.next(Some(&mut unsafe_to)) {
462 let info = iter.buffer.info.get(iter.index()).likely()?;
463 unsafe_to = iter.index() + 1;
464 if iter.may_skip(info) == MaySkip::No {
467 second = Some(info.glyph_id);
468 }
469 }
470 }
471
472 let Some(second) = second else {
473 return set
474 .iter()
475 .find_map(|ligature| apply_ligature(ctx, &ligature));
476 };
477 if !seconds.may_have(second) {
478 ctx.buffer
482 .unsafe_to_concat(Some(ctx.buffer.idx), Some(unsafe_to));
483 return None;
484 }
485 let mut unsafe_to_concat = false;
486 for ligature in set.iter() {
487 match ligature.components.first() {
488 Some(first) if first != second => unsafe_to_concat = true,
489 _ => {
490 if apply_ligature(ctx, &ligature).is_some() {
491 if unsafe_to_concat {
492 ctx.buffer
493 .unsafe_to_concat(Some(ctx.buffer.idx), Some(unsafe_to));
494 }
495 return Some(());
496 }
497 }
498 }
499 }
500 if unsafe_to_concat {
501 ctx.buffer
502 .unsafe_to_concat(Some(ctx.buffer.idx), Some(unsafe_to));
503 }
504 None
505}
506
507fn apply_ligature<const W: usize>(ctx: &mut ApplyContext, ligature: &Ligature<W>) -> Option<()> {
508 let components = &ligature.components;
509 let ligature_glyph = ligature.glyph.into();
510 if components.is_empty() {
512 message!(
513 ctx,
514 "replacing glyph at {} (ligature substitution)",
515 ctx.buffer.message_idx()
516 );
517 ctx.replace_glyph(ligature_glyph);
518 message!(
519 ctx,
520 "replaced glyph at {} (ligature substitution)",
521 ctx.buffer.message_idx() - 1
522 );
523 return Some(());
524 }
525 let matches = |info: &mut GlyphInfo, index: u32| {
526 components
527 .get(index as usize)
528 .is_some_and(|component| match_glyph(info, component))
529 };
530 let mut match_end = 0;
531 let mut total_component_count = 0;
532 if !match_input(
533 ctx,
534 components.len() as u16,
535 matches,
536 &mut match_end,
537 Some(&mut total_component_count),
538 )? {
539 ctx.buffer
540 .unsafe_to_concat(Some(ctx.buffer.idx), Some(match_end));
541 return None;
542 }
543 #[cfg(feature = "tracing")]
544 let mut pos = 0;
545 #[cfg(feature = "tracing")]
546 if ctx.buffer.messaging() {
547 pos = ctx.buffer.message_idx();
548 let mut msg = String::from("ligating glyphs at ");
549 for i in 0..components.len() + 1 {
550 let index = ctx.match_positions[i] as usize - ctx.buffer.idx + pos;
551 if i > 0 {
552 msg.push(',');
553 }
554 use core::fmt::Write;
555 let _ = write!(msg, "{index}");
556 }
557 ctx.buffer.message(ctx.font, &msg);
558 }
559 ligate_input(
560 ctx,
561 components.len() + 1,
562 match_end,
563 total_component_count,
564 ligature_glyph,
565 )?;
566 message!(ctx, "ligated glyph at {}", pos);
567 Some(())
568}
569
570pub(crate) struct ReverseChainSubst1<'a> {
572 substitutes: Uints<'a>,
573 backtrack: CoverageArray<'a>,
575 lookahead: CoverageArray<'a>,
576}
577
578impl<'a> ReverseChainSubst1<'a> {
579 pub fn new(
580 table: &ReverseChainSingleSubstFormat1<'a>,
581 budget: &Budget,
582 ) -> Result<Option<Self>, Exhausted> {
583 let data = table.offset_data();
584 let Some(substitutes) = Uints::new(data, table.substitute_glyph_ids_byte_range(), NARROW)
585 else {
586 return Ok(None);
587 };
588 Ok(Some(Self {
589 substitutes,
590 backtrack: CoverageArray::new(
591 Offsets::new(data, table.backtrack_coverage_offsets_byte_range(), NARROW),
592 budget,
593 )?,
594 lookahead: CoverageArray::new(
595 Offsets::new(data, table.lookahead_coverage_offsets_byte_range(), NARROW),
596 budget,
597 )?,
598 }))
599 }
600
601 pub fn new_wide(
602 table: &ReverseChainSingleSubstFormat2<'a>,
603 budget: &Budget,
604 ) -> Result<Option<Self>, Exhausted> {
605 let data = table.offset_data();
606 let Some(substitutes) = Uints::new(data, table.substitute_glyph_ids_byte_range(), WIDE)
607 else {
608 return Ok(None);
609 };
610 Ok(Some(Self {
611 substitutes,
612 backtrack: CoverageArray::new(
613 Offsets::new(data, table.backtrack_coverage_offsets_byte_range(), WIDE),
614 budget,
615 )?,
616 lookahead: CoverageArray::new(
617 Offsets::new(data, table.lookahead_coverage_offsets_byte_range(), WIDE),
618 budget,
619 )?,
620 }))
621 }
622
623 pub fn apply(&self, ctx: &mut ApplyContext, index: u32) -> Option<()> {
624 if ctx.nesting_level_left != MAX_NESTING_LEVEL {
626 return None;
627 }
628 let substitute = self.substitutes.get(index as usize)?;
629
630 let mut start_index = 0;
631 let mut end_index = 0;
632 if match_backtrack(
633 ctx,
634 self.backtrack.len() as u16,
635 |info, index| covered_at(&self.backtrack, index, info),
636 &mut start_index,
637 ) && match_lookahead(
638 ctx,
639 self.lookahead.len() as u16,
640 |info, index| covered_at(&self.lookahead, index, info),
641 ctx.buffer.idx + 1,
642 &mut end_index,
643 ) {
644 message!(
645 ctx,
646 "replacing glyph at {} (reverse chaining substitution)",
647 ctx.buffer.message_idx()
648 );
649 ctx.buffer
650 .unsafe_to_break_from_outbuffer(Some(start_index), Some(end_index));
651 if ctx.replace_glyph_inplace(substitute.into()).is_none() {
652 ctx.buffer.index_failed();
653 }
654 message!(
655 ctx,
656 "replaced glyph at {} (reverse chaining substitution)",
657 ctx.buffer.message_idx()
658 );
659 return Some(());
662 }
663 ctx.buffer
664 .unsafe_to_concat_from_outbuffer(Some(start_index), Some(end_index));
665 None
666 }
667}
668
669impl<'a> SubtableDigests<'a> for ReverseChainSubst1<'a> {}
670
671#[inline(always)]
673pub(super) fn covered_at(coverages: &CoverageArray, index: u32, info: &GlyphInfo) -> bool {
674 coverages.get(index as usize).covers(info.glyph_id)
675}
676
677#[cfg(test)]
678mod tests {
679 use super::*;
680 use alloc::vec;
681 use read_fonts::FontRead;
682
683 fn seconds_of(data: &[u8], budget: &Budget) -> Result<SetDigest, Exhausted> {
684 let table = LigatureSubstFormat1::read(FontData::new(data)).unwrap();
685 LigatureSubst1::new(&table, budget).map(|subst| subst.seconds)
686 }
687
688 #[test]
689 fn collect_seconds_bails_on_too_many_ligature_sets() {
690 let ligature_set_count = 17;
691 let mut data = vec![0; 6 + ligature_set_count * 2];
692 data[0..2].copy_from_slice(&1u16.to_be_bytes());
693 data[4..6].copy_from_slice(&(ligature_set_count as u16).to_be_bytes());
694 assert_eq!(
695 seconds_of(&data, &Budget::new(16, 0)).unwrap_err(),
696 Exhausted
697 );
698 }
699
700 #[test]
701 fn collect_seconds_bails_on_too_many_ligatures() {
702 let ligature_count = 16;
703 let mut data = vec![0; 10 + ligature_count * 2];
704 data[0..2].copy_from_slice(&1u16.to_be_bytes());
705 data[4..6].copy_from_slice(&1u16.to_be_bytes());
706 data[6..8].copy_from_slice(&8u16.to_be_bytes());
707 data[8..10].copy_from_slice(&(ligature_count as u16).to_be_bytes());
708 assert_eq!(
709 seconds_of(&data, &Budget::new(16, 0)).unwrap_err(),
710 Exhausted
711 );
712 }
713}