Skip to main content

read_fonts/tables/gsub/closure/
extended.rs

1//! Closure support for the ISO OFF extended GSUB formats.
2
3use super::*;
4use crate::tables::gsub::{
5    AlternateSubstFormat2, Ligature2, LigatureSet2, LigatureSubstFormat2, MultipleSubstFormat2,
6    ReverseChainSingleSubstFormat2, SingleSubstFormat3, SingleSubstFormat4,
7};
8
9impl GlyphClosure for SingleSubstFormat3<'_> {
10    fn closure_glyphs(
11        &self,
12        ctx: &mut ClosureCtx,
13        _lookup_list: &SubstitutionLookupList,
14        _lookup_index: u16,
15    ) -> Result<(), ReadError> {
16        if self.coverage_offset().is_null() {
17            return Ok(());
18        }
19        let coverage = self.coverage()?;
20        let mask = 0xffffff;
21        // Preserve the same degenerate-font guardrails as the 16-bit format.
22        if coverage.population() >= mask as usize {
23            return Ok(());
24        }
25        let intersection = coverage.intersect_set(ctx.parent_active_glyphs());
26        let Some(first) = intersection.first() else {
27            return Ok(());
28        };
29        let delta = self.delta_glyph_id().to_i32();
30        let min_before = first.to_u32();
31        let max_before = intersection.last().unwrap().to_u32();
32        let min_after = min_before.wrapping_add_signed(delta) & mask;
33        let max_after = max_before.wrapping_add_signed(delta) & mask;
34        if intersection.len() == (max_before - min_before + 1) as u64
35            && ((min_before <= min_after && min_after <= max_before)
36                || (min_before <= max_after && max_after <= max_before))
37        {
38            return Ok(());
39        }
40        ctx.output.extend(
41            intersection
42                .iter()
43                .map(|gid| GlyphId::new(gid.to_u32().wrapping_add_signed(delta) & mask)),
44        );
45        Ok(())
46    }
47}
48
49impl GlyphClosure for SingleSubstFormat4<'_> {
50    fn closure_glyphs(
51        &self,
52        ctx: &mut ClosureCtx,
53        _lookup_list: &SubstitutionLookupList,
54        _lookup_index: u16,
55    ) -> Result<(), ReadError> {
56        if self.coverage_offset().is_null() || self.glyph_count().to_u32() == 0 {
57            return Ok(());
58        }
59        let coverage = self.coverage()?;
60        let glyph_set = ctx.active_glyphs_stack.last().unwrap_or(&*ctx.glyphs);
61        let substitutes = self.substitute_glyph_ids();
62        if self.glyph_count().to_u32() as u64 > glyph_set.len() * coverage.cost() as u64 {
63            ctx.output.extend(
64                glyph_set
65                    .iter()
66                    .filter_map(|gid| coverage.get(gid))
67                    .filter_map(|index| substitutes.get(index as usize))
68                    .map(|gid| GlyphId::from(gid.get())),
69            );
70        } else {
71            ctx.output.extend(
72                coverage
73                    .iter()
74                    .zip(substitutes)
75                    .filter(|(gid, _)| glyph_set.contains(*gid))
76                    .map(|(_, gid)| GlyphId::from(gid.get())),
77            );
78        }
79        Ok(())
80    }
81}
82
83macro_rules! intersects_coverage {
84    ($($table:ident),* $(,)?) => {$(
85        impl Intersect for $table<'_> {
86            fn intersects(&self, glyphs: &IntSet<GlyphId>) -> Result<bool, ReadError> {
87                if self.coverage_offset().is_null() {
88                    return Ok(false);
89                }
90                Ok(self.coverage()?.intersects(glyphs))
91            }
92        }
93    )*};
94}
95
96intersects_coverage!(
97    SingleSubstFormat3,
98    SingleSubstFormat4,
99    MultipleSubstFormat2,
100    AlternateSubstFormat2,
101);
102
103macro_rules! closure_array_sets {
104    ($table:ident, $count:ident, $sets:ident, $glyphs:ident) => {
105        impl GlyphClosure for $table<'_> {
106            fn closure_glyphs(
107                &self,
108                ctx: &mut ClosureCtx,
109                _lookup_list: &SubstitutionLookupList,
110                _lookup_index: u16,
111            ) -> Result<(), ReadError> {
112                if self.coverage_offset().is_null() || self.$count().to_u32() == 0 {
113                    return Ok(());
114                }
115                let coverage = self.coverage()?;
116                let glyph_set = ctx.active_glyphs_stack.last().unwrap_or(&*ctx.glyphs);
117                let sets = self.$sets();
118                if self.$count().to_u32() as u64 > glyph_set.len() * coverage.cost() as u64 {
119                    ctx.output.extend(
120                        glyph_set
121                            .iter()
122                            .filter_map(|gid| coverage.get(gid))
123                            .filter_map(|index| sets.get(index as usize).ok())
124                            .flat_map(|set| {
125                                set.$glyphs().iter().map(|gid| GlyphId::from(gid.get()))
126                            }),
127                    );
128                } else {
129                    ctx.output.extend(
130                        coverage
131                            .iter()
132                            .zip(sets.iter_as_nullable())
133                            .filter_map(|(gid, set)| {
134                                if glyph_set.contains(gid) {
135                                    set.transpose().ok().flatten()
136                                } else {
137                                    None
138                                }
139                            })
140                            .flat_map(|set| {
141                                set.$glyphs().iter().map(|gid| GlyphId::from(gid.get()))
142                            }),
143                    );
144                }
145                Ok(())
146            }
147        }
148    };
149}
150
151closure_array_sets!(
152    MultipleSubstFormat2,
153    sequence_count,
154    sequences,
155    substitute_glyph_ids
156);
157closure_array_sets!(
158    AlternateSubstFormat2,
159    alternate_set_count,
160    alternate_sets,
161    alternate_glyph_ids
162);
163
164fn visit_ligatures<'a>(
165    table: &LigatureSubstFormat2<'a>,
166    glyphs: &IntSet<GlyphId>,
167    mut visit: impl FnMut(Ligature2<'a>) -> Result<bool, ReadError>,
168) -> Result<bool, ReadError> {
169    if table.coverage_offset().is_null() || table.ligature_set_count().to_u32() == 0 {
170        return Ok(false);
171    }
172    let coverage = table.coverage()?;
173    let sets = table.ligature_sets();
174    let mut visit_set = |index: usize| {
175        let set = match sets.get(index) {
176            Err(ReadError::NullOffset) => return Ok(false),
177            other => other?,
178        };
179        for ligature in set.ligatures().iter_as_nullable() {
180            let Some(ligature) = ligature.transpose()? else {
181                continue;
182            };
183            if visit(ligature)? {
184                return Ok(true);
185            }
186        }
187        Ok(false)
188    };
189    if table.ligature_set_count().to_u32() as u64 > glyphs.len() * coverage.cost() as u64 {
190        for index in glyphs.iter().filter_map(|gid| coverage.get(gid)) {
191            if visit_set(index as usize)? {
192                return Ok(true);
193            }
194        }
195    } else {
196        for (index, gid) in coverage.iter().enumerate() {
197            if glyphs.contains(gid) && visit_set(index)? {
198                return Ok(true);
199            }
200        }
201    }
202    Ok(false)
203}
204
205impl GlyphClosure for LigatureSubstFormat2<'_> {
206    fn closure_glyphs(
207        &self,
208        ctx: &mut ClosureCtx,
209        _lookup_list: &SubstitutionLookupList,
210        _lookup_index: u16,
211    ) -> Result<(), ReadError> {
212        let active = ctx.active_glyphs_stack.last().unwrap_or(&*ctx.glyphs);
213        visit_ligatures(self, active, |ligature| {
214            if ligature.intersects(ctx.glyphs)? {
215                ctx.output.insert(ligature.ligature_glyph().into());
216            }
217            Ok(false)
218        })?;
219        Ok(())
220    }
221}
222
223impl Intersect for LigatureSubstFormat2<'_> {
224    fn intersects(&self, glyphs: &IntSet<GlyphId>) -> Result<bool, ReadError> {
225        visit_ligatures(self, glyphs, |ligature| ligature.intersects(glyphs))
226    }
227}
228
229impl Intersect for LigatureSet2<'_> {
230    fn intersects(&self, glyphs: &IntSet<GlyphId>) -> Result<bool, ReadError> {
231        for ligature in self.ligatures().iter_as_nullable().flatten() {
232            if ligature?.intersects(glyphs)? {
233                return Ok(true);
234            }
235        }
236        Ok(false)
237    }
238}
239
240impl Intersect for Ligature2<'_> {
241    fn intersects(&self, glyphs: &IntSet<GlyphId>) -> Result<bool, ReadError> {
242        Ok(self
243            .component_glyph_ids()
244            .iter()
245            .all(|gid| glyphs.contains(gid.get().into())))
246    }
247}
248
249impl Intersect for ReverseChainSingleSubstFormat2<'_> {
250    fn intersects(&self, glyphs: &IntSet<GlyphId>) -> Result<bool, ReadError> {
251        if self.coverage_offset().is_null() || !self.coverage()?.intersects(glyphs) {
252            return Ok(false);
253        }
254        for coverage in self
255            .backtrack_coverages()
256            .iter_as_nullable()
257            .chain(self.lookahead_coverages().iter_as_nullable())
258        {
259            let Some(coverage) = coverage.transpose()? else {
260                return Ok(false);
261            };
262            if !coverage.intersects(glyphs) {
263                return Ok(false);
264            }
265        }
266        Ok(true)
267    }
268}
269
270impl GlyphClosure for ReverseChainSingleSubstFormat2<'_> {
271    fn closure_glyphs(
272        &self,
273        ctx: &mut ClosureCtx,
274        _lookup_list: &SubstitutionLookupList,
275        _lookup_index: u16,
276    ) -> Result<(), ReadError> {
277        if !self.intersects(ctx.glyphs())? {
278            return Ok(());
279        }
280        let coverage = self.coverage()?;
281        let glyphs = ctx.active_glyphs_stack.last().unwrap_or(&*ctx.glyphs);
282        let substitutes = self.substitute_glyph_ids();
283        if self.glyph_count().to_u32() as u64 > glyphs.len() * coverage.cost() as u64 {
284            ctx.output.extend(
285                glyphs
286                    .iter()
287                    .filter_map(|gid| coverage.get(gid))
288                    .filter_map(|index| substitutes.get(index as usize))
289                    .map(|gid| GlyphId::from(gid.get())),
290            );
291        } else {
292            ctx.output.extend(
293                coverage
294                    .iter()
295                    .zip(substitutes)
296                    .filter(|(gid, _)| glyphs.contains(*gid))
297                    .map(|(_, gid)| GlyphId::from(gid.get())),
298            );
299        }
300        Ok(())
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307    use crate::FontData;
308    use font_test_data::bebuffer::BeBuffer;
309    use font_types::{GlyphId24, Int24, Uint24};
310
311    fn gsub_with_lookup(kind: u16, subtable: &[u8]) -> Vec<u8> {
312        BeBuffer::new()
313            .push(1u16)
314            .push(2u16)
315            .push(0u16)
316            .push(0u16)
317            .push(0u16)
318            .push(0u32)
319            .push(0u32)
320            .push(0u32)
321            .push(26u32)
322            .push(1u16)
323            .push(6u32)
324            .push(kind)
325            .push(0u16)
326            .push(1u16)
327            .push(8u16)
328            .extend(subtable.iter().copied())
329            .to_vec()
330    }
331
332    fn close_lookup(kind: u16, subtable: &[u8], inputs: &[u32]) -> Vec<u32> {
333        let bytes = gsub_with_lookup(kind, subtable);
334        let gsub = Gsub::read(FontData::new(&bytes)).unwrap();
335        let mut glyphs: IntSet<_> = inputs.iter().copied().map(GlyphId::new).collect();
336        let mut lookups: IntSet<_> = [0].into_iter().collect();
337        gsub.closure_lookups(&glyphs, &mut lookups).unwrap();
338        assert_eq!(lookups.iter().collect::<Vec<_>>(), [0]);
339        gsub.closure_glyphs(&lookups, &mut glyphs).unwrap();
340        glyphs.iter().map(GlyphId::to_u32).collect()
341    }
342
343    fn close(subtable: &[u8], inputs: &[u32]) -> Vec<u32> {
344        close_lookup(1, subtable, inputs)
345    }
346
347    #[test]
348    fn single_subst3_closure_wraps_signed_24bit_deltas() {
349        for (input, delta, output) in [
350            (65535, 1, 65536),
351            (65536, -1, 65535),
352            (0, -1, 0xffffff),
353            (0xffffff, 1, 0),
354            (0x800000, -0x800000, 0),
355            (0, 0x7fffff, 0x7fffff),
356        ] {
357            let subtable = BeBuffer::new()
358                .push(3u16)
359                .push(9u32)
360                .push(Int24::new(delta))
361                .push(3u16)
362                .push(Uint24::new(1))
363                .push(GlyphId24::new(input));
364            let mut expected = vec![input, output];
365            expected.sort_unstable();
366            expected.dedup();
367            assert_eq!(close(&subtable, &[input]), expected);
368        }
369    }
370
371    #[test]
372    fn single_subst4_closure_repeats_until_stable() {
373        let subtable = BeBuffer::new()
374            .push(4u16)
375            .push(18u32)
376            .push(Uint24::new(3))
377            .extend([65536, 0, 0xffffff].map(GlyphId24::new))
378            .push(3u16)
379            .push(Uint24::new(3))
380            .extend([65535, 65536, 70000].map(GlyphId24::new));
381        assert_eq!(
382            close(&subtable, &[65535, 70000]),
383            [0, 65535, 65536, 70000, 0xffffff]
384        );
385    }
386
387    #[test]
388    fn single_subst4_closure_keeps_full_width_coverage_indices() {
389        let count = 65537u32;
390        let subtable = BeBuffer::new()
391            .push(4u16)
392            .push(9 + count * 3)
393            .push(Uint24::new(count))
394            .extend((0..count).map(|gid| GlyphId24::new(if gid == 65536 { 70000 } else { 0 })))
395            .push(4u16)
396            .push(Uint24::new(1))
397            .extend([0, 65536, 0].map(Uint24::new));
398        assert_eq!(close(&subtable, &[65536]), [65536, 70000]);
399    }
400
401    #[test]
402    fn single_subst_wide_null_and_truncated_tables() {
403        for subtable in [
404            BeBuffer::new()
405                .push(3u16)
406                .push(0u32)
407                .push(Int24::new(1))
408                .to_vec(),
409            BeBuffer::new()
410                .push(4u16)
411                .push(0u32)
412                .push(Uint24::new(0))
413                .to_vec(),
414        ] {
415            let bytes = gsub_with_lookup(1, &subtable);
416            let gsub = Gsub::read(FontData::new(&bytes)).unwrap();
417            let mut glyphs: IntSet<_> = [GlyphId::new(65536)].into_iter().collect();
418            let mut lookups: IntSet<_> = [0].into_iter().collect();
419            gsub.closure_lookups(&glyphs, &mut lookups).unwrap();
420            assert!(lookups.is_empty());
421            gsub.closure_glyphs(&IntSet::all(), &mut glyphs).unwrap();
422            assert_eq!(glyphs.iter().collect::<Vec<_>>(), [GlyphId::new(65536)]);
423        }
424        let truncated = BeBuffer::new()
425            .push(4u16)
426            .push(12u32)
427            .push(Uint24::new(2))
428            .push(GlyphId24::new(70000));
429        let bytes = gsub_with_lookup(1, &truncated);
430        let gsub = Gsub::read(FontData::new(&bytes)).unwrap();
431        let mut glyphs = [GlyphId::new(65536)].into_iter().collect();
432        assert!(gsub.closure_glyphs(&IntSet::all(), &mut glyphs).is_err());
433    }
434
435    #[test]
436    fn wide_multiple_and_alternate_closure_is_transitive() {
437        let subtable = BeBuffer::new()
438            .push(2u16)
439            .push(15u32)
440            .push(Uint24::new(2))
441            .extend([26, 34].map(Uint24::new))
442            .push(3u16)
443            .push(Uint24::new(2))
444            .extend([65536, 70000].map(GlyphId24::new))
445            .push(2u16)
446            .extend([70000, 65535].map(GlyphId24::new))
447            .push(1u16)
448            .push(GlyphId24::new(0xffffff));
449        for kind in [2, 3] {
450            assert_eq!(
451                close_lookup(kind, &subtable, &[65536]),
452                [65535, 65536, 70000, 0xffffff]
453            );
454            assert_eq!(
455                close_lookup(kind, &subtable, &[65536, 70000]),
456                [65535, 65536, 70000, 0xffffff]
457            );
458        }
459    }
460
461    #[test]
462    fn wide_multiple_and_alternate_closure_keeps_large_indices_and_offsets() {
463        let count = 65537u32;
464        let coverage_offset = 9 + count * 3;
465        let sequence_offset = coverage_offset + 14;
466        let subtable = BeBuffer::new()
467            .push(2u16)
468            .push(coverage_offset)
469            .push(Uint24::new(count))
470            .extend(
471                (0..count)
472                    .map(|index| Uint24::new(if index == 65536 { sequence_offset } else { 0 })),
473            )
474            .push(4u16)
475            .push(Uint24::new(1))
476            .extend([0, 65536, 0].map(Uint24::new))
477            .push(1u16)
478            .push(GlyphId24::new(70000));
479        for kind in [2, 3] {
480            assert_eq!(close_lookup(kind, &subtable, &[65536]), [65536, 70000]);
481        }
482    }
483
484    #[test]
485    fn wide_multiple_and_alternate_closure_skips_null_and_invalid_sets() {
486        for kind in [2, 3] {
487            for offset in [0, 0xffffff] {
488                let subtable = BeBuffer::new()
489                    .push(2u16)
490                    .push(12u32)
491                    .push(Uint24::new(1))
492                    .push(Uint24::new(offset))
493                    .push(3u16)
494                    .push(Uint24::new(1))
495                    .push(GlyphId24::new(65536));
496                assert_eq!(close_lookup(kind, &subtable, &[65536]), [65536]);
497            }
498        }
499    }
500
501    fn ligature_subtable() -> Vec<u8> {
502        BeBuffer::new()
503            .push(2u16)
504            .push(12u32)
505            .push(Uint24::new(1))
506            .push(Uint24::new(20))
507            .push(3u16)
508            .push(Uint24::new(1))
509            .push(GlyphId24::new(65536))
510            .push(2u16)
511            .extend([8, 16].map(Uint24::new))
512            .push(GlyphId24::new(70000))
513            .push(2u16)
514            .push(GlyphId24::new(65535))
515            .push(GlyphId24::new(0xffffff))
516            .push(2u16)
517            .push(GlyphId24::new(70000))
518            .to_vec()
519    }
520
521    #[test]
522    fn wide_ligature_closure_requires_all_components_and_repeats() {
523        assert_eq!(
524            close_lookup(4, &ligature_subtable(), &[65535, 65536]),
525            [65535, 65536, 70000, 0xffffff]
526        );
527        let bytes = gsub_with_lookup(4, &ligature_subtable());
528        let gsub = Gsub::read(FontData::new(&bytes)).unwrap();
529        let mut glyphs = [GlyphId::new(65536)].into_iter().collect();
530        let mut lookups = [0].into_iter().collect();
531        gsub.closure_lookups(&glyphs, &mut lookups).unwrap();
532        assert!(lookups.is_empty());
533        gsub.closure_glyphs(&IntSet::all(), &mut glyphs).unwrap();
534        assert_eq!(glyphs.iter().collect::<Vec<_>>(), [GlyphId::new(65536)]);
535    }
536
537    #[test]
538    fn wide_ligature_closure_keeps_large_indices_and_offsets() {
539        let count = 65537u32;
540        let coverage_offset = 9 + count * 3;
541        let set_offset = coverage_offset + 14;
542        let subtable = BeBuffer::new()
543            .push(2u16)
544            .push(coverage_offset)
545            .push(Uint24::new(count))
546            .extend(
547                (0..count).map(|index| Uint24::new(if index == 65536 { set_offset } else { 0 })),
548            )
549            .push(4u16)
550            .push(Uint24::new(1))
551            .extend([0, 65536, 0].map(Uint24::new))
552            .push(1u16)
553            .push(Uint24::new(5))
554            .push(GlyphId24::new(70000))
555            .push(2u16)
556            .push(GlyphId24::new(70001));
557        assert_eq!(
558            close_lookup(4, &subtable, &[65536, 70001]),
559            [65536, 70000, 70001]
560        );
561    }
562
563    #[test]
564    fn wide_ligature_closure_skips_null_offsets_but_reports_invalid_ones() {
565        for offset in [0, 0xffffff] {
566            let subtable = BeBuffer::new()
567                .push(2u16)
568                .push(12u32)
569                .push(Uint24::new(1))
570                .push(Uint24::new(offset))
571                .push(3u16)
572                .push(Uint24::new(1))
573                .push(GlyphId24::new(65536));
574            let bytes = gsub_with_lookup(4, &subtable);
575            let gsub = Gsub::read(FontData::new(&bytes)).unwrap();
576            let mut glyphs = [GlyphId::new(65536)].into_iter().collect();
577            let result = gsub.closure_glyphs(&IntSet::all(), &mut glyphs);
578            assert_eq!(result.is_ok(), offset == 0);
579        }
580    }
581
582    fn reverse_subtable(backtrack_offset: u32, lookahead_offset: u32) -> Vec<u8> {
583        BeBuffer::new()
584            .push(2u16)
585            .push(22u32)
586            .push(1u16)
587            .push(Uint24::new(backtrack_offset))
588            .push(1u16)
589            .push(Uint24::new(lookahead_offset))
590            .push(Uint24::new(1))
591            .push(GlyphId24::new(70000))
592            .push(3u16)
593            .push(Uint24::new(1))
594            .push(GlyphId24::new(65536))
595            .push(3u16)
596            .push(Uint24::new(1))
597            .push(GlyphId24::new(65535))
598            .push(3u16)
599            .push(Uint24::new(1))
600            .push(GlyphId24::new(0xffffff))
601            .to_vec()
602    }
603
604    #[test]
605    fn wide_reverse_closure_requires_backtrack_and_lookahead() {
606        let subtable = reverse_subtable(30, 38);
607        assert_eq!(
608            close_lookup(8, &subtable, &[65535, 65536, 0xffffff]),
609            [65535, 65536, 70000, 0xffffff]
610        );
611        for inputs in [vec![65536], vec![65535, 65536], vec![65536, 0xffffff]] {
612            let bytes = gsub_with_lookup(8, &subtable);
613            let gsub = Gsub::read(FontData::new(&bytes)).unwrap();
614            let mut glyphs = inputs.iter().copied().map(GlyphId::new).collect();
615            let mut lookups = [0].into_iter().collect();
616            gsub.closure_lookups(&glyphs, &mut lookups).unwrap();
617            assert!(lookups.is_empty());
618            gsub.closure_glyphs(&IntSet::all(), &mut glyphs).unwrap();
619            assert_eq!(
620                glyphs.iter().map(GlyphId::to_u32).collect::<Vec<_>>(),
621                inputs
622            );
623        }
624    }
625
626    #[test]
627    fn wide_reverse_closure_keeps_large_coverage_indices() {
628        let count = 65537u32;
629        let subtable = BeBuffer::new()
630            .push(2u16)
631            .push(13 + 3 * count)
632            .push(0u16)
633            .push(0u16)
634            .push(Uint24::new(count))
635            .extend((0..count).map(|index| GlyphId24::new(if index == 65536 { 70000 } else { 0 })))
636            .push(4u16)
637            .push(Uint24::new(1))
638            .extend([0, 65536, 0].map(Uint24::new));
639        assert_eq!(close_lookup(8, &subtable, &[65536]), [65536, 70000]);
640    }
641
642    #[test]
643    fn wide_reverse_closure_handles_null_and_invalid_context_offsets() {
644        let glyphs: IntSet<_> = [65535, 65536, 0xffffff]
645            .map(GlyphId::new)
646            .into_iter()
647            .collect();
648        for (backtrack, lookahead) in [(0, 38), (30, 0), (0xffffff, 38), (30, 0xffffff)] {
649            let bytes = reverse_subtable(backtrack, lookahead);
650            let subtable = ReverseChainSingleSubstFormat2::read(FontData::new(&bytes)).unwrap();
651            if backtrack == 0 || lookahead == 0 {
652                assert!(!subtable.intersects(&glyphs).unwrap());
653            } else {
654                assert!(subtable.intersects(&glyphs).is_err());
655            }
656        }
657    }
658}