Skip to main content

harfrust/aat/
mod.rs

1pub mod common;
2pub mod kern;
3pub mod kerx;
4pub mod layout;
5pub mod map;
6pub mod morx;
7pub mod trak;
8
9use crate::aat::common::SafeToBreakAccel;
10use crate::aat::kern::KernSubtableCache;
11use crate::aat::kerx::KerxSubtableCache;
12use crate::aat::morx::{MorphSubtableCache, MorphSubtableDescriptor};
13use crate::once::Once;
14use crate::ot::OtCache;
15use alloc::boxed::Box;
16use alloc::sync::Arc;
17use alloc::vec::Vec;
18use read_fonts::{
19    model::Tables,
20    tables::{
21        ankr::Ankr, feat::Feat, kern::Kern, kerx::Kerx, ltag::Ltag, mort::Mort, morx::Morx,
22        trak::Trak,
23    },
24    TableProvider,
25};
26use yoke::{Yoke, Yokeable};
27
28/// Font-wide AAT tables and accelerators initialized on first use.
29pub struct AatCache {
30    // Keep uninitialized caches small, including in fonts without AAT tables.
31    morx: Once<Box<Yoke<MorphTableCache<'static>, Arc<Tables>>>>,
32    mort: Once<Box<Yoke<MorphTableCache<'static>, Arc<Tables>>>>,
33    kern: Once<Box<Yoke<KernTableCache<'static>, Arc<Tables>>>>,
34    kerx: Once<Box<Yoke<KerxTableCache<'static>, Arc<Tables>>>>,
35    tables: Option<Yoke<CachedAatTables<'static>, Arc<Tables>>>,
36}
37
38impl AatCache {
39    pub fn new(tables: Option<Arc<Tables>>, ot_cache: &OtCache) -> Self {
40        let active_gdef_len = if ot_cache.has_gdef {
41            ot_cache.gdef_len
42        } else {
43            0
44        };
45        let gsub_len = ot_cache.gsub_len;
46        Self {
47            morx: Once::new(),
48            mort: Once::new(),
49            kern: Once::new(),
50            kerx: Once::new(),
51            tables: tables.map(|tables| {
52                Yoke::attach_to_cart(tables, |tables| {
53                    CachedAatTables::new(tables, gsub_len, active_gdef_len)
54                })
55            }),
56        }
57    }
58}
59
60/// The AAT tables, parsed once and kept with the font tables.
61#[derive(Yokeable)]
62pub struct CachedAatTables<'a> {
63    pub morx: Option<Morx<'a>>,
64    pub mort: Option<Mort<'a>>,
65    pub ankr: Option<Ankr<'a>>,
66    pub kern: Option<Kern<'a>>,
67    pub kerx: Option<Kerx<'a>>,
68    pub trak: Option<Trak<'a>>,
69    pub feat: Option<Feat<'a>>,
70    pub ltag: Option<Ltag<'a>>,
71    num_glyphs: u32,
72}
73
74impl<'a> CachedAatTables<'a> {
75    const EMPTY: Self = Self {
76        morx: None,
77        mort: None,
78        ankr: None,
79        kern: None,
80        kerx: None,
81        trak: None,
82        feat: None,
83        ltag: None,
84        num_glyphs: 0,
85    };
86
87    fn new(tables: &'a Tables, gsub_len: u32, gdef_len: u32) -> Self {
88        let morx = tables.morx().ok().filter(|morx| {
89            let morx_len = morx.offset_data().len() as u32;
90            !is_morx_blocklisted(morx_len, gsub_len, gdef_len)
91        });
92        Self {
93            morx,
94            mort: tables.mort().ok(),
95            ankr: tables.ankr().ok(),
96            kern: tables.kern().ok(),
97            kerx: tables.kerx().ok(),
98            trak: tables.trak().ok(),
99            feat: tables.feat().ok(),
100            ltag: tables.ltag().ok(),
101            num_glyphs: tables
102                .selected_maxp()
103                .map(|maxp| maxp.num_glyphs())
104                .unwrap_or_default(),
105        }
106    }
107}
108
109/// The subtables of a `morx` or `mort` table, parsed, with their
110/// accelerators.
111#[derive(Default, Yokeable)]
112pub(crate) struct MorphTableCache<'a> {
113    safe_to_break: SafeToBreakAccel,
114    subtables: Vec<MorphSubtableCache<'a>>,
115    descriptors: Vec<MorphSubtableDescriptor>,
116}
117
118impl<'a> MorphTableCache<'a> {
119    fn new_morx(morx: &Morx<'a>, num_glyphs: u32) -> Self {
120        let mut cache = Self::default();
121        for (chain_index, chain) in morx.chains().iter().enumerate() {
122            let Ok(chain) = chain else {
123                continue;
124            };
125            for subtable in chain.subtables().iter() {
126                let Ok(subtable) = subtable else {
127                    continue;
128                };
129                let entry =
130                    MorphSubtableCache::new_morx(&subtable, num_glyphs, &mut cache.safe_to_break);
131                cache
132                    .descriptors
133                    .push(MorphSubtableCache::descriptor_morx(chain_index, &subtable));
134                cache.subtables.push(entry);
135            }
136        }
137        cache
138    }
139
140    fn new_mort(mort: &Mort<'a>, num_glyphs: u32) -> Self {
141        let mut cache = Self::default();
142        for (chain_index, chain) in mort.chains().iter().enumerate() {
143            let Ok(chain) = chain else {
144                continue;
145            };
146            for subtable in chain.subtables().iter() {
147                let Ok(subtable) = subtable else {
148                    continue;
149                };
150                let entry =
151                    MorphSubtableCache::new_mort(&subtable, num_glyphs, &mut cache.safe_to_break);
152                cache
153                    .descriptors
154                    .push(MorphSubtableCache::descriptor_mort(chain_index, &subtable));
155                cache.subtables.push(entry);
156            }
157        }
158        cache
159    }
160}
161
162/// The subtables of a `kern` table, parsed, with their accelerators.
163#[derive(Default, Yokeable)]
164pub(crate) struct KernTableCache<'a> {
165    safe_to_break: SafeToBreakAccel,
166    subtables: Vec<KernSubtableCache<'a>>,
167}
168
169impl<'a> KernTableCache<'a> {
170    fn new(kern: &Kern<'a>, num_glyphs: u32) -> Self {
171        let mut cache = Self::default();
172        for subtable in kern.subtables() {
173            let Ok(subtable) = subtable else {
174                continue;
175            };
176            let entry = KernSubtableCache::new(&subtable, num_glyphs, &mut cache.safe_to_break);
177            cache.subtables.push(entry);
178        }
179        cache
180    }
181}
182
183/// The subtables of a `kerx` table, parsed, with their accelerators.
184#[derive(Default, Yokeable)]
185pub(crate) struct KerxTableCache<'a> {
186    safe_to_break: SafeToBreakAccel,
187    subtables: Vec<KerxSubtableCache<'a>>,
188}
189
190impl<'a> KerxTableCache<'a> {
191    fn new(kerx: &Kerx<'a>, num_glyphs: u32) -> Self {
192        let mut cache = Self::default();
193        for subtable in kerx.subtables().iter() {
194            let Ok(subtable) = subtable else {
195                continue;
196            };
197            let entry = KerxSubtableCache::new(&subtable, num_glyphs, &mut cache.safe_to_break);
198            cache.subtables.push(entry);
199        }
200        cache
201    }
202}
203
204/// The AAT tables of a font, and its accelerators.
205#[derive(Clone)]
206pub struct AatData<'a> {
207    cache: Option<&'a AatCache>,
208    tables: &'a CachedAatTables<'a>,
209}
210
211impl<'a> core::ops::Deref for AatData<'a> {
212    type Target = CachedAatTables<'a>;
213
214    fn deref(&self) -> &Self::Target {
215        self.tables
216    }
217}
218
219use crate::algs::HB_CODEPOINT_ENCODE3 as encode3;
220
221/// Blocklist specific broken morx tables identified by the combination of
222/// morx, GSUB, and GDEF table lengths.
223fn is_morx_blocklisted(morx_len: u32, gsub_len: u32, gdef_len: u32) -> bool {
224    const BLOCKLIST: &[u64] = &[
225        // AALMAGHRIBI.ttf — https://github.com/harfbuzz/harfbuzz/issues/4108
226        encode3(19892, 2794, 340),
227    ];
228    let key = encode3(morx_len, gsub_len, gdef_len);
229    BLOCKLIST.contains(&key)
230}
231
232static EMPTY_AAT_TABLES: CachedAatTables<'static> = CachedAatTables::EMPTY;
233
234pub(crate) static EMPTY_AAT_DATA: AatData<'static> = AatData {
235    cache: None,
236    tables: &EMPTY_AAT_TABLES,
237};
238
239impl<'a> AatData<'a> {
240    pub fn new(cache: &'a AatCache) -> Self {
241        Self {
242            cache: Some(cache),
243            tables: cache.tables.as_ref().map_or(&EMPTY_AAT_TABLES, Yoke::get),
244        }
245    }
246
247    // Access accelerators only when applying the corresponding table, so
248    // planning can select GPOS or a preferred AAT table without building them.
249    // The accelerators borrow the parsed tables, so each is projected from
250    // the yoke that holds them.
251    pub(crate) fn morx_cache(&self) -> Option<&'a MorphTableCache<'a>> {
252        self.morx.as_ref()?;
253        let cache = self.cache?;
254        let tables = cache.tables.as_ref()?;
255        let yoke = cache.morx.get_or_init(|| {
256            Box::new(tables.map_project_cloned(|tables, _| {
257                tables
258                    .morx
259                    .as_ref()
260                    .map(|morx| MorphTableCache::new_morx(morx, tables.num_glyphs))
261                    .unwrap_or_default()
262            }))
263        });
264        Some(yoke.get())
265    }
266
267    pub(crate) fn mort_cache(&self) -> Option<&'a MorphTableCache<'a>> {
268        self.mort.as_ref()?;
269        let cache = self.cache?;
270        let tables = cache.tables.as_ref()?;
271        let yoke = cache.mort.get_or_init(|| {
272            Box::new(tables.map_project_cloned(|tables, _| {
273                tables
274                    .mort
275                    .as_ref()
276                    .map(|mort| MorphTableCache::new_mort(mort, tables.num_glyphs))
277                    .unwrap_or_default()
278            }))
279        });
280        Some(yoke.get())
281    }
282
283    pub(crate) fn kern_cache(&self) -> Option<&'a KernTableCache<'a>> {
284        self.kern.as_ref()?;
285        let cache = self.cache?;
286        let tables = cache.tables.as_ref()?;
287        let yoke = cache.kern.get_or_init(|| {
288            Box::new(tables.map_project_cloned(|tables, _| {
289                tables
290                    .kern
291                    .as_ref()
292                    .map(|kern| KernTableCache::new(kern, tables.num_glyphs))
293                    .unwrap_or_default()
294            }))
295        });
296        Some(yoke.get())
297    }
298
299    pub(crate) fn kerx_cache(&self) -> Option<&'a KerxTableCache<'a>> {
300        self.kerx.as_ref()?;
301        let cache = self.cache?;
302        let tables = cache.tables.as_ref()?;
303        let yoke = cache.kerx.get_or_init(|| {
304            Box::new(tables.map_project_cloned(|tables, _| {
305                tables
306                    .kerx
307                    .as_ref()
308                    .map(|kerx| KerxTableCache::new(kerx, tables.num_glyphs))
309                    .unwrap_or_default()
310            }))
311        });
312        Some(yoke.get())
313    }
314}
315
316#[cfg(all(test, feature = "std"))]
317mod tests {
318    use super::*;
319    use crate::{
320        font::Font, shape, Buffer, SerializeFlags, ShapeOptions, ShapePlan, ShaperFont, Tag,
321    };
322    use alloc::sync::Arc;
323    use read_fonts::{
324        model::{Blob, TableFunction},
325        FontRef,
326    };
327
328    fn initialized(cache: &AatCache) -> [bool; 4] {
329        [
330            cache.morx.get().is_some(),
331            cache.mort.get().is_some(),
332            cache.kern.get().is_some(),
333            cache.kerx.get().is_some(),
334        ]
335    }
336
337    fn shape_text(shaper: &ShaperFont<'_, '_>, text: &str, plan: &ShapePlan) -> Buffer {
338        let mut buffer = Buffer::new();
339        buffer.push_str(text);
340        buffer.guess_segment_properties();
341        shape(shaper, &mut buffer, ShapeOptions::new().plan(Some(plan))).unwrap();
342        buffer
343    }
344
345    fn plan_for_text(font: &Font, text: &str) -> ShapePlan {
346        let mut buffer = Buffer::new();
347        buffer.push_str(text);
348        buffer.guess_segment_properties();
349        ShapePlan::new(font, buffer.direction(), buffer.script(), None, &[])
350    }
351
352    #[test]
353    fn gpos_kerning_leaves_legacy_kern_cache_uninitialized() {
354        let font = Font::new(
355            include_bytes!("../../tests/fonts/rb_custom/PT_Sans-Caption-Web-Regular.ttf").to_vec(),
356            0,
357        )
358        .unwrap();
359        let shaper = ShaperFont::new(&font);
360        let aat = shaper.layout().aat;
361        let cache = aat.cache.unwrap();
362        assert!(aat.kern.is_some());
363        assert_eq!(initialized(cache), [false; 4]);
364
365        let plan = plan_for_text(&font, "AV");
366        assert!(plan.apply_gpos);
367        assert!(!plan.apply_kern);
368        assert_eq!(initialized(cache), [false; 4]);
369        let _ = shape_text(&shaper, "AV", &plan);
370        assert_eq!(initialized(cache), [false; 4]);
371    }
372
373    #[test]
374    fn aat_caches_initialize_on_first_shape_and_are_shared() {
375        let cases: &[(&[u8], &str, usize)] = &[
376            (
377                include_bytes!("../../tests/fonts/in-house/MORXTwentyeight.ttf"),
378                "AxEyDyy",
379                0,
380            ),
381            (
382                include_bytes!("../../tests/fonts/text-rendering-tests/TestAATMort.ttf"),
383                "ABCEFGX",
384                1,
385            ),
386            (
387                include_bytes!("../../tests/fonts/text-rendering-tests/TestKERNOne.otf"),
388                "uTuT",
389                2,
390            ),
391        ];
392        for &(bytes, text, cache_index) in cases {
393            let font = Font::new(bytes.to_vec(), 0).unwrap();
394            let shaper = ShaperFont::new(&font);
395            let aat = shaper.layout().aat;
396            let cache = aat.cache.unwrap();
397            assert_eq!(initialized(cache), [false; 4]);
398            let plan = plan_for_text(&font, text);
399            assert_eq!(initialized(cache), [false; 4]);
400
401            let first = shape_text(&shaper, text, &plan);
402            let mut expected = [false; 4];
403            expected[cache_index] = true;
404            assert_eq!(initialized(cache), expected);
405
406            let instance = font.instance_builder().build();
407            let second_shaper = ShaperFont::new(&instance);
408            assert!(core::ptr::eq(
409                cache,
410                second_shaper.layout().aat.cache.unwrap()
411            ));
412            let second = shape_text(&second_shaper, text, &plan);
413            assert_eq!(
414                first.serialize(Some(&shaper), SerializeFlags::GLYPH_FLAGS),
415                second.serialize(Some(&second_shaper), SerializeFlags::GLYPH_FLAGS)
416            );
417            assert_eq!(initialized(cache), expected);
418        }
419    }
420
421    #[test]
422    fn kerx_cache_initializes_without_legacy_kern_cache() {
423        let bytes = include_bytes!("../../tests/fonts/text-rendering-tests/TestKERNOne.otf");
424        let source = FontRef::new(bytes).unwrap();
425        let source_font = Font::new(bytes.to_vec(), 0).unwrap();
426        let charmap = source_font.charmap();
427        let left = charmap.map_unicode('u' as u32).unwrap().to_u32() as u16;
428        let right = charmap.map_unicode('T' as u32).unwrap().to_u32() as u16;
429        // A format-0 kerx subtable with one horizontal pair adjustment of -100.
430        #[rustfmt::skip]
431        let mut kerx = vec![
432            0, 2, 0, 0, // version 2, padding
433            0, 0, 0, 1, // nTables
434            0, 0, 0, 34, // subtable length
435            0, 0, 0, 0, // coverage: horizontal, format 0
436            0, 0, 0, 0, // tupleCount
437            0, 0, 0, 1, // nPairs
438            0, 0, 0, 6, // searchRange
439            0, 0, 0, 0, // entrySelector
440            0, 0, 0, 0, // rangeShift
441        ];
442        kerx.extend_from_slice(&left.to_be_bytes());
443        kerx.extend_from_slice(&right.to_be_bytes());
444        kerx.extend_from_slice(&(-100i16).to_be_bytes());
445        let tables = TableFunction::new(Arc::new(move |tag| {
446            if tag == Tag::new(b"kerx") {
447                Some(Blob::from(kerx.clone()))
448            } else {
449                source
450                    .data_for_tag(tag)
451                    .map(|data| Blob::from(data.as_bytes().to_vec()))
452            }
453        }));
454        let font = Font::new(tables, 0).unwrap();
455        let shaper = ShaperFont::new(&font);
456        let aat = shaper.layout().aat;
457        let cache = aat.cache.unwrap();
458        assert!(aat.kern.is_some());
459        assert!(aat.kerx.is_some());
460        let plan = plan_for_text(&font, "uT");
461        assert!(plan.apply_kerx);
462        assert!(!plan.apply_kern);
463        assert_eq!(initialized(cache), [false; 4]);
464
465        let buffer = shape_text(&shaper, "uT", &plan);
466        assert_eq!(initialized(cache), [false, false, false, true]);
467        let positions = buffer.glyph_positions();
468        assert_eq!(
469            positions[0].x_advance,
470            shaper.default_glyph_h_advance(left.into()) - 50
471        );
472        assert_eq!(
473            positions[1].x_advance,
474            shaper.default_glyph_h_advance(right.into()) - 50
475        );
476        assert_eq!(positions[1].x_offset, -50);
477    }
478
479    #[test]
480    fn concurrent_first_shapes_share_morx_cache() {
481        let font = Font::new(
482            include_bytes!("../../tests/fonts/in-house/MORXTwentyeight.ttf").to_vec(),
483            0,
484        )
485        .unwrap();
486        let shaper = ShaperFont::new(&font);
487        let cache = shaper.layout().aat.cache.unwrap();
488        let plan = plan_for_text(&font, "AxEyDyy");
489        let barrier = std::sync::Barrier::new(4);
490        assert_eq!(initialized(cache), [false; 4]);
491        std::thread::scope(|scope| {
492            let handles: Vec<_> = (0..4)
493                .map(|_| {
494                    scope.spawn(|| {
495                        let shaper = ShaperFont::new(&font);
496                        barrier.wait();
497                        let buffer = shape_text(&shaper, "AxEyDyy", &plan);
498                        (
499                            buffer.serialize(Some(&shaper), SerializeFlags::GLYPH_FLAGS),
500                            core::ptr::from_ref(shaper.layout().aat.morx_cache().unwrap()) as usize,
501                        )
502                    })
503                })
504                .collect();
505            let results: Vec<_> = handles
506                .into_iter()
507                .map(|handle| handle.join().unwrap())
508                .collect();
509            for result in &results[1..] {
510                assert_eq!(results[0].0, result.0);
511                assert_eq!(results[0].1, result.1);
512            }
513        });
514        assert_eq!(initialized(cache), [true, false, false, false]);
515    }
516}