Skip to main content

harfrust/aat/
kerx.rs

1use super::layout::DELETED_GLYPH;
2use crate::aat::common::{
3    get_class, set_digest, AatApplyContext, ClassCache, SafeToBreakAccel, SafeToBreakSubtable,
4    TypedCollectGlyphs, START_OF_TEXT,
5};
6use crate::aat::kern::apply_pair_kerning;
7use crate::set_digest::SetDigest;
8use crate::U32Set;
9use crate::{
10    buffer::*,
11    ot::apply::{ApplyContext, SkippingIterator},
12    ot::gpos::attach_type,
13    ot::layout::LayoutTableKind,
14    ot::lookup_flags,
15};
16use alloc::boxed::Box;
17use core::convert::TryFrom;
18use read_fonts::{
19    tables::{
20        aat,
21        ankr::Ankr,
22        kerx::{
23            Subtable, Subtable0, Subtable1, Subtable2, Subtable4, Subtable4Actions, Subtable6,
24            SubtableKind,
25        },
26    },
27    types::{BigEndian, FixedSize, GlyphId},
28    FontData,
29};
30
31// Only tracing messages read the subtable index.
32#[cfg_attr(not(feature = "tracing"), allow(clippy::unused_enumerate_index))]
33pub(crate) fn apply(c: &mut AatApplyContext) -> Option<()> {
34    c.buffer.unsafe_to_concat(None, None);
35
36    c.setup_buffer_glyph_set();
37
38    let cache = c.layout.aat.kerx_cache()?;
39    let subtable_caches = &cache.subtables;
40    c.setup_buffer_digest(subtable_caches.len());
41    let safe_to_break = &cache.safe_to_break;
42
43    let mut seen_cross_stream = false;
44    for (_index, subtable_cache) in subtable_caches.iter().enumerate() {
45        let subtable = &subtable_cache.subtable;
46        #[cfg(feature = "tracing")]
47        let message_index = _index;
48
49        if c.buffer.direction.is_horizontal() != subtable.is_horizontal() {
50            continue;
51        }
52
53        c.first_set = Some(&subtable_cache.first_set);
54        c.first_digest = subtable_cache.first_digest.clone();
55        c.second_set = Some(&subtable_cache.second_set);
56        c.machine_class_cache = Some(&subtable_cache.class_cache);
57        c.start_end_safe_to_break = subtable_cache.start_end_safe_to_break;
58        c.safe_to_break = safe_to_break.subtable(subtable_cache.safe_to_break)?;
59
60        if !c.buffer_intersects_machine() {
61            message!(
62                c,
63                "skipped subtable {} because no glyph matches",
64                message_index
65            );
66            continue;
67        }
68
69        let reverse = c.buffer.direction.is_backward();
70
71        message_continue!(c, "start subtable {}", message_index);
72
73        if !seen_cross_stream && subtable.is_cross_stream() {
74            seen_cross_stream = true;
75
76            // Attach all glyphs into a chain.
77            for pos in &mut c.buffer.pos {
78                pos.set_attach_type(attach_type::CURSIVE);
79                pos.set_attach_chain(if c.buffer.direction.is_forward() {
80                    -1
81                } else {
82                    1
83                });
84                // We intentionally don't set BufferScratchFlags::HAS_GPOS_ATTACHMENT,
85                // since there needs to be a non-zero attachment for post-positioning to
86                // be needed.
87            }
88        }
89
90        let Some(kind) = &subtable_cache.kind else {
91            continue;
92        };
93
94        if reverse != c.buffer_is_reversed {
95            c.reverse_buffer();
96        }
97
98        match kind {
99            SubtableKind::Format0(format0) => {
100                if c.plan.requested_kerning {
101                    apply_simple_kerning(c, subtable, format0);
102                }
103            }
104            SubtableKind::Format1(format1) => {
105                let mut driver = Driver1 {
106                    stack: [0; 8],
107                    depth: 0,
108                };
109                if apply_state_machine_kerning(
110                    c,
111                    subtable,
112                    format1,
113                    &format1.state_table,
114                    &mut driver,
115                )
116                .is_none()
117                {
118                    c.buffer.index_failed();
119                }
120            }
121            SubtableKind::Format2(format2) => {
122                if c.plan.requested_kerning {
123                    apply_simple_kerning(c, subtable, format2);
124                }
125            }
126            SubtableKind::Format4(format4) => {
127                let mut driver = Driver4 {
128                    mark_set: false,
129                    mark: 0,
130                    ankr_table: c.layout.aat.ankr.clone(),
131                };
132                if apply_state_machine_kerning(
133                    c,
134                    subtable,
135                    format4,
136                    &format4.state_table,
137                    &mut driver,
138                )
139                .is_none()
140                {
141                    c.buffer.index_failed();
142                }
143            }
144            SubtableKind::Format6(format6) => {
145                if c.plan.requested_kerning {
146                    apply_simple_kerning(c, subtable, format6);
147                }
148            }
149        }
150        message!(c, "end subtable {}", message_index);
151    }
152
153    if c.buffer_is_reversed {
154        c.reverse_buffer();
155    }
156
157    Some(())
158}
159
160pub trait SimpleKerning {
161    fn simple_kerning(&self, left: GlyphId, right: GlyphId) -> Option<i32>;
162    fn resolve_tuple_kerning(&self, value: i32, _tuple_count: u32) -> Option<i32> {
163        Some(value)
164    }
165    fn collect_glyphs(&self, _first_set: &mut U32Set, _second_set: &mut U32Set, _num_glyphs: u32);
166}
167
168// HarfBuzz supports kerx tuple kerning "without the variation part": values
169// are offsets to an array of tupleCount FWORDs, of which it applies the first.
170fn resolve_tuple_kerning(value: i32, tuple_count: u32, data: FontData<'_>) -> Option<i32> {
171    if tuple_count == 0 {
172        return Some(value);
173    }
174
175    let offset = usize::try_from(value).ok()?;
176    data.read_at::<i16>(offset).ok().map(i32::from)
177}
178
179impl SimpleKerning for Subtable0<'_> {
180    fn simple_kerning(&self, left: GlyphId, right: GlyphId) -> Option<i32> {
181        self.kerning(left, right)
182    }
183    fn resolve_tuple_kerning(&self, value: i32, tuple_count: u32) -> Option<i32> {
184        resolve_tuple_kerning(value, tuple_count, self.offset_data())
185    }
186    fn collect_glyphs(&self, first_set: &mut U32Set, second_set: &mut U32Set, _num_glyphs: u32) {
187        for &pair in self.pairs() {
188            first_set.insert(pair.left.get().to_u32());
189            second_set.insert(pair.right.get().to_u32());
190        }
191    }
192}
193
194impl SimpleKerning for Subtable2<'_> {
195    fn simple_kerning(&self, left: GlyphId, right: GlyphId) -> Option<i32> {
196        self.kerning(left, right)
197    }
198    fn resolve_tuple_kerning(&self, value: i32, tuple_count: u32) -> Option<i32> {
199        resolve_tuple_kerning(value, tuple_count, self.data)
200    }
201    fn collect_glyphs(&self, first_set: &mut U32Set, second_set: &mut U32Set, num_glyphs: u32) {
202        let left_classes = &self.left_offset_table;
203        let right_classes = &self.right_offset_table;
204
205        left_classes.collect_glyphs(first_set, num_glyphs);
206        right_classes.collect_glyphs(second_set, num_glyphs);
207    }
208}
209
210impl SimpleKerning for Subtable6<'_> {
211    fn simple_kerning(&self, left: GlyphId, right: GlyphId) -> Option<i32> {
212        self.kerning(left, right)
213    }
214    fn collect_glyphs(&self, first_set: &mut U32Set, second_set: &mut U32Set, num_glyphs: u32) {
215        match &self {
216            Self::ShortValues(rows, columns, ..) => {
217                rows.collect_glyphs(first_set, num_glyphs);
218                columns.collect_glyphs(second_set, num_glyphs);
219            }
220            Self::LongValues(rows, columns, ..) => {
221                rows.collect_glyphs(first_set, num_glyphs);
222                columns.collect_glyphs(second_set, num_glyphs);
223            }
224        }
225    }
226}
227
228fn apply_simple_kerning<T: SimpleKerning>(c: &mut AatApplyContext, subtable: &Subtable, kind: &T) {
229    message_return!(c, "start kern");
230    let scale = c.scale;
231    let mut ctx = ApplyContext::new(
232        LayoutTableKind::Gpos,
233        c.layout,
234        c.scale,
235        c.buffer,
236        #[cfg(feature = "tracing")]
237        c.font,
238    );
239    ctx.set_lookup_mask(c.plan.kern_mask);
240    ctx.lookup_props = u32::from(lookup_flags::IGNORE_MARKS);
241    ctx.update_matchers();
242
243    let horizontal = ctx.buffer.direction.is_horizontal();
244    let cross_stream = subtable.is_cross_stream();
245    let use_x_scale = horizontal ^ cross_stream;
246
247    let first_set = c.first_set.as_ref().unwrap();
248    let second_set = c.second_set.as_ref().unwrap();
249
250    let mut i = 0;
251    let mut iter = SkippingIterator::new(&mut ctx, false);
252    while i < iter.buffer.len {
253        if iter
254            .buffer
255            .info
256            .get(i)
257            .is_none_or(|info| info.mask & c.plan.kern_mask == 0)
258        {
259            i += 1;
260            continue;
261        }
262
263        iter.reset_fast(i);
264
265        let mut unsafe_to = 0;
266        if !iter.next(Some(&mut unsafe_to)) {
267            iter.buffer.unsafe_to_concat(Some(i), Some(unsafe_to));
268            i += 1;
269            continue;
270        }
271
272        let j = iter.index();
273
274        let info = &iter.buffer.info;
275        let (Some(first), Some(second)) = (info.get(i), info.get(j)) else {
276            i = j;
277            continue;
278        };
279        let a = first.as_glyph();
280        let b = second.as_glyph();
281        let kern = if !first_set.contains(a.to_u32()) || !second_set.contains(b.to_u32()) {
282            0
283        } else {
284            kind.simple_kerning(a, b)
285                .and_then(|value| kind.resolve_tuple_kerning(value, subtable.tuple_count()))
286                .unwrap_or(0)
287        };
288        let kern = if use_x_scale {
289            scale.scale_x(kern)
290        } else {
291            scale.scale_y(kern)
292        };
293
294        let pos = &mut iter.buffer.pos;
295        if kern != 0 {
296            apply_pair_kerning(pos, i, j, kern, horizontal, cross_stream);
297            if cross_stream {
298                iter.buffer.scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;
299            }
300
301            iter.buffer.unsafe_to_break(Some(i), Some(j + 1));
302        }
303
304        i = j;
305    }
306    message!(ctx, "end kern");
307}
308
309pub(crate) trait KerxStateEntryExt {
310    fn flags(&self) -> u16;
311    fn action_index(&self) -> u16;
312
313    fn is_action_initiable(&self) -> bool {
314        self.flags() & 0x8000 != 0
315    }
316
317    fn is_actionable(&self) -> bool {
318        self.action_index() != 0xFFFF
319    }
320
321    fn has_advance(&self) -> bool {
322        self.flags() & 0x4000 == 0
323    }
324
325    fn has_reset(&self) -> bool {
326        self.flags() & 0x2000 != 0
327    }
328
329    fn has_push(&self) -> bool {
330        self.flags() & 0x8000 != 0
331    }
332
333    fn has_mark(&self) -> bool {
334        self.flags() & 0x8000 != 0
335    }
336}
337
338impl KerxStateEntryExt for aat::StateEntry<BigEndian<u16>> {
339    fn flags(&self) -> u16 {
340        self.flags
341    }
342
343    fn action_index(&self) -> u16 {
344        self.payload.get()
345    }
346}
347
348fn collect_initial_glyphs<T>(
349    machine: &aat::ExtendedStateTable<T>,
350    glyphs: &mut U32Set,
351    num_glyphs: u32,
352) where
353    T: FixedSize + bytemuck::AnyBitPattern,
354    aat::StateEntry<T>: KerxStateEntryExt,
355{
356    let mut classes = U32Set::default();
357
358    let class_table = &machine.class_table;
359    for i in 0..machine.n_classes {
360        if let Ok(entry) = machine.entry(START_OF_TEXT, i as u16) {
361            if entry.new_state == START_OF_TEXT
362                && !entry.is_action_initiable()
363                && !entry.is_actionable()
364            {
365                continue;
366            }
367            classes.insert(i as u32);
368        }
369    }
370
371    // And glyphs in those classes.
372
373    let filter = crate::aat::common::class_set_filter(&classes);
374
375    if filter(aat::class::DELETED_GLYPH as u16) {
376        glyphs.insert(DELETED_GLYPH);
377    }
378
379    class_table.collect_glyphs_filtered(glyphs, num_glyphs, filter);
380}
381
382fn collect_start_end_safe_to_break<T>(machine: &aat::ExtendedStateTable<T>) -> u64
383where
384    T: FixedSize + bytemuck::AnyBitPattern,
385    aat::StateEntry<T>: KerxStateEntryExt,
386{
387    let mut result = 0u64;
388    for state in 0..64 {
389        let bit = if let Ok(entry) = machine.entry(state, aat::class::END_OF_TEXT as u16) {
390            !entry.is_actionable()
391        } else {
392            true
393        };
394        if bit {
395            result |= 1 << state;
396        }
397    }
398    result
399}
400
401fn apply_state_machine_kerning<T, E, Driver: StateTableDriver<T, E>>(
402    c: &mut AatApplyContext,
403    subtable: &Subtable,
404    kind: &T,
405    state_table: &aat::ExtendedStateTable<E>,
406    driver: &mut Driver,
407) -> Option<()>
408where
409    E: FixedSize + bytemuck::AnyBitPattern,
410    aat::StateEntry<E>: KerxStateEntryExt,
411{
412    let mut state = START_OF_TEXT;
413    // Condition 3 below, precomputed for the start-of-text state: no
414    // end-of-text action can fire if we stop while in the start state.
415    let start_state_safe_to_break_eot = (c.start_end_safe_to_break & (1 << START_OF_TEXT)) != 0;
416    c.buffer.idx = 0;
417    'drive: loop {
418        let class = if c.buffer.idx < c.buffer.len {
419            get_class(
420                state_table,
421                c.buffer.cur(0)?.as_glyph(),
422                c.machine_class_cache.unwrap(),
423            )
424        } else {
425            u16::from(aat::class::END_OF_TEXT)
426        };
427
428        let Ok(entry) = state_table.entry(state, class) else {
429            break;
430        };
431
432        let next_state = entry.new_state;
433
434        // Fast path for when transitioning from start-state to start-state with
435        // no action and advancing. Do so as long as the class remains the same.
436        // This is common with runs of non-actionable glyphs.
437        if state == START_OF_TEXT
438            && next_state == START_OF_TEXT
439            && start_state_safe_to_break_eot
440            && !entry.is_actionable()
441            && entry.has_advance()
442        {
443            let old_class = class;
444            loop {
445                let _ = driver.transition(
446                    kind,
447                    &entry,
448                    subtable.is_cross_stream(),
449                    subtable.tuple_count(),
450                    c,
451                );
452                if c.buffer.idx >= c.buffer.len {
453                    break 'drive;
454                }
455                c.buffer.next_glyph();
456                c.buffer.max_ops -= 1;
457
458                let new_class = if c.buffer.idx < c.buffer.len {
459                    get_class(
460                        state_table,
461                        c.buffer.cur(0)?.as_glyph(),
462                        c.machine_class_cache.unwrap(),
463                    )
464                } else {
465                    u16::from(aat::class::END_OF_TEXT)
466                };
467                if new_class != old_class {
468                    break;
469                }
470            }
471            if c.buffer.idx >= c.buffer.len {
472                break 'drive;
473            }
474            continue 'drive;
475        }
476
477        // Conditions under which it's guaranteed safe-to-break before current glyph:
478        //
479        // 1. There was no action in this transition; and
480        //
481        // 2. If we break before current glyph, the results will be the same. That
482        //    is guaranteed if:
483        //
484        //    2a. We were already in start-of-text state; or
485        //
486        //    2b. We are epsilon-transitioning to start-of-text state; or
487        //
488        //    2c. Starting from start-of-text state seeing current glyph:
489        //
490        //        2c'. There won't be any actions; and
491        //
492        //        2c". We would end up in the same state that we were going to end up
493        //             in now, including whether epsilon-transitioning.
494        //
495        //    and
496        //
497        // 3. If we break before current glyph, there won't be any end-of-text action
498        //    after previous glyph.
499        //
500        // This triples the transitions we need to look up, but is worth returning
501        // granular unsafe-to-break results. See eg.:
502        //
503        //   https://github.com/harfbuzz/harfbuzz/issues/2860
504
505        let is_safe_to_break =
506            // 1
507            !entry.is_actionable() &&
508
509            // 2
510            (
511                state == START_OF_TEXT
512                || (!entry.has_advance() && next_state == START_OF_TEXT)
513                // 2c, 2c', 2c"
514                || c.safe_to_break.wouldbe_matches(class, next_state, entry.has_advance())
515            ) &&
516
517            // 3
518            (
519                if state < 64 {
520                    (c.start_end_safe_to_break & (1 << state)) != 0
521                } else {
522                    c.safe_to_break.eot_safe_high(state)
523                }
524            )
525        ;
526
527        if !is_safe_to_break && c.buffer.backtrack_len() > 0 && c.buffer.idx < c.buffer.len {
528            c.buffer.unsafe_to_break_from_outbuffer(
529                Some(c.buffer.backtrack_len() - 1),
530                Some(c.buffer.idx + 1),
531            );
532        }
533
534        let _ = driver.transition(
535            kind,
536            &entry,
537            subtable.is_cross_stream(),
538            subtable.tuple_count(),
539            c,
540        );
541
542        state = next_state;
543
544        if c.buffer.idx >= c.buffer.len {
545            break;
546        }
547
548        if entry.has_advance() || c.buffer.max_ops <= 0 {
549            c.buffer.next_glyph();
550        }
551        c.buffer.max_ops -= 1;
552    }
553    Some(())
554}
555
556trait StateTableDriver<T, E> {
557    fn transition(
558        &mut self,
559        aat: &T,
560        entry: &aat::StateEntry<E>,
561        has_cross_stream: bool,
562        tuple_count: u32,
563        c: &mut AatApplyContext,
564    ) -> Option<()>;
565}
566
567struct Driver1 {
568    stack: [usize; 8],
569    depth: usize,
570}
571
572impl StateTableDriver<Subtable1<'_>, BigEndian<u16>> for Driver1 {
573    #[inline(always)]
574    fn transition(
575        &mut self,
576        aat: &Subtable1,
577        entry: &aat::StateEntry<BigEndian<u16>>,
578        has_cross_stream: bool,
579        tuple_count: u32,
580        c: &mut AatApplyContext,
581    ) -> Option<()> {
582        if entry.has_reset() {
583            self.depth = 0;
584        }
585
586        if entry.has_push() {
587            if self.depth < self.stack.len() {
588                self.stack[self.depth] = c.buffer.idx;
589                self.depth += 1;
590            } else {
591                self.depth = 0; // Probably not what CoreText does, but better?
592            }
593        }
594
595        if entry.is_actionable() && self.depth != 0 {
596            let tuple_count = u16::try_from(tuple_count.max(1)).ok()?;
597
598            let mut action_index = entry.action_index();
599
600            // From Apple 'kern' spec:
601            // "Each pops one glyph from the kerning stack and applies the kerning value to it.
602            // The end of the list is marked by an odd value...
603            let mut last = false;
604            let use_x_scale = c.buffer.direction.is_horizontal() ^ has_cross_stream;
605            while !last && self.depth != 0 {
606                self.depth -= 1;
607                let idx = self.stack[self.depth];
608                let mut v = aat.values.get(action_index as usize)?.get() as i32;
609                action_index = action_index.checked_add(tuple_count)?;
610                if idx >= c.buffer.len {
611                    continue;
612                }
613
614                // "The end of the list is marked by an odd value..."
615                last = v & 1 != 0;
616                v &= !1;
617                let scaled_v = if use_x_scale {
618                    c.scale_x(v)
619                } else {
620                    c.scale_y(v)
621                };
622                // Testing shows that CoreText only applies kern (cross-stream or not)
623                // if none has been applied by previous subtables. That is, it does
624                // NOT seem to accumulate as otherwise implied by specs.
625
626                let mut has_gpos_attachment = false;
627                let (Some(info), Some(pos)) = (c.buffer.info.get(idx), c.buffer.pos.get_mut(idx))
628                else {
629                    continue;
630                };
631                let glyph_mask = info.mask;
632
633                if c.buffer.direction.is_horizontal() {
634                    if has_cross_stream {
635                        // The following flag is undocumented in the spec, but described
636                        // in the 'kern' table example.
637                        if v == -0x8000 {
638                            pos.set_attach_type(0);
639                            pos.set_attach_chain(0);
640                            pos.y_offset = 0;
641                        } else if pos.attach_type() != 0 {
642                            pos.y_offset = pos.y_offset.saturating_add(scaled_v);
643                            has_gpos_attachment = true;
644                        }
645                    } else if glyph_mask & c.plan.kern_mask != 0 {
646                        pos.x_advance = pos.x_advance.saturating_add(scaled_v);
647                        pos.x_offset = pos.x_offset.saturating_add(scaled_v);
648                    }
649                } else {
650                    if has_cross_stream {
651                        // CoreText doesn't do crossStream kerning in vertical. We do.
652                        if v == -0x8000 {
653                            pos.set_attach_type(0);
654                            pos.set_attach_chain(0);
655                            pos.x_offset = 0;
656                        } else if pos.attach_type() != 0 {
657                            pos.x_offset = pos.x_offset.saturating_add(scaled_v);
658                            has_gpos_attachment = true;
659                        }
660                    } else if glyph_mask & c.plan.kern_mask != 0 {
661                        if pos.y_offset == 0 {
662                            pos.y_advance = pos.y_advance.saturating_add(scaled_v);
663                            pos.y_offset = pos.y_offset.saturating_add(scaled_v);
664                        }
665                    }
666                }
667
668                if has_gpos_attachment {
669                    c.buffer.scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;
670                }
671            }
672        }
673
674        Some(())
675    }
676}
677struct Driver4<'a> {
678    mark_set: bool,
679    mark: usize,
680    ankr_table: Option<Ankr<'a>>,
681}
682
683impl StateTableDriver<Subtable4<'_>, BigEndian<u16>> for Driver4<'_> {
684    #[inline(always)]
685    fn transition(
686        &mut self,
687        aat: &Subtable4,
688        entry: &aat::StateEntry<BigEndian<u16>>,
689        _has_cross_stream: bool,
690        _tuple_count: u32,
691        c: &mut AatApplyContext,
692    ) -> Option<()> {
693        if self.mark_set && entry.is_actionable() && c.buffer.idx < c.buffer.len {
694            match (self.ankr_table.as_ref(), &aat.actions) {
695                (Some(ankr_table), Subtable4Actions::AnchorPoints(ankr_data)) => {
696                    let action_idx = entry.action_index() as usize * 2;
697                    let mark_action_idx = ankr_data.get(action_idx)?.get() as usize;
698                    let curr_action_idx = ankr_data.get(action_idx + 1)?.get() as usize;
699                    let mark_anchor = c
700                        .buffer
701                        .info
702                        .get(self.mark)
703                        .and_then(|info| ankr_table.anchor_points(info.as_glyph()).ok())
704                        .and_then(|list| list.get(mark_action_idx))
705                        .map(|point| (point.x(), point.y()))
706                        .unwrap_or_default();
707
708                    let curr_idx = c.buffer.cur(0)?.as_glyph();
709                    let curr_anchor = ankr_table
710                        .anchor_points(curr_idx)
711                        .ok()
712                        .and_then(|list| list.get(curr_action_idx))
713                        .map(|point| (point.x(), point.y()))
714                        .unwrap_or_default();
715
716                    let x_offset = c
717                        .scale_x(i32::from(mark_anchor.0))
718                        .saturating_sub(c.scale_x(i32::from(curr_anchor.0)));
719                    let y_offset = c
720                        .scale_y(i32::from(mark_anchor.1))
721                        .saturating_sub(c.scale_y(i32::from(curr_anchor.1)));
722                    let pos = c.buffer.cur_pos_mut()?;
723                    pos.x_offset = x_offset;
724                    pos.y_offset = y_offset;
725                }
726                (_, Subtable4Actions::ControlPointCoords(coords)) => {
727                    let action_idx = entry.action_index() as usize * 4;
728                    let mark_x = coords.get(action_idx)?.get() as i32;
729                    let mark_y = coords.get(action_idx + 1)?.get() as i32;
730                    let curr_x = coords.get(action_idx + 2)?.get() as i32;
731                    let curr_y = coords.get(action_idx + 3)?.get() as i32;
732                    let x_offset = c.scale_x(mark_x).saturating_sub(c.scale_x(curr_x));
733                    let y_offset = c.scale_y(mark_y).saturating_sub(c.scale_y(curr_y));
734                    let pos = c.buffer.cur_pos_mut()?;
735                    pos.x_offset = x_offset;
736                    pos.y_offset = y_offset;
737                }
738                _ => {}
739            }
740
741            c.buffer.cur_pos_mut()?.set_attach_type(attach_type::MARK);
742            let idx = c.buffer.idx;
743            let mut attach_chain = self.mark as i16 - idx as i16;
744            if c.buffer_is_reversed {
745                attach_chain = -attach_chain;
746            }
747            c.buffer.cur_pos_mut()?.set_attach_chain(attach_chain);
748            c.buffer.scratch_flags |= HB_BUFFER_SCRATCH_FLAG_HAS_GPOS_ATTACHMENT;
749        }
750
751        if entry.has_mark() {
752            self.mark_set = true;
753            self.mark = c.buffer.idx;
754        }
755
756        Some(())
757    }
758}
759
760pub(crate) struct KerxSubtableCache<'a> {
761    start_end_safe_to_break: u64,
762    safe_to_break: SafeToBreakSubtable,
763    first_set: U32Set,
764    first_digest: SetDigest,
765    second_set: U32Set,
766    class_cache: Box<ClassCache>,
767    subtable: Subtable<'a>,
768    /// The parsed subtable, or `None` if it is unreadable.
769    kind: Option<SubtableKind<'a>>,
770}
771
772impl<'a> KerxSubtableCache<'a> {
773    pub(crate) fn new(
774        subtable: &Subtable<'a>,
775        num_glyphs: u32,
776        safe_to_break: &mut SafeToBreakAccel,
777    ) -> Self {
778        let mut start_end_safe_to_break = 0u64;
779        let mut safe_to_break_subtable = safe_to_break.empty_subtable();
780        let mut first_set = U32Set::default();
781        let mut second_set = U32Set::default();
782        let kind = subtable.kind().ok();
783        if let Some(kind) = &kind {
784            match kind {
785                SubtableKind::Format0(format0) => {
786                    format0.collect_glyphs(&mut first_set, &mut second_set, num_glyphs);
787                }
788                SubtableKind::Format1(format1) => {
789                    start_end_safe_to_break = collect_start_end_safe_to_break(&format1.state_table);
790                    safe_to_break_subtable = safe_to_break.build_extended(
791                        &format1.state_table,
792                        subtable.data(),
793                        &KerxStateEntryExt::is_actionable,
794                        &KerxStateEntryExt::has_advance,
795                    );
796                    collect_initial_glyphs(&format1.state_table, &mut first_set, num_glyphs);
797                }
798                SubtableKind::Format2(format2) => {
799                    format2.collect_glyphs(&mut first_set, &mut second_set, num_glyphs);
800                }
801                SubtableKind::Format4(format4) => {
802                    start_end_safe_to_break = collect_start_end_safe_to_break(&format4.state_table);
803                    safe_to_break_subtable = safe_to_break.build_extended(
804                        &format4.state_table,
805                        subtable.data(),
806                        &KerxStateEntryExt::is_actionable,
807                        &KerxStateEntryExt::has_advance,
808                    );
809                    collect_initial_glyphs(&format4.state_table, &mut first_set, num_glyphs);
810                }
811                SubtableKind::Format6(format6) => {
812                    format6.collect_glyphs(&mut first_set, &mut second_set, num_glyphs);
813                }
814            }
815        }
816        KerxSubtableCache {
817            start_end_safe_to_break,
818            safe_to_break: safe_to_break_subtable,
819            first_digest: set_digest(&first_set),
820            first_set,
821            second_set,
822            class_cache: Box::new(ClassCache::new()),
823            subtable: subtable.clone(),
824            kind,
825        }
826    }
827}
828
829#[cfg(test)]
830mod tests {
831    use super::*;
832    use read_fonts::FontRead;
833
834    #[test]
835    fn format0_resolves_first_tuple_kerning_value() {
836        #[rustfmt::skip]
837        let data = [
838            0, 0, 0, 1, // nPairs
839            0, 0, 0, 0, // searchRange
840            0, 0, 0, 0, // entrySelector
841            0, 0, 0, 0, // rangeShift
842            0, 1, 0, 2, 0, 22, // pair: glyphs 1, 2; value is tuple offset 22
843            0xFF, 0x9C, 0x01, 0x2C, // tuple values: -100, 300
844        ];
845        let subtable = Subtable0::read(FontData::new(&data)).unwrap();
846        let value = subtable.simple_kerning(1u32.into(), 2u32.into()).unwrap();
847
848        assert_eq!(value, 22);
849        assert_eq!(subtable.resolve_tuple_kerning(value, 2), Some(-100));
850        assert_eq!(subtable.resolve_tuple_kerning(value, 3), Some(-100));
851    }
852}