Skip to main content

harfrust/
shaper_font.rs

1//! The font data and callbacks visible to a shaping operation.
2
3use alloc::boxed::Box;
4use core::{mem::size_of, ops::Deref, ptr, slice};
5use read_fonts::types::GlyphId;
6use read_fonts::TableProvider;
7
8use crate::aat::{AatCache, AatData, EMPTY_AAT_DATA};
9use crate::buffer::{Buffer, GlyphInfo, GlyphPosition};
10use crate::cache::Cache;
11use crate::font::Font;
12use crate::once::Once;
13use crate::ot::{OtCache, OtData, EMPTY_OT_DATA};
14use crate::scale::Scale;
15use read_fonts::model::{
16    charmap::Charmap,
17    metrics::{GlyphMetrics, ScaledGlyphMetrics},
18    name::GlyphName,
19};
20
21/// A font configured for shaping and font queries.
22///
23/// Uses the font's own character map and metrics by default. A scale and
24/// custom [`FontFuncs`] can be set to change the queries used during shaping.
25/// Dereferences to the underlying [`Font`] for direct font queries.
26#[derive(Clone)]
27pub struct ShaperFont<'a, 'f> {
28    font: &'a Font,
29    ot: OtData<'a>,
30    aat: AatData<'a>,
31    units_per_em: u16,
32    apply_trak: bool,
33    charmap: Charmap<'a>,
34    glyph_metrics: Once<GlyphMetrics<'a>>,
35    cmap_cache: Option<&'a CharmapCache>,
36    symbol_font_page: Once<u16>,
37    pub(crate) scale: Scale,
38    funcs: Option<&'f dyn FontFuncs>,
39}
40
41impl<'a, 'f> ShaperFont<'a, 'f> {
42    /// Prepares a font for shaping, reusing its cached layout data.
43    pub fn new(font: &'a Font) -> Self {
44        let cached = layout_cache(font);
45        let (ot, aat, apply_trak, cmap_cache) = if let Some(cache) = cached {
46            let coords = font.normalized_coords();
47            // The default location can select a feature variation too, and
48            // shape plan keys ask the font the same way.
49            let variations = font.feature_variations();
50            (
51                OtData::new(&cache.ot, coords, variations),
52                AatData::new(&cache.aat),
53                cache.apply_trak,
54                Some(&cache.cmap),
55            )
56        } else {
57            (EMPTY_OT_DATA.clone(), EMPTY_AAT_DATA.clone(), false, None)
58        };
59        let scale = Scale::default();
60        Self {
61            font,
62            ot,
63            aat,
64            units_per_em: font.units_per_em(),
65            apply_trak,
66            charmap: font.charmap(),
67            glyph_metrics: Once::new(),
68            cmap_cache,
69            symbol_font_page: Once::new(),
70            scale,
71            funcs: None,
72        }
73    }
74
75    /// Returns the currently active normalized coordinates.
76    pub fn normalized_coords(&self) -> &[crate::font::NormalizedCoord] {
77        self.font.normalized_coords()
78    }
79
80    /// Sets the same scale on both axes.
81    pub fn set_scale(&mut self, scale: i32) {
82        self.set_scale_separate(scale, scale);
83    }
84
85    /// Returns a new shaping font with the same scale applied to both axes.
86    pub fn with_scale(mut self, scale: i32) -> Self {
87        self.set_scale(scale);
88        self
89    }
90
91    /// Sets independent horizontal and vertical scales.
92    pub fn set_scale_separate(&mut self, x_scale: i32, y_scale: i32) {
93        self.scale = Scale::new(Some((x_scale, y_scale)), self.units_per_em as i32);
94    }
95
96    /// Returns a new shaping font with independent horizontal and vertical scales applied.
97    pub fn with_scale_separate(mut self, x_scale: i32, y_scale: i32) -> Self {
98        self.set_scale_separate(x_scale, y_scale);
99        self
100    }
101
102    /// Replaces the callbacks used for effective font queries.
103    pub fn set_font_funcs(&mut self, funcs: Option<&'f dyn FontFuncs>) {
104        self.funcs = funcs;
105    }
106
107    /// Returns a new shaping font with the specified font function callbacks.
108    pub fn with_font_funcs(mut self, funcs: Option<&'f dyn FontFuncs>) -> Self {
109        self.set_font_funcs(funcs);
110        self
111    }
112
113    /// Returns the conversion from font units to the configured scale.
114    pub fn scale(&self) -> Scale {
115        self.scale
116    }
117
118    /// Returns the name stored for a glyph in the font, if any.
119    pub fn glyph_name(&self, glyph: GlyphId) -> Option<GlyphName> {
120        self.font.glyph_name(glyph)
121    }
122
123    /// Maps a character through the configured callbacks.
124    pub fn nominal_glyph(&self, codepoint: u32) -> Option<GlyphId> {
125        self.funcs.map_or_else(
126            || self.default_nominal_glyph(codepoint),
127            |f| f.nominal_glyph(self, codepoint),
128        )
129    }
130
131    /// Maps a character using the font's own charmap.
132    pub fn default_nominal_glyph(&self, codepoint: u32) -> Option<GlyphId> {
133        if let Some(gid) = self.cmap_cache().and_then(|cache| cache.get(codepoint)) {
134            Some(gid.into())
135        } else if let Some(gid) = self.map_unicode(codepoint) {
136            if let Some(cache) = self.cmap_cache() {
137                cache.set(codepoint, gid.to_u32());
138            }
139            Some(gid)
140        } else {
141            None
142        }
143    }
144
145    /// Maps a batch of codepoints through the configured callbacks.
146    pub fn nominal_glyphs(&self, glyphs: NominalGlyphs<'_>) -> usize {
147        if let Some(funcs) = self.funcs {
148            funcs.nominal_glyphs(self, glyphs)
149        } else {
150            self.default_nominal_glyphs(glyphs)
151        }
152    }
153
154    /// Maps a batch of codepoints using the font's own charmap.
155    pub fn default_nominal_glyphs(&self, glyphs: NominalGlyphs<'_>) -> usize {
156        let mut done = 0;
157        for (codepoint, glyph) in glyphs {
158            match self.default_nominal_glyph(codepoint) {
159                Some(gid) => *glyph = gid,
160                None => break,
161            }
162            done += 1;
163        }
164        done
165    }
166
167    /// Maps a character and variation selector through the configured callbacks.
168    pub fn variation_glyph(&self, codepoint: u32, selector: u32) -> Option<GlyphId> {
169        self.funcs.map_or_else(
170            || self.default_variation_glyph(codepoint, selector),
171            |f| f.variation_glyph(self, codepoint, selector),
172        )
173    }
174
175    /// Maps a variation sequence using the font's own charmap.
176    pub fn default_variation_glyph(&self, codepoint: u32, selector: u32) -> Option<GlyphId> {
177        self.charmap.map_unicode_variant(codepoint, selector)
178    }
179
180    /// Returns the effective horizontal advance.
181    pub fn glyph_h_advance(&self, glyph: GlyphId) -> i32 {
182        self.funcs.map_or_else(
183            || self.default_glyph_h_advance(glyph),
184            |f| f.glyph_h_advance(self, glyph),
185        )
186    }
187
188    /// Returns the scaled horizontal advance from the font's own tables.
189    pub fn default_glyph_h_advance(&self, glyph: GlyphId) -> i32 {
190        self.scale
191            .clamp_x_advance(self.glyph_metrics().h_advance(glyph))
192    }
193
194    /// Writes effective horizontal advances for a batch of glyphs.
195    pub fn glyph_h_advances(&self, advances: Advances<'_>) {
196        if let Some(funcs) = self.funcs {
197            funcs.glyph_h_advances(self, advances);
198        } else {
199            self.default_glyph_h_advances(advances);
200        }
201    }
202
203    /// Writes scaled horizontal advances from the font's own tables.
204    pub fn default_glyph_h_advances(&self, advances: Advances<'_>) {
205        self.glyph_metrics().h_advance_batched(
206            |advance| self.scale.clamp_x_advance(advance),
207            advances.into_iter(),
208        );
209    }
210
211    /// Returns the effective vertical advance.
212    pub fn glyph_v_advance(&self, glyph: GlyphId) -> i32 {
213        self.funcs.map_or_else(
214            || self.default_glyph_v_advance(glyph),
215            |f| f.glyph_v_advance(self, glyph),
216        )
217    }
218
219    /// Returns the scaled vertical advance from the font's own tables.
220    pub fn default_glyph_v_advance(&self, glyph: GlyphId) -> i32 {
221        self.scale
222            .clamp_y_advance(self.glyph_metrics().v_advance(glyph))
223            .saturating_neg()
224    }
225
226    /// Returns the effective vertical origin.
227    pub fn glyph_v_origin(&self, glyph: GlyphId) -> (i32, i32) {
228        self.funcs.map_or_else(
229            || self.default_glyph_v_origin(glyph),
230            |f| f.glyph_v_origin(self, glyph),
231        )
232    }
233
234    /// Returns the scaled vertical origin from the font's own tables.
235    pub fn default_glyph_v_origin(&self, glyph: GlyphId) -> (i32, i32) {
236        let y = if self.funcs.is_some() {
237            let extents = |glyph| {
238                self.glyph_extents(glyph)
239                    .map(|extents| read_fonts::model::metrics::GlyphExtents {
240                        x_bearing: extents.x_bearing,
241                        y_bearing: extents.y_bearing,
242                        width: extents.width,
243                        height: extents.height.saturating_neg(),
244                    })
245            };
246            self.glyph_metrics()
247                .with_glyph_extents(Some(&extents))
248                .v_origin_y(glyph)
249        } else {
250            self.glyph_metrics().v_origin_y(glyph)
251        };
252        (self.glyph_h_advance(glyph) / 2, y)
253    }
254
255    /// Returns the effective glyph extents.
256    pub fn glyph_extents(&self, glyph: GlyphId) -> Option<GlyphExtents> {
257        self.funcs.map_or_else(
258            || self.default_glyph_extents(glyph),
259            |f| f.glyph_extents(self, glyph),
260        )
261    }
262
263    /// Returns the scaled glyph extents from the font's own tables.
264    pub fn default_glyph_extents(&self, glyph: GlyphId) -> Option<GlyphExtents> {
265        self.glyph_metrics()
266            .extents(glyph)
267            .map(|extents| GlyphExtents {
268                x_bearing: extents.x_bearing,
269                y_bearing: extents.y_bearing,
270                width: extents.width,
271                height: extents.height.saturating_neg(),
272            })
273    }
274}
275
276impl Deref for ShaperFont<'_, '_> {
277    type Target = Font;
278
279    fn deref(&self) -> &Self::Target {
280        self.font
281    }
282}
283
284/// Overrides character mapping and glyph metrics for a [`ShaperFont`].
285///
286/// Scalar methods default to queries on the underlying font; batch methods
287/// call their scalar counterparts. Implement only the callbacks that need
288/// different behavior. Callbacks take `&self`; mutable state can be managed
289/// by the implementation.
290///
291/// # Metrics scaling
292///
293/// All font metrics returned by these callbacks must be consistent with the
294/// scale factor configured on [`ShaperFont`].
295///
296/// If no scale is set, values must be in unscaled font units (i.e. the same
297/// coordinate space as the font's `units_per_em`). If a scale is set —
298/// for example `font_size * 64` for FreeType-style 26.6 — then all returned
299/// values must already be in that scaled coordinate space.
300pub trait FontFuncs {
301    /// Nominal character-to-glyph mapping callback.
302    fn nominal_glyph(&self, font: &ShaperFont, c: u32) -> Option<GlyphId> {
303        font.default_nominal_glyph(c)
304    }
305
306    /// Batch nominal character-to-glyph mapping callback.
307    ///
308    /// Maps a run of codepoints to glyphs, stopping at the first
309    /// codepoint the font has no glyph for. Returns the number of
310    /// consecutive codepoints mapped.
311    fn nominal_glyphs(&self, font: &ShaperFont, glyphs: NominalGlyphs<'_>) -> usize {
312        let mut done = 0;
313        for (codepoint, glyph) in glyphs {
314            match self.nominal_glyph(font, codepoint) {
315                Some(gid) => *glyph = gid,
316                None => break,
317            }
318            done += 1;
319        }
320        done
321    }
322
323    /// Variation-selector mapping callback.
324    fn variation_glyph(&self, font: &ShaperFont, c: u32, vs: u32) -> Option<GlyphId> {
325        font.default_variation_glyph(c, vs)
326    }
327
328    /// Horizontal advance callback.
329    ///
330    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
331    /// on what value this method should return.
332    fn glyph_h_advance(&self, font: &ShaperFont, glyph: GlyphId) -> i32 {
333        font.default_glyph_h_advance(glyph)
334    }
335
336    /// Batch horizontal-advance callback.
337    ///
338    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
339    /// on what value this method should return.
340    fn glyph_h_advances(&self, font: &ShaperFont, advances: Advances<'_>) {
341        for (glyph, advance) in advances {
342            *advance = self.glyph_h_advance(font, glyph);
343        }
344    }
345
346    /// Vertical advance callback.
347    ///
348    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
349    /// on what value this method should return.
350    fn glyph_v_advance(&self, font: &ShaperFont, glyph: GlyphId) -> i32 {
351        font.default_glyph_v_advance(glyph)
352    }
353
354    /// Vertical origin callback.
355    ///
356    /// Returns the (x, y) coordinates of the vertical origin for the given glyph.
357    ///
358    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
359    /// on what values this method should return.
360    fn glyph_v_origin(&self, font: &ShaperFont, glyph: GlyphId) -> (i32, i32) {
361        font.default_glyph_v_origin(glyph)
362    }
363
364    /// Glyph extents callback.
365    ///
366    /// See "Metrics scaling" in the [trait-level docs](FontFuncs) for details
367    /// on what values this method should return.
368    fn glyph_extents(&self, font: &ShaperFont, glyph: GlyphId) -> Option<GlyphExtents> {
369        font.default_glyph_extents(glyph)
370    }
371}
372
373/// The ink extents of a glyph.
374///
375/// Values use the configured font scale, or font units if no scale was set.
376/// The bearings locate the top-left corner of the ink box relative to the
377/// glyph origin. Height is usually negative in a Y-up coordinate system.
378#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)]
379#[repr(C)]
380pub struct GlyphExtents {
381    /// Horizontal bearing from glyph origin to the left side of the ink box.
382    pub x_bearing: i32,
383    /// Vertical bearing from glyph origin to the top of the ink box.
384    pub y_bearing: i32,
385    /// Width of the glyph ink box.
386    pub width: i32,
387    /// Height of the glyph ink box.
388    pub height: i32,
389}
390
391/// A batch of codepoints and writable nominal glyphs.
392///
393/// Nominal glyphs must be written for consecutive codepoints starting at
394/// the first entry; mapping stops at the first codepoint the font has no
395/// glyph for, and the number of glyphs written is returned from
396/// [`FontFuncs::nominal_glyphs`](crate::FontFuncs::nominal_glyphs).
397pub struct NominalGlyphs<'a> {
398    pub(crate) infos: &'a mut [GlyphInfo],
399}
400
401impl<'a> NominalGlyphs<'a> {
402    pub(crate) fn new(infos: &'a mut [GlyphInfo]) -> Self {
403        Self { infos }
404    }
405
406    /// Returns the number of entries in the batch.
407    pub fn len(&self) -> usize {
408        self.infos.len()
409    }
410
411    /// Returns true if the batch is empty.
412    pub fn is_empty(&self) -> bool {
413        self.infos.is_empty()
414    }
415}
416
417/// Iterates over codepoints and writable glyphs.
418pub struct NominalGlyphsIter<'a> {
419    infos: slice::IterMut<'a, GlyphInfo>,
420}
421
422impl<'a> Iterator for NominalGlyphsIter<'a> {
423    type Item = (u32, &'a mut GlyphId);
424
425    fn next(&mut self) -> Option<Self::Item> {
426        let info = self.infos.next()?;
427        let codepoint = info.glyph_id;
428        let var_index = GlyphInfo::NORMALIZER_GLYPH_INDEX_VAR.var_index as usize - 1;
429        Some((codepoint, bytemuck::cast_mut(&mut info.vars[var_index])))
430    }
431}
432
433impl<'a> IntoIterator for NominalGlyphs<'a> {
434    type Item = (u32, &'a mut GlyphId);
435    type IntoIter = NominalGlyphsIter<'a>;
436
437    fn into_iter(self) -> Self::IntoIter {
438        NominalGlyphsIter {
439            infos: self.infos.iter_mut(),
440        }
441    }
442}
443
444/// Raw C-style view over a batch of codepoints and output glyphs.
445#[derive(Clone, Copy, Debug)]
446pub struct RawNominalGlyphs {
447    /// Number of batch entries.
448    pub len: usize,
449    /// Pointer to codepoints (read-only).
450    pub codepoints: *const u32,
451    /// Pointer to output glyphs (writable).
452    pub glyphs: *mut u32,
453    /// Byte stride between successive codepoints.
454    pub codepoint_stride: isize,
455    /// Byte stride between successive glyphs.
456    pub glyph_stride: isize,
457}
458
459impl NominalGlyphs<'_> {
460    /// Byte offset of the output glyph id within a batch entry.
461    const GLYPH_OFFSET: usize = core::mem::offset_of!(GlyphInfo, vars)
462        + (GlyphInfo::NORMALIZER_GLYPH_INDEX_VAR.var_index as usize - 1) * size_of::<u32>();
463
464    /// Returns a raw C-style view over this batch.
465    pub fn into_raw(self) -> RawNominalGlyphs {
466        if self.infos.is_empty() {
467            return RawNominalGlyphs {
468                len: 0,
469                codepoints: ptr::null(),
470                glyphs: ptr::null_mut(),
471                codepoint_stride: size_of::<GlyphInfo>() as isize,
472                glyph_stride: size_of::<GlyphInfo>() as isize,
473            };
474        }
475
476        let base = self.infos.as_mut_ptr();
477        RawNominalGlyphs {
478            len: self.infos.len(),
479            // `glyph_id` is the first field in `GlyphInfo` and holds the
480            // codepoint before mapping.
481            codepoints: base.cast::<u32>().cast_const(),
482            // The normalizer glyph-index var.
483            glyphs: base.wrapping_byte_add(Self::GLYPH_OFFSET).cast::<u32>(),
484            codepoint_stride: size_of::<GlyphInfo>() as isize,
485            glyph_stride: size_of::<GlyphInfo>() as isize,
486        }
487    }
488}
489
490/// A batch of glyphs and their writable advances.
491pub struct Advances<'a> {
492    pub(crate) infos: &'a [GlyphInfo],
493    pub(crate) positions: &'a mut [GlyphPosition],
494}
495
496impl<'a> Advances<'a> {
497    pub(crate) fn new(buffer: &'a mut Buffer) -> Self {
498        let len = buffer.len;
499        match (buffer.info.get(..len), buffer.pos.get_mut(..len)) {
500            (Some(infos), Some(positions)) => Self { infos, positions },
501            // The raw view uses one length for both arrays, so a short one empties the batch.
502            _ => Self {
503                infos: &[],
504                positions: &mut [],
505            },
506        }
507    }
508
509    /// Returns the number of entries in the batch.
510    pub fn len(&self) -> usize {
511        self.infos.len()
512    }
513
514    /// Returns true if the batch is empty.
515    pub fn is_empty(&self) -> bool {
516        self.infos.is_empty()
517    }
518}
519
520/// Iterates over glyphs and their writable advances.
521pub struct AdvancesIter<'a> {
522    infos: slice::Iter<'a, GlyphInfo>,
523    positions: slice::IterMut<'a, GlyphPosition>,
524}
525
526impl<'a> Iterator for AdvancesIter<'a> {
527    type Item = (GlyphId, &'a mut i32);
528
529    fn next(&mut self) -> Option<Self::Item> {
530        let info = self.infos.next()?;
531        let pos = self.positions.next()?;
532        Some((info.as_glyph(), &mut pos.x_advance))
533    }
534}
535
536impl<'a> IntoIterator for Advances<'a> {
537    type Item = (GlyphId, &'a mut i32);
538    type IntoIter = AdvancesIter<'a>;
539
540    fn into_iter(self) -> Self::IntoIter {
541        AdvancesIter {
542            infos: self.infos.iter(),
543            positions: self.positions.iter_mut(),
544        }
545    }
546}
547
548/// Raw C-style view over a batch of glyphs and their writable advances.
549#[derive(Clone, Copy, Debug)]
550pub struct RawAdvances {
551    /// Number of batch entries.
552    pub len: usize,
553    /// Pointer to glyphs (read-only).
554    pub gids: *const u32,
555    /// Pointer to horizontal advances (writable).
556    ///
557    /// See "Metrics scaling" in the [FontFuncs] for details
558    /// on what value this method should return.
559    pub advances: *mut i32,
560    /// Byte stride between successive glyphs.
561    pub gid_stride: isize,
562    /// Byte stride between successive advances.
563    pub advance_stride: isize,
564}
565
566impl Advances<'_> {
567    /// Returns a raw C-style view over this batch.
568    pub fn into_raw(self) -> RawAdvances {
569        if self.infos.is_empty() {
570            return RawAdvances {
571                len: 0,
572                gids: ptr::null(),
573                advances: ptr::null_mut(),
574                gid_stride: size_of::<GlyphInfo>() as isize,
575                advance_stride: size_of::<GlyphPosition>() as isize,
576            };
577        }
578
579        RawAdvances {
580            len: self.infos.len(),
581            // `glyph_id` is the first field in `GlyphInfo`.
582            gids: self.infos.as_ptr().cast::<u32>(),
583            // `x_advance` is the first field in `GlyphPosition`.
584            advances: self.positions.as_mut_ptr().cast::<i32>(),
585            gid_stride: size_of::<GlyphInfo>() as isize,
586            advance_stride: size_of::<GlyphPosition>() as isize,
587        }
588    }
589}
590
591pub(crate) type CharmapCache = Cache<21, 19, 256, 32>;
592
593/// Font-wide layout data shared by shapers at different variation positions.
594pub(crate) struct LayoutCache {
595    pub ot: OtCache,
596    pub aat: AatCache,
597    pub cmap: CharmapCache,
598    /// True if the font has both `trak` and `STAT` tables.
599    pub apply_trak: bool,
600}
601
602impl LayoutCache {
603    pub(crate) fn new(font: &Font) -> Self {
604        let tables = font.tables();
605        let host = crate::font::_font_interop::_table_cache_host(font);
606        let ot = OtCache::new(host.clone());
607        let aat = AatCache::new(host, &ot);
608        let apply_trak = tables.trak_data().is_some() && tables.stat_data().is_some();
609        Self {
610            ot,
611            aat,
612            cmap: CharmapCache::new(),
613            apply_trak,
614        }
615    }
616}
617
618/// Returns cached layout data, or `None` if the read-fonts interop slot
619/// contains an unexpected type.
620fn layout_cache(font: &Font) -> Option<&LayoutCache> {
621    let data = crate::font::_font_interop::_get_or_init_shaping_data(font, || {
622        Box::new(LayoutCache::new(font))
623    });
624    let cache = data.downcast_ref::<LayoutCache>()?;
625    Some(cache)
626}
627
628/// Prepared, read-only data for one font and variation position.
629///
630/// The table views borrow a long-lived `LayoutCache`.
631#[derive(Clone, Copy)]
632pub(crate) struct LayoutData<'a> {
633    pub ot: &'a OtData<'a>,
634    pub aat: &'a AatData<'a>,
635    pub units_per_em: u16,
636    pub apply_trak: bool,
637}
638
639impl<'a> ShaperFont<'a, '_> {
640    pub(crate) fn layout(&self) -> LayoutData<'_> {
641        LayoutData {
642            ot: &self.ot,
643            aat: &self.aat,
644            units_per_em: self.units_per_em,
645            apply_trak: self.apply_trak,
646        }
647    }
648
649    pub(crate) fn has_glyph(&self, codepoint: u32) -> bool {
650        self.nominal_glyph(codepoint).is_some()
651    }
652
653    fn cmap_cache(&self) -> Option<&CharmapCache> {
654        self.cmap_cache
655    }
656
657    fn symbol_font_page(&self) -> u16 {
658        *self.symbol_font_page.get_or_init(|| {
659            if self.charmap.unicode_is_symbol() {
660                legacy_symbol_font_page(self.font.tables().os2().ok().as_ref())
661            } else {
662                0
663            }
664        })
665    }
666
667    fn glyph_metrics(&self) -> ScaledGlyphMetrics<'a, 'static, Scale> {
668        (*self.glyph_metrics.get_or_init(|| self.font.glyph_metrics())).scaled(self.scale)
669    }
670
671    fn map_unicode(&self, codepoint: u32) -> Option<GlyphId> {
672        self.charmap.map_unicode(codepoint).or_else(|| {
673            let mapped = match self.symbol_font_page() {
674                0xB200 => arabic_pua_map(codepoint, true),
675                0xB300 => arabic_pua_map(codepoint, false),
676                _ => 0,
677            };
678            (mapped != 0)
679                .then(|| self.charmap.map_unicode(mapped))
680                .flatten()
681        })
682    }
683}
684
685fn legacy_symbol_font_page(os2: Option<&read_fonts::tables::os2::Os2<'_>>) -> u16 {
686    let Some(os2) = os2.filter(|os2| os2.version() == 0) else {
687        return 0;
688    };
689    os2.offset_data()
690        .read_at::<u16>(os2.fs_selection_byte_range().start)
691        .unwrap_or_default()
692        & 0xFF00
693}
694
695fn arabic_pua_map(codepoint: u32, simplified: bool) -> u32 {
696    let Ok(codepoint) = usize::try_from(codepoint) else {
697        return 0;
698    };
699    let mapped = if simplified {
700        crate::ot::shaper::arabic_pua::arabic_pua_simp_map(codepoint)
701    } else {
702        crate::ot::shaper::arabic_pua::arabic_pua_trad_map(codepoint)
703    };
704    u32::from(mapped)
705}
706
707#[cfg(test)]
708mod tests {
709    use super::*;
710    use crate::{aat::AatData, ot::OtData, Tag};
711    use core::sync::atomic::{AtomicUsize, Ordering};
712    use read_fonts::{FontRef, TableProvider};
713
714    use alloc::sync::Arc;
715    use read_fonts::model::{Blob, TableFunction};
716
717    #[test]
718    fn cached_glyph_metrics_are_sync() {
719        fn assert_send_sync<T: Send + Sync>() {}
720        assert_send_sync::<Once<GlyphMetrics<'static>>>();
721    }
722
723    #[test]
724    fn cached_table_disposition_skips_missing_tables() {
725        let source = FontRef::new(include_bytes!("../benches/fonts/Roboto-Regular.ttf")).unwrap();
726        let loads = Arc::new(AtomicUsize::new(0));
727        let load_count = loads.clone();
728        let tables = TableFunction::new(Arc::new(move |tag| {
729            load_count.fetch_add(1, Ordering::Relaxed);
730            source
731                .data_for_tag(tag)
732                .map(|data| Blob::from(data.as_bytes().to_vec()))
733        }));
734        let font = Font::new(tables, 0).unwrap();
735        let cache = LayoutCache::new(&font);
736
737        loads.store(0, Ordering::Relaxed);
738        let ot_data = OtData::new(
739            &cache.ot,
740            &[],
741            read_fonts::tables::layout::SelectedFeatureVariations::default(),
742        );
743        let aat_data = AatData::new(&cache.aat);
744
745        assert!(ot_data.gsub().is_some());
746        assert!(ot_data.gpos().is_some());
747        assert!(ot_data.has_glyph_classes());
748        assert!(aat_data.morx.is_none());
749        assert!(aat_data.mort.is_none());
750        assert!(aat_data.ankr.is_none());
751        assert!(aat_data.kern.is_none());
752        assert!(aat_data.kerx.is_none());
753        assert!(aat_data.trak.is_none());
754        assert!(aat_data.feat.is_none());
755        assert!(aat_data.ltag.is_none());
756        // The layout cache has already loaded these tables through Font.
757        assert_eq!(loads.load(Ordering::Relaxed), 0);
758    }
759
760    #[test]
761    fn charmap_and_glyph_metrics_load_on_first_query() {
762        let source = FontRef::new(include_bytes!("../benches/fonts/Roboto-Regular.ttf")).unwrap();
763        let cmap_loads = Arc::new(AtomicUsize::new(0));
764        let hmtx_loads = Arc::new(AtomicUsize::new(0));
765        let cmap_count = cmap_loads.clone();
766        let hmtx_count = hmtx_loads.clone();
767        let tables = TableFunction::new(Arc::new(move |tag| {
768            if tag == Tag::new(b"cmap") {
769                cmap_count.fetch_add(1, Ordering::Relaxed);
770            } else if tag == Tag::new(b"hmtx") {
771                hmtx_count.fetch_add(1, Ordering::Relaxed);
772            }
773            source
774                .data_for_tag(tag)
775                .map(|data| Blob::from(data.as_bytes().to_vec()))
776        }));
777        let font = Font::new(tables, 0).unwrap();
778        let shaper = ShaperFont::new(&font);
779        assert_eq!(cmap_loads.load(Ordering::Relaxed), 0);
780        assert_eq!(hmtx_loads.load(Ordering::Relaxed), 0);
781
782        assert!(shaper.default_nominal_glyph('A' as u32).is_some());
783        assert_eq!(cmap_loads.load(Ordering::Relaxed), 1);
784        assert_eq!(hmtx_loads.load(Ordering::Relaxed), 0);
785
786        let _ = shaper.default_glyph_h_advance(GlyphId::new(1));
787        assert_eq!(hmtx_loads.load(Ordering::Relaxed), 1);
788    }
789
790    #[test]
791    fn maps_legacy_arabic_symbol_fonts() {
792        let simplified = Font::new(
793            include_bytes!("../tests/fonts/in-house/SimpArabicTest.ttf").to_vec(),
794            0,
795        )
796        .unwrap();
797        assert_eq!(
798            ShaperFont::new(&simplified).default_nominal_glyph(0x0627),
799            Some(GlyphId::new(45))
800        );
801
802        let traditional = Font::new(
803            include_bytes!("../tests/fonts/in-house/TradArabicTest.ttf").to_vec(),
804            0,
805        )
806        .unwrap();
807        assert_eq!(
808            ShaperFont::new(&traditional).default_nominal_glyph(0x0627),
809            Some(GlyphId::new(65))
810        );
811    }
812
813    #[test]
814    fn extents_scale_from_corners_like_harfbuzz() {
815        // HarfBuzz scales corners in floating point, floors the bearings,
816        // ceils the far corners, and then derives width/height from them.
817        let scale = Scale::new(Some((1500, 1500)), 1000);
818        let extents = GlyphExtents {
819            x_bearing: 1,
820            y_bearing: 4,
821            width: 3,
822            height: -2,
823        };
824        let scaled = scale.scale_extents(extents);
825        assert_eq!(scaled.x_bearing, 1);
826        assert_eq!(scaled.y_bearing, 6);
827        assert_eq!(scaled.width, 5);
828        assert_eq!(scaled.height, -3);
829    }
830
831    #[test]
832    fn full_range_extents_saturate() {
833        let extents = GlyphExtents {
834            x_bearing: i32::MAX,
835            y_bearing: i32::MIN,
836            width: i32::MAX,
837            height: i32::MIN,
838        };
839
840        let scaled = Scale::default().scale_extents(extents);
841        assert_eq!(scaled.x_bearing, i32::MAX);
842        assert_eq!(scaled.y_bearing, i32::MIN);
843        assert_eq!(scaled.width, i32::MAX);
844        assert_eq!(scaled.height, i32::MIN);
845    }
846}