Skip to main content

harfrust/ot/
mod.rs

1use self::apply::MappingCache;
2use self::layout::LayoutTableKind;
3use super::buffer::GlyphPropsFlags;
4use super::{set_digest::SetDigest, tag::TagExt};
5use crate::budget::{Budget, Exhausted};
6use crate::Tag;
7use alloc::{sync::Arc, vec::Vec};
8use lookup::{CachedLookup, ClassDef, Coverage, LookupCache};
9use read_fonts::model::Tables;
10use read_fonts::{
11    tables::{
12        gdef::Gdef,
13        gpos::{AnchorTable, DeviceOrVariationIndex, Gpos},
14        gsub::{FeatureList, FeatureVariations, Gsub, ScriptList},
15        layout::{
16            Feature as LayoutFeature, LangSys, LookupVariations, Script as LayoutScript,
17            SelectedFeatureVariations,
18        },
19        varc::CoverageTable,
20        variations::{DeltaSetIndex, ItemVariationStore},
21    },
22    types::{F2Dot14, GlyphId},
23    FontData, ReadError, TableProvider,
24};
25use yoke::{Yoke, Yokeable};
26
27pub(crate) mod apply;
28pub mod gpos;
29pub mod gsub;
30pub(crate) mod layout;
31pub mod lookup;
32
33#[cfg(test)]
34#[path = "lookup_variations_tests.rs"]
35mod lookup_variations_tests;
36pub(crate) mod map;
37pub(crate) mod shaper;
38
39#[allow(unused_imports)]
40use super::{aat, buffer, cache, set_digest, tag};
41#[allow(unused_imports)]
42use super::{clamp_i64_to_i32, Direction, Feature, GlyphInfo, Language, Mask, Script};
43
44#[allow(dead_code)]
45pub(crate) mod lookup_flags {
46    pub const RIGHT_TO_LEFT: u16 = 0x0001;
47    pub const IGNORE_BASE_GLYPHS: u16 = 0x0002;
48    pub const IGNORE_LIGATURES: u16 = 0x0004;
49    pub const IGNORE_MARKS: u16 = 0x0008;
50    pub const IGNORE_FLAGS: u16 = 0x000E;
51    pub const USE_MARK_FILTERING_SET: u16 = 0x0010;
52    pub const MARK_ATTACHMENT_TYPE_MASK: u16 = 0xFF00;
53}
54
55pub struct OtCache {
56    pub gsub: LookupCache,
57    pub gpos: LookupCache,
58    pub gdef_glyph_props_cache: MappingCache,
59    tables: Option<Yoke<CachedTables<'static>, Arc<Tables>>>,
60    pub(crate) has_gdef: bool,
61    pub(crate) gsub_len: u32,
62    pub(crate) gdef_len: u32,
63}
64
65const MARK_GLYPH_SET_PAGE_BITS: u32 = 512;
66
67#[derive(Clone, Debug)]
68pub enum MarkGlyphSetBitmap {
69    Page { bias: u32, bits: [u64; 8] },
70    Digest(SetDigest),
71}
72
73impl MarkGlyphSetBitmap {
74    fn page_from_coverage(
75        coverage: &CoverageTable,
76        min_gid: u32,
77        budget: &Budget,
78    ) -> Result<Option<[u64; 8]>, Exhausted> {
79        let mut bits = [0; 8];
80        let mut add_glyph = |glyph: u32| {
81            let biased = glyph.wrapping_sub(min_gid);
82            *bits.get_mut((biased / 64) as usize)? |= 1 << (biased & 63);
83            Some(())
84        };
85
86        match coverage {
87            CoverageTable::Format1(table) => {
88                budget.work(table.glyph_array().len())?;
89                for glyph in table.glyph_array() {
90                    if add_glyph(u32::from(glyph.get())).is_none() {
91                        return Ok(None);
92                    }
93                }
94            }
95            CoverageTable::Format2(table) => {
96                budget.work(table.range_records().len())?;
97                for range in table.range_records() {
98                    let start = u32::from(range.start_glyph_id());
99                    let end = u32::from(range.end_glyph_id());
100                    budget.work(end.saturating_sub(start) as usize + 1)?;
101                    for glyph in start..=end {
102                        if add_glyph(glyph).is_none() {
103                            return Ok(None);
104                        }
105                    }
106                }
107            }
108            CoverageTable::Format3(table) => {
109                budget.work(table.glyph_array().len())?;
110                for glyph in table.glyph_array() {
111                    if add_glyph(glyph.get().to_u32()).is_none() {
112                        return Ok(None);
113                    }
114                }
115            }
116            CoverageTable::Format4(table) => {
117                budget.work(table.range_records().len())?;
118                for range in table.range_records() {
119                    let start = range.start_glyph_id().to_u32();
120                    let end = range.end_glyph_id().to_u32();
121                    budget.work(end.saturating_sub(start) as usize + 1)?;
122                    for glyph in start..=end {
123                        if add_glyph(glyph).is_none() {
124                            return Ok(None);
125                        }
126                    }
127                }
128            }
129        }
130        Ok(Some(bits))
131    }
132
133    fn from_coverage(coverage: &CoverageTable, budget: &Budget) -> Result<Self, Exhausted> {
134        let bounds = match coverage {
135            CoverageTable::Format1(table) => table
136                .glyph_array()
137                .first()
138                .zip(table.glyph_array().last())
139                .map(|(min, max)| (u32::from(min.get()), u32::from(max.get()))),
140            CoverageTable::Format2(table) => table
141                .range_records()
142                .first()
143                .zip(table.range_records().last())
144                .map(|(min, max)| {
145                    (
146                        u32::from(min.start_glyph_id()),
147                        u32::from(max.end_glyph_id()),
148                    )
149                }),
150            CoverageTable::Format3(table) => table
151                .glyph_array()
152                .first()
153                .zip(table.glyph_array().last())
154                .map(|(min, max)| (min.get().to_u32(), max.get().to_u32())),
155            CoverageTable::Format4(table) => table
156                .range_records()
157                .first()
158                .zip(table.range_records().last())
159                .map(|(min, max)| (min.start_glyph_id().to_u32(), max.end_glyph_id().to_u32())),
160        };
161
162        if let Some((min_gid, max_gid)) = bounds {
163            if max_gid.wrapping_sub(min_gid) < MARK_GLYPH_SET_PAGE_BITS {
164                if let Some(bits) = Self::page_from_coverage(coverage, min_gid, budget)? {
165                    return Ok(Self::Page {
166                        bias: min_gid,
167                        bits,
168                    });
169                }
170            }
171        }
172
173        budget.work(match coverage {
174            CoverageTable::Format1(table) => table.glyph_array().len(),
175            CoverageTable::Format2(table) => table.range_records().len(),
176            CoverageTable::Format3(table) => table.glyph_array().len(),
177            CoverageTable::Format4(table) => table.range_records().len(),
178        })?;
179        Ok(Self::Digest(SetDigest::from_coverage(coverage)))
180    }
181
182    #[inline(always)]
183    fn covers(&self, glyph_id: u32) -> Option<bool> {
184        match self {
185            Self::Page { bias, bits } => {
186                let biased = glyph_id.wrapping_sub(*bias);
187                Some(
188                    biased < MARK_GLYPH_SET_PAGE_BITS
189                        && bits[(biased / 64) as usize] & (1 << (biased & 63)) != 0,
190                )
191            }
192            Self::Digest(digest) => (!digest.may_have(glyph_id)).then_some(false),
193        }
194    }
195}
196
197impl OtCache {
198    pub fn new(tables: Option<Arc<Tables>>) -> Self {
199        let bytes = tables.as_deref().map_or(0, |tables| {
200            [tables.gsub_data(), tables.gpos_data(), tables.gdef_data()]
201                .into_iter()
202                .flatten()
203                .fold(0usize, |bytes, data| bytes.saturating_add(data.len()))
204        });
205        let budget = Arc::new(Budget::for_table_bytes(bytes));
206        let cached = tables.clone().map(|tables| {
207            Yoke::attach_to_cart(tables, |tables| CachedTables::new(tables, &budget))
208        });
209        let parsed: Option<&CachedTables> = cached.as_ref().map(Yoke::get);
210        Self {
211            // A missing table has no lookups.
212            gsub: LookupCache::new(tables.clone(), true, budget.clone()),
213            gpos: LookupCache::new(tables, false, budget.clone()),
214            gdef_glyph_props_cache: MappingCache::new(),
215            has_gdef: parsed.is_some_and(|cached| cached.has_gdef),
216            gsub_len: parsed.map_or(0, |cached| cached.gsub_len),
217            gdef_len: parsed.map_or(0, |cached| cached.gdef_len),
218            tables: cached,
219        }
220    }
221}
222
223/// The layout tables, parsed once and kept with the font tables.
224#[derive(Yokeable)]
225pub(crate) struct CachedTables<'a> {
226    gsub: Option<Gsub<'a>>,
227    gpos: Option<Gpos<'a>>,
228    gdef: CachedGdef<'a>,
229    /// Whether GDEF is used: present, and not one of the known broken ones.
230    has_gdef: bool,
231    gsub_len: u32,
232    gdef_len: u32,
233}
234
235impl<'a> CachedTables<'a> {
236    const EMPTY: Self = Self {
237        gsub: None,
238        gpos: None,
239        gdef: CachedGdef::EMPTY,
240        has_gdef: false,
241        gsub_len: 0,
242        gdef_len: 0,
243    };
244
245    fn new(tables: &'a Tables, budget: &Budget) -> Self {
246        let gsub = tables.gsub().ok();
247        let gpos = tables.gpos().ok();
248        let gdef = tables.gdef().ok();
249        let len = |data: Option<FontData>| data.map_or(0, |data| data.len() as u32);
250        let gsub_len = len(gsub.as_ref().map(|table| table.offset_data()));
251        let gpos_len = len(gpos.as_ref().map(|table| table.offset_data()));
252        let gdef_len = len(gdef.as_ref().map(|table| table.offset_data()));
253        let gdef = gdef.filter(|_| !is_gdef_blocklisted(gdef_len, gsub_len, gpos_len));
254        Self {
255            gsub,
256            gpos,
257            has_gdef: gdef.is_some(),
258            gdef: gdef.map_or(CachedGdef::EMPTY, |gdef| CachedGdef::new(&gdef, budget)),
259            gsub_len,
260            gdef_len,
261        }
262    }
263}
264
265/// The parts of GDEF read while shaping.
266#[derive(Yokeable)]
267pub(crate) struct CachedGdef<'a> {
268    classes: ClassDef<'a>,
269    mark_classes: ClassDef<'a>,
270    mark_sets: Vec<MarkSet<'a>>,
271    var_store: Option<ItemVariationStore<'a>>,
272}
273
274impl<'a> CachedGdef<'a> {
275    const EMPTY: Self = Self {
276        classes: ClassDef::None,
277        mark_classes: ClassDef::None,
278        mark_sets: Vec::new(),
279        var_store: None,
280    };
281
282    fn new(gdef: &Gdef<'a>, budget: &Budget) -> Self {
283        let class_def = |table: Option<Result<_, _>>| table.map_or(ClassDef::None, ClassDef::new);
284        let build_mark_sets = || -> Result<Vec<MarkSet<'a>>, Exhausted> {
285            let Some(sets) = gdef.mark_glyph_sets_def().and_then(Result::ok) else {
286                return Ok(Vec::new());
287            };
288            let coverages = sets.coverages();
289            budget.work(coverages.len())?;
290            budget.alloc::<MarkSet>(coverages.len())?;
291            let mut mark_sets = Vec::with_capacity(coverages.len());
292            for coverage in coverages.iter() {
293                mark_sets.push(MarkSet::new(coverage, budget)?);
294            }
295            Ok(mark_sets)
296        };
297        // An incomplete mark-set cache must not approve a filtering lookup.
298        let mark_sets = build_mark_sets().unwrap_or_default();
299        Self {
300            classes: class_def(gdef.glyph_class_def()),
301            mark_classes: class_def(gdef.mark_attach_class_def()),
302            mark_sets,
303            var_store: gdef.item_var_store().and_then(Result::ok),
304        }
305    }
306}
307
308/// A mark glyph set, with a bitmap or digest that settles most queries.
309struct MarkSet<'a> {
310    bitmap: MarkGlyphSetBitmap,
311    coverage: Coverage<'a>,
312}
313
314impl<'a> MarkSet<'a> {
315    fn new(
316        coverage: Result<CoverageTable<'a>, ReadError>,
317        budget: &Budget,
318    ) -> Result<Self, Exhausted> {
319        let bitmap = match &coverage {
320            Ok(coverage) => MarkGlyphSetBitmap::from_coverage(coverage, budget)?,
321            Err(_) => MarkGlyphSetBitmap::Digest(SetDigest::default()),
322        };
323        Ok(Self {
324            bitmap,
325            coverage: Coverage::new(coverage),
326        })
327    }
328
329    #[inline(never)]
330    fn covers(&self, glyph_id: u32) -> bool {
331        self.coverage.covers(GlyphId::new(glyph_id))
332    }
333}
334
335#[derive(Clone)]
336pub struct GsubTable<'a> {
337    pub lookups: &'a LookupCache,
338}
339
340impl layout::LayoutTable for GsubTable<'_> {
341    const KIND: LayoutTableKind = LayoutTableKind::Gsub;
342    const IN_PLACE: bool = false;
343
344    fn get_lookup(&self, index: u16) -> Option<&CachedLookup<'_>> {
345        self.lookups.get(index)
346    }
347}
348
349#[derive(Clone)]
350pub struct GposTable<'a> {
351    pub lookups: &'a LookupCache,
352}
353
354impl layout::LayoutTable for GposTable<'_> {
355    const KIND: LayoutTableKind = LayoutTableKind::Gpos;
356    const IN_PLACE: bool = true;
357
358    fn get_lookup(&self, index: u16) -> Option<&CachedLookup<'_>> {
359        self.lookups.get(index)
360    }
361}
362
363/// The OpenType layout data of a font, borrowed from its layout cache.
364#[derive(Clone)]
365pub struct OtData<'a> {
366    cache: &'a OtCache,
367    tables: &'a CachedTables<'a>,
368    /// The variation store, if the font is variable and has an instance.
369    var_store: Option<&'a ItemVariationStore<'a>>,
370    pub coords: &'a [F2Dot14],
371    pub feature_variations: [Option<u32>; 2],
372    /// Whether a layout table has lookup variations, which plans then
373    /// resolve per feature at `coords`.
374    pub has_lookup_variations: bool,
375}
376
377static EMPTY_OT_CACHE: OtCache = OtCache {
378    gsub: LookupCache::EMPTY,
379    gpos: LookupCache::EMPTY,
380    gdef_glyph_props_cache: MappingCache::empty(),
381    tables: None,
382    has_gdef: false,
383    gsub_len: 0,
384    gdef_len: 0,
385};
386static EMPTY_TABLES: CachedTables<'static> = CachedTables::EMPTY;
387
388pub(crate) static EMPTY_OT_DATA: OtData<'static> = OtData {
389    cache: &EMPTY_OT_CACHE,
390    tables: &EMPTY_TABLES,
391    var_store: None,
392    coords: &[],
393    feature_variations: [None; 2],
394    has_lookup_variations: false,
395};
396
397impl<'a> OtData<'a> {
398    pub fn new(
399        cache: &'a OtCache,
400        coords: &'a [F2Dot14],
401        variations: SelectedFeatureVariations,
402    ) -> Self {
403        let tables = cache.tables.as_ref().map_or(&EMPTY_TABLES, Yoke::get);
404        Self {
405            cache,
406            tables,
407            var_store: tables
408                .gdef
409                .var_store
410                .as_ref()
411                .filter(|_| !coords.is_empty()),
412            coords,
413            feature_variations: [variations.gsub, variations.gpos],
414            has_lookup_variations: variations.has_lookup_variations,
415        }
416    }
417
418    pub fn gsub(&self) -> Option<GsubTable<'a>> {
419        self.tables.gsub.is_some().then_some(GsubTable {
420            lookups: &self.cache.gsub,
421        })
422    }
423
424    pub fn gpos(&self) -> Option<GposTable<'a>> {
425        self.tables.gpos.is_some().then_some(GposTable {
426            lookups: &self.cache.gpos,
427        })
428    }
429
430    /// The variation store, if the font is variable and has an instance.
431    pub fn var_store(&self) -> Option<&'a ItemVariationStore<'a>> {
432        self.var_store
433    }
434
435    pub(crate) fn layout_table(&self, table_index: LayoutTableKind) -> Option<LayoutTable<'a>> {
436        match table_index {
437            LayoutTableKind::Gsub => self.tables.gsub.clone().map(LayoutTable::Gsub),
438            LayoutTableKind::Gpos => self.tables.gpos.clone().map(LayoutTable::Gpos),
439        }
440    }
441
442    pub(crate) fn layout_tables(
443        &self,
444    ) -> impl Iterator<Item = (LayoutTableKind, LayoutTable<'a>)> + '_ {
445        LayoutTableKind::iter()
446            .filter_map(move |idx| self.layout_table(idx).map(|table| (idx, table)))
447    }
448
449    pub fn has_glyph_classes(&self) -> bool {
450        !self.tables.gdef.classes.is_none()
451    }
452
453    pub fn glyph_class(&self, glyph_id: u32) -> u16 {
454        self.tables.gdef.classes.get(GlyphId::new(glyph_id)) as u16
455    }
456
457    pub fn glyph_mark_attachment_class(&self, glyph_id: u32) -> u16 {
458        // Glyph props keep only the low bits, as in HarfBuzz.
459        self.tables.gdef.mark_classes.get(GlyphId::new(glyph_id)) as u16
460    }
461
462    pub(crate) fn glyph_props(&self, glyph: GlyphId) -> u16 {
463        let glyph = glyph.to_u32();
464
465        if let Some(props) = self.cache.gdef_glyph_props_cache.get(glyph) {
466            return props as u16;
467        }
468
469        let props = match self.glyph_class(glyph) {
470            1 => GlyphPropsFlags::BASE_GLYPH.bits(),
471            2 => GlyphPropsFlags::LIGATURE.bits(),
472            3 => {
473                let class = self.glyph_mark_attachment_class(glyph);
474                (class << 8) | GlyphPropsFlags::MARK.bits()
475            }
476            _ => 0,
477        };
478
479        self.cache.gdef_glyph_props_cache.set(glyph, props as u32);
480
481        props
482    }
483
484    #[inline(always)]
485    pub fn is_mark_glyph(&self, glyph_id: u32, set_index: u16) -> bool {
486        self.tables
487            .gdef
488            .mark_sets
489            .get(set_index as usize)
490            .is_some_and(|set| {
491                set.bitmap
492                    .covers(glyph_id)
493                    .unwrap_or_else(|| set.covers(glyph_id))
494            })
495    }
496
497    pub fn lookup(
498        &self,
499        table_index: LayoutTableKind,
500        lookup_index: u16,
501    ) -> Option<&'a CachedLookup<'a>> {
502        // A missing table has no lookups.
503        if table_index == LayoutTableKind::Gsub {
504            self.cache.gsub.get(lookup_index)
505        } else {
506            self.cache.gpos.get(lookup_index)
507        }
508    }
509
510    pub(super) fn resolve_anchor(&self, anchor: &AnchorTable) -> (f32, f32) {
511        let mut x = anchor.x_coordinate() as f32;
512        let mut y = anchor.y_coordinate() as f32;
513        if let Some(vs) = self.var_store() {
514            // Keep the delta fractional; the caller rounds once when scaling,
515            // matching HarfBuzz's Anchor::get_anchor.
516            let delta = |val: Option<Result<DeviceOrVariationIndex<'_>, ReadError>>| match val {
517                Some(Ok(DeviceOrVariationIndex::VariationIndex(varix))) => {
518                    vs.compute_delta(
519                        DeltaSetIndex {
520                            outer: varix.delta_set_outer_index(),
521                            inner: varix.delta_set_inner_index(),
522                        },
523                        self.coords,
524                    )
525                    .unwrap_or_default()
526                    .to_f64() as f32
527                }
528                _ => 0.0,
529            };
530            x += delta(anchor.x_device());
531            y += delta(anchor.y_device());
532        }
533        (x, y)
534    }
535}
536
537pub enum LayoutTable<'a> {
538    Gsub(Gsub<'a>),
539    Gpos(Gpos<'a>),
540}
541
542impl<'a> LayoutTable<'a> {
543    fn script_list(&self) -> Option<ScriptList<'a>> {
544        match self {
545            Self::Gsub(gsub) => gsub.script_list().ok(),
546            Self::Gpos(gpos) => gpos.script_list().ok(),
547        }
548    }
549
550    fn feature_list(&self) -> Option<FeatureList<'a>> {
551        match self {
552            Self::Gsub(gsub) => gsub.feature_list().ok(),
553            Self::Gpos(gpos) => gpos.feature_list().ok(),
554        }
555    }
556
557    /// The table's lookup variations, if it has any.
558    pub(crate) fn lookup_variations(&self) -> Option<LookupVariations<'a>> {
559        self.feature_variations()?.lookup_variations()
560    }
561
562    fn feature_variations(&self) -> Option<FeatureVariations<'a>> {
563        match self {
564            Self::Gsub(gsub) => gsub.feature_variations(),
565            Self::Gpos(gpos) => gpos.feature_variations(),
566        }
567        .transpose()
568        .ok()
569        .flatten()
570    }
571
572    fn script(&self, index: u16) -> Option<LayoutScript<'a>> {
573        self.script_list()?
574            .get(index)
575            .ok()
576            .map(|script| script.element)
577    }
578
579    fn langsys_index(&self, script_index: u16, tag: Tag) -> Option<u16> {
580        let script = self.script(script_index)?;
581        script.lang_sys_index_for_tag(tag)
582    }
583
584    fn langsys(&self, script_index: u16, langsys_index: Option<u16>) -> Option<LangSys<'a>> {
585        let script = self.script(script_index)?;
586        if let Some(index) = langsys_index {
587            let record = script.lang_sys_records().get(index as usize)?;
588            record.lang_sys(script.offset_data()).ok()
589        } else {
590            script.default_lang_sys().transpose().ok().flatten()
591        }
592    }
593
594    pub(crate) fn feature(&self, index: u16) -> Option<LayoutFeature<'a>> {
595        self.feature_list()?
596            .get(index)
597            .ok()
598            .map(|feature| feature.element)
599    }
600
601    fn feature_tag(&self, index: u16) -> Option<Tag> {
602        self.feature_list()?
603            .get(index)
604            .ok()
605            .map(|feature| feature.tag)
606    }
607
608    pub(crate) fn feature_substitution(
609        &self,
610        variation_index: u32,
611        feature_index: u16,
612    ) -> Option<LayoutFeature<'a>> {
613        let feature_variations = self.feature_variations()?;
614        let record = feature_variations
615            .feature_variation_records()
616            .get(variation_index as usize)?;
617        let subst_table = record
618            .feature_table_substitution(feature_variations.offset_data())?
619            .ok()?;
620        let subst_records = subst_table.substitutions();
621        match subst_records.binary_search_by_key(&feature_index, |subst| subst.feature_index()) {
622            Ok(ix) => Some(
623                subst_records
624                    .get(ix)?
625                    .alternate_feature(subst_table.offset_data())
626                    .ok()?,
627            ),
628            _ => None,
629        }
630    }
631
632    pub(crate) fn feature_index(&self, tag: Tag) -> Option<u16> {
633        let list = self.feature_list()?;
634        for (index, feature) in list.feature_records().iter().enumerate() {
635            if feature.feature_tag() == tag {
636                return Some(index as u16);
637            }
638        }
639        None
640    }
641
642    pub(crate) fn lookup_count(&self) -> u16 {
643        match self {
644            Self::Gsub(gsub) => gsub
645                .lookup_list()
646                .map(|list| list.lookup_count())
647                .unwrap_or_default(),
648            Self::Gpos(gpos) => gpos
649                .lookup_list()
650                .map(|list| list.lookup_count())
651                .unwrap_or_default(),
652        }
653    }
654
655    // hb_ot_layout_table_select_script
656    /// Returns true + index and tag of the first found script tag in the given GSUB or GPOS table
657    /// or false + index and tag if falling back to a default script.
658    pub(crate) fn select_script(&self, script_tags: &[Tag]) -> Option<(bool, u16, Tag)> {
659        let selected = self.script_list()?.select(script_tags)?;
660        Some((!selected.is_fallback, selected.index, selected.tag))
661    }
662
663    // hb_ot_layout_script_select_language
664    /// Returns the index of the first found language tag in the given GSUB or GPOS table,
665    /// underneath the specified script index.
666    pub(crate) fn select_script_language(
667        &self,
668        script_index: u16,
669        lang_tags: &[Tag],
670    ) -> Option<u16> {
671        for &tag in lang_tags {
672            if let Some(index) = self.langsys_index(script_index, tag) {
673                return Some(index);
674            }
675        }
676
677        // try finding 'dflt'
678        if let Some(index) = self.langsys_index(script_index, Tag::default_language()) {
679            return Some(index);
680        }
681
682        None
683    }
684
685    // hb_ot_layout_language_get_required_feature
686    /// Returns the index and tag of a required feature in the given GSUB or GPOS table,
687    /// underneath the specified script and language.
688    pub(crate) fn get_required_language_feature(
689        &self,
690        script_index: u16,
691        lang_index: Option<u16>,
692    ) -> Option<(u16, Tag)> {
693        let sys = self.langsys(script_index, lang_index)?;
694        let idx = sys.required_feature_index();
695        if idx == 0xFFFF {
696            return None;
697        }
698        let tag = self.feature_tag(idx)?;
699        Some((idx, tag))
700    }
701
702    // hb_ot_layout_language_find_feature
703    /// Returns the index of a given feature tag in the given GSUB or GPOS table,
704    /// underneath the specified script and language.
705    pub(crate) fn find_language_feature(
706        &self,
707        script_index: u16,
708        lang_index: Option<u16>,
709        feature_tag: Tag,
710    ) -> Option<u16> {
711        self.langsys(script_index, lang_index)?
712            .feature_index_for_tag(&self.feature_list()?, feature_tag)
713    }
714}
715
716use crate::algs::HB_CODEPOINT_ENCODE3 as encode3;
717
718/// Blocklist specific broken GDEF tables identified by the combination of
719/// GDEF, GSUB, and GPOS table lengths. Nuke the GDEF tables to avoid
720/// unwanted width-zeroing.
721///
722/// In certain versions of Times New Roman Italic and Bold Italic,
723/// ASCII double quotation mark U+0022 has wrong glyph class 3 (mark)
724/// in GDEF. Many versions of Tahoma have bad GDEF tables that
725/// incorrectly classify some spacing marks such as certain IPA
726/// symbols as glyph class 3. So do older versions of Microsoft
727/// Himalaya, and the version of Cantarell shipped by Ubuntu 16.04.
728///
729/// See https://lists.freedesktop.org/archives/harfbuzz/2016-February/005489.html
730///     https://bugzilla.mozilla.org/show_bug.cgi?id=1279925
731///     https://bugzilla.mozilla.org/show_bug.cgi?id=1279693
732///     https://bugzilla.mozilla.org/show_bug.cgi?id=1279875
733///
734/// Upstream: hb-ot-layout.cc OT::GDEF::is_blocklisted
735fn is_gdef_blocklisted(gdef_len: u32, gsub_len: u32, gpos_len: u32) -> bool {
736    const BLOCKLIST: &[u64] = &[
737        // Windows 7? timesi.ttf
738        encode3(442, 2874, 42038),
739        // Windows 7? timesbi.ttf
740        encode3(430, 2874, 40662),
741        // Windows 7 timesi.ttf
742        encode3(442, 2874, 39116),
743        // Windows 7 timesbi.ttf
744        encode3(430, 2874, 39374),
745        // OS X 10.11.3 Times New Roman Italic.ttf
746        encode3(490, 3046, 41638),
747        // OS X 10.11.3 Times New Roman Bold Italic.ttf
748        encode3(478, 3046, 41902),
749        // tahoma.ttf from Windows 8
750        encode3(898, 12554, 46470),
751        // tahomabd.ttf from Windows 8
752        encode3(910, 12566, 47732),
753        // tahoma.ttf from Windows 8.1
754        encode3(928, 23298, 59332),
755        // tahomabd.ttf from Windows 8.1
756        encode3(940, 23310, 60732),
757        // tahoma.ttf v6.04 from Windows 8.1 x64
758        encode3(964, 23836, 60072),
759        // tahomabd.ttf v6.04 from Windows 8.1 x64
760        encode3(976, 23832, 61456),
761        // tahoma.ttf from Windows 10
762        encode3(994, 24474, 60336),
763        // tahomabd.ttf from Windows 10
764        encode3(1006, 24470, 61740),
765        // tahoma.ttf v6.91 from Windows 10 x64
766        encode3(1006, 24576, 61346),
767        // tahomabd.ttf v6.91 from Windows 10 x64
768        encode3(1018, 24572, 62828),
769        // tahoma.ttf from Windows 10 AU
770        encode3(1006, 24576, 61352),
771        // tahomabd.ttf from Windows 10 AU
772        encode3(1018, 24572, 62834),
773        // Tahoma.ttf from Mac OS X 10.9
774        encode3(832, 7324, 47162),
775        // Tahoma Bold.ttf from Mac OS X 10.9
776        encode3(844, 7302, 45474),
777        // himalaya.ttf from Windows 7
778        encode3(180, 13054, 7254),
779        // himalaya.ttf from Windows 8
780        encode3(192, 12638, 7254),
781        // himalaya.ttf from Windows 8.1
782        encode3(192, 12690, 7254),
783        // cantarell-fonts-0.0.21 Cantarell-Regular.otf / Cantarell-Oblique.otf
784        encode3(188, 248, 3852),
785        // cantarell-fonts-0.0.21 Cantarell-Bold.otf / Cantarell-Bold-Oblique.otf
786        encode3(188, 264, 3426),
787        // padauk-2.80/Padauk.ttf RHEL 7.2
788        encode3(1058, 47032, 11818),
789        // padauk-2.80/Padauk-Bold.ttf RHEL 7.2
790        encode3(1046, 47030, 12600),
791        // padauk-2.80/Padauk.ttf Ubuntu 16.04
792        encode3(1058, 71796, 16770),
793        // padauk-2.80/Padauk-Bold.ttf Ubuntu 16.04
794        encode3(1046, 71790, 17862),
795        // padauk-2.80/Padauk-book.ttf
796        encode3(1046, 71788, 17112),
797        // padauk-2.80/Padauk-bookbold.ttf
798        encode3(1058, 71794, 17514),
799        // padauk-3.0/Padauk-book.ttf
800        encode3(1330, 109_904, 57938),
801        // padauk-3.0/Padauk-bookbold.ttf
802        encode3(1330, 109_904, 58972),
803        // Padauk.ttf "Version 2.5", https://crbug.com/681813
804        encode3(1004, 59092, 14836),
805        // Courier New.ttf from macOS 15
806        encode3(588, 5078, 14418),
807        // Courier New Bold.ttf from macOS 15
808        encode3(588, 5078, 14238),
809        // cour.ttf from Windows 10
810        encode3(894, 17162, 33960),
811        // courbd.ttf from Windows 10
812        encode3(894, 17154, 34472),
813        // cour.ttf from Windows 8.1
814        encode3(816, 7868, 17052),
815        // courbd.ttf from Windows 8.1
816        encode3(816, 7868, 17138),
817    ];
818    let key = encode3(gdef_len, gsub_len, gpos_len);
819    BLOCKLIST.contains(&key)
820}
821
822#[cfg(test)]
823mod tests {
824    use super::*;
825    use read_fonts::FontRead;
826
827    #[test]
828    fn exhausted_mark_sets_are_discarded_together() {
829        // GDEF 1.2, with two mark-set offsets aliasing one coverage.
830        let words: [u16; 16] = [1, 2, 0, 0, 0, 0, 14, 1, 2, 0, 12, 0, 12, 1, 1, 42];
831        let data: Vec<_> = words.into_iter().flat_map(u16::to_be_bytes).collect();
832        let gdef = Gdef::read(FontData::new(&data)).unwrap();
833        let cache = CachedGdef::new(&gdef, &Budget::new(4, 1024));
834        assert_eq!(cache.mark_sets.len(), 2);
835        assert!(cache.mark_sets.iter().all(|set| set.covers(42)));
836
837        // Exhaustion while building the second set must discard the first.
838        let cache = CachedGdef::new(&gdef, &Budget::new(3, 1024));
839        assert!(cache.mark_sets.is_empty());
840        let cache = CachedGdef::new(&gdef, &Budget::new(4, 0));
841        assert!(cache.mark_sets.is_empty());
842    }
843}