epaint 0.37.0

Minimal 2D graphics library for GUI work
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
#![expect(clippy::mem_forget)]

#[cfg(feature = "color_fonts")]
use alloc::sync::Arc;

use ahash::HashMap;
use ecolor::Color32;
use emath::{GuiRounding as _, OrderedFloat, vec2};
use self_cell::self_cell;
use skrifa::{GlyphId, MetadataProvider as _};
use vello_cpu::{color, kurbo};

use crate::{
    ColorImage, TextOptions,
    text::{
        FontTweak, GlyphBitmap, VariationCoords,
        font_data::Blob,
        glyph_atlas::SubpixelBin,
        styled_metrics::{LocationHash, StyledMetrics},
        unicode::invisible_char,
    },
};

/// A glyph id and its advance, as resolved from a `char` in one [`FontFace`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct GlyphInfo {
    /// Doesn't need to be unique.
    ///
    /// Is `None` for a special "invisible" glyph.
    pub(crate) id: Option<GlyphId>,

    /// In [`skrifa`]s "unscaled" coordinate system.
    pub advance_width_unscaled: OrderedFloat<f32>,
}

impl GlyphInfo {
    /// A valid, but invisible, glyph of zero-width.
    pub const INVISIBLE: Self = Self {
        id: None,
        advance_width_unscaled: OrderedFloat(0.0),
    };
}

/// Result of resolving a `char` to a [`GlyphId`] within a single [`FontFace`].
///
/// Location-independent: only depends on the font's charmap and `FontTweak`,
/// not on variable-font variation coordinates.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum GlyphIdResolution {
    /// A real, visible glyph.
    Glyph(GlyphId),

    /// A valid char, but rendered as zero-width (control chars, joiners, …).
    Invisible,
}

// ----------------------------------------------------------------------------

/// The parsed `skrifa` views into a font file, borrowing from the file's [`Blob`].
struct DependentFontData<'a> {
    skrifa: skrifa::FontRef<'a>,

    /// Index of this face in the font file (a font collection, e.g. `.ttc`, holds several).
    #[cfg(feature = "color_fonts")]
    index: u32,

    /// Does the font have a `COLR`, `sbix`, `CBDT`, or `EBDT` table?
    #[cfg(feature = "color_fonts")]
    has_color_glyphs: bool,

    charmap: skrifa::charmap::Charmap<'a>,
    outline_glyphs: skrifa::outline::OutlineGlyphCollection<'a>,
    metrics: skrifa::metrics::Metrics,
    hinting_instance: Option<skrifa::outline::HintingInstance>,
}

self_cell! {
    /// A font file together with the parsed [`DependentFontData`] that borrows from it.
    struct FontCell {
        owner: Blob,

        #[covariant]
        dependent: DependentFontData,
    }
}

impl FontCell {
    fn px_scale_factor(&self, scale: f32) -> f32 {
        let units_per_em = self.borrow_dependent().metrics.units_per_em as f32;
        scale / units_per_em
    }

    /// Render a glyph to a bitmap: a color glyph if the font has one, else the outline as coverage.
    ///
    /// Returns `None` if the glyph has neither (e.g. a space).
    fn rasterize_glyph(
        &mut self,
        metrics: &StyledMetrics,
        glyph_id: GlyphId,
        bin: SubpixelBin,
        hinting_target: skrifa::outline::Target,
    ) -> Option<GlyphBitmap> {
        let location: skrifa::instance::LocationRef<'_> = (&metrics.location).into();

        // Color emoji fonts often have empty outlines next to their bitmap or `COLR` glyphs,
        // so try those first:
        core::cfg_select! {
            feature = "color_fonts" => {
                if let Some(bitmap) = self.rasterize_color_glyph(metrics, glyph_id, location) {
                    return Some(bitmap);
                }
            }
            _ => {}
        }

        let mut path = kurbo::BezPath::new();
        let mut pen = VelloPen {
            path: &mut path,
            x_offset: bin.as_float() as f64,
        };

        self.with_dependent_mut(|_, font_data| {
            let outline = font_data.outline_glyphs.get(glyph_id)?;

            if let Some(hinting_instance) = &mut font_data.hinting_instance {
                let size = skrifa::instance::Size::new(metrics.scale);
                if hinting_instance.size() != size
                    || hinting_instance.location().coords() != location.coords()
                    || hinting_instance.target() != hinting_target
                {
                    hinting_instance
                        .reconfigure(&font_data.outline_glyphs, size, location, hinting_target)
                        .ok()?;
                }
                let draw_settings = skrifa::outline::DrawSettings::hinted(hinting_instance, false);
                outline.draw(draw_settings, &mut pen).ok()?;
            } else {
                let draw_settings = skrifa::outline::DrawSettings::unhinted(
                    skrifa::instance::Size::new(metrics.scale),
                    location,
                );
                outline.draw(draw_settings, &mut pen).ok()?;
            }

            Some(())
        })?;

        let bounds = path.control_box().expand();
        let width = bounds.width() as u16;
        let height = bounds.height() as u16;
        if width == 0 || height == 0 {
            return None;
        }

        let mut ctx = vello_cpu::RenderContext::new(width, height);
        ctx.set_transform(kurbo::Affine::translate((-bounds.x0, -bounds.y0)));
        ctx.set_paint(color::OpaqueColor::<color::Srgb>::WHITE);
        ctx.fill_path(&path);
        let mut dest = vello_cpu::Pixmap::new(width, height);
        let mut resources = vello_cpu::Resources::new();
        ctx.render(&mut dest, &mut resources);

        let pixels = dest
            .data_as_u8_slice()
            .chunks_exact(4)
            .map(|px| Color32::from_rgba_premultiplied(px[0], px[1], px[2], px[3]))
            .collect();
        let image = ColorImage::new([width as usize, height as usize], pixels);

        Some(GlyphBitmap {
            image,
            offset_px: vec2(bounds.x0 as f32, bounds.y0 as f32),
            is_color: false,
        })
    }

    /// Does this glyph have a color bitmap (`sbix`, `CBDT`) or a `COLR` paint graph?
    #[cfg(feature = "color_fonts")]
    fn has_color_glyph(&self, glyph_id: GlyphId, size: skrifa::instance::Size) -> bool {
        let font_data = self.borrow_dependent();
        font_data.has_color_glyphs
            && (font_data.skrifa.color_glyphs().get(glyph_id).is_some()
                || font_data
                    .skrifa
                    .bitmap_strikes()
                    .glyph_for_size(size, glyph_id)
                    .is_some())
    }

    /// Rasterize a bitmap (`sbix`, `CBDT`) or `COLR` glyph, e.g. a color emoji.
    ///
    /// Returns `None` if the glyph has neither.
    ///
    /// Never sub-pixel positioned: [`crate::text::glyph_atlas::GlyphAtlas::allocate_outline`]
    /// bins color glyphs to whole pixels.
    #[cfg(feature = "color_fonts")]
    fn rasterize_color_glyph(
        &self,
        metrics: &StyledMetrics,
        glyph_id: GlyphId,
        location: skrifa::instance::LocationRef<'_>,
    ) -> Option<GlyphBitmap> {
        use vello_cpu::peniko;

        let font_data = self.borrow_dependent();
        let font_size_px = metrics.scale;
        let size = skrifa::instance::Size::new(font_size_px);

        if !self.has_color_glyph(glyph_id, size) || font_size_px == 0.0 || !font_size_px.is_finite()
        {
            return None;
        }

        // We don't know the bounds of the glyph up front, so we render it onto a
        // canvas with room for one em on each side of the em box, then crop.
        let canvas_size = (3.0 * font_size_px)
            .ceil()
            .clamp(1.0, crate::text::MAX_GLYPH_SIZE as f32) as u16;
        let origin_x = font_size_px as f64;
        let origin_y = 2.0 * font_size_px as f64;

        let font = peniko::FontData::new(
            peniko::Blob::new(Arc::clone(self.borrow_owner())),
            font_data.index,
        );
        let coords: Vec<i16> = location.coords().iter().map(|c| c.to_bits()).collect();

        let mut ctx = vello_cpu::RenderContext::new(canvas_size, canvas_size);
        let mut resources = vello_cpu::Resources::new();
        ctx.set_paint(color::OpaqueColor::<color::Srgb>::WHITE);
        ctx.glyph_run(&mut resources, &font)
            .font_size(font_size_px)
            .hint(false)
            .normalized_coords(&coords)
            .fill_glyphs(core::iter::once(vello_cpu::Glyph {
                id: glyph_id.to_u32(),
                x: origin_x as f32,
                y: origin_y as f32,
            }));
        let mut pixmap = vello_cpu::Pixmap::new(canvas_size, canvas_size);
        ctx.render(&mut pixmap, &mut resources);

        let canvas_size = canvas_size as usize;
        let pixels = pixmap.data_as_u8_slice();
        let alpha_at = |x: usize, y: usize| pixels[4 * (y * canvas_size + x) + 3];

        // Crop to the painted pixels:
        let mut min = [canvas_size, canvas_size];
        let mut max = [0, 0];
        for y in 0..canvas_size {
            for x in 0..canvas_size {
                if alpha_at(x, y) != 0 {
                    min = [min[0].min(x), min[1].min(y)];
                    max = [max[0].max(x + 1), max[1].max(y + 1)];
                }
            }
        }
        if max[0] <= min[0] || max[1] <= min[1] {
            return None; // Nothing painted
        }
        let width = max[0] - min[0];
        let height = max[1] - min[1];

        let cropped: Vec<Color32> = (min[1]..max[1])
            .flat_map(|y| (min[0]..max[0]).map(move |x| (x, y)))
            .map(|(x, y)| {
                let i = 4 * (y * canvas_size + x);
                // `vello_cpu::Pixmap` holds premultiplied RGBA8:
                Color32::from_rgba_premultiplied(
                    pixels[i],
                    pixels[i + 1],
                    pixels[i + 2],
                    pixels[i + 3],
                )
            })
            .collect();

        Some(GlyphBitmap {
            image: ColorImage::new([width, height], cropped),
            offset_px: vec2(
                min[0] as f32 - origin_x as f32,
                min[1] as f32 - origin_y as f32,
            ),
            is_color: true,
        })
    }
}

/// Collects a `skrifa` glyph outline into a `kurbo` path, flipping Y to point down.
struct VelloPen<'a> {
    path: &'a mut kurbo::BezPath,
    x_offset: f64,
}

impl skrifa::outline::OutlinePen for VelloPen<'_> {
    fn move_to(&mut self, x: f32, y: f32) {
        self.path.move_to((x as f64 + self.x_offset, -y as f64));
    }

    fn line_to(&mut self, x: f32, y: f32) {
        self.path.line_to((x as f64 + self.x_offset, -y as f64));
    }

    fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
        self.path.quad_to(
            (cx0 as f64 + self.x_offset, -cy0 as f64),
            (x as f64 + self.x_offset, -y as f64),
        );
    }

    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
        self.path.curve_to(
            (cx0 as f64 + self.x_offset, -cy0 as f64),
            (cx1 as f64 + self.x_offset, -cy1 as f64),
            (x as f64 + self.x_offset, -y as f64),
        );
    }

    fn close(&mut self) {
        self.path.close_path();
    }
}

/// A specific font face.
/// The interface uses points as the unit for everything.
pub struct FontFace {
    name: String,
    font: FontCell,
    tweak: FontTweak,
    subpixel_binning: bool,

    /// Cached `harfrust` shaper data (parsed GSUB/GPOS tables).
    /// `ShaperData` is `Copy` — lives outside the `self_cell`.
    shaper_data: harfrust::ShaperData,

    /// Location-independent: `char → GlyphId | Invisible`.
    ///
    /// Only depends on the font's charmap + `FontTweak`. A miss means the char
    /// is not in this face's repertoire and the fallback chain should be tried.
    glyph_id_cache: HashMap<char, GlyphIdResolution>,

    /// Location-dependent: `(char, LocationHash) → unscaled advance width`.
    ///
    /// Variable fonts can vary advance widths per axis (HVAR table), so this
    /// must be re-keyed per resolved [`skrifa::instance::Location`].
    advance_width_cache: HashMap<(char, LocationHash), OrderedFloat<f32>>,
}

impl FontFace {
    pub fn new(
        options: TextOptions,
        name: String,
        font_data: Blob,
        index: u32,
        tweak: FontTweak,
    ) -> Result<Self, Box<dyn core::error::Error>> {
        let font = FontCell::try_new(font_data, |font_data| {
            let skrifa_font =
                skrifa::FontRef::from_index(AsRef::<[u8]>::as_ref(font_data.as_ref()), index)?;

            let charmap = skrifa_font.charmap();
            let glyphs = skrifa_font.outline_glyphs();

            // Note: We use default location here during initialization because
            // the actual weight will be applied via the stored location during rendering.
            // The metrics won't be significantly different at this unscaled size.
            // TODO(emilk): heed location for vertical metrics too (HVAR/MVAR).
            let metrics = skrifa_font.metrics(
                skrifa::instance::Size::unscaled(),
                skrifa::instance::LocationRef::default(),
            );

            let hinting_enabled = tweak.hinting.unwrap_or(options.font_hinting);
            let hinting_instance = hinting_enabled
                .then(|| {
                    // It doesn't really matter what we put here for options. Since the size is `unscaled()`, we will
                    // always reconfigure this hinting instance with the real options when rendering for the first time.
                    skrifa::outline::HintingInstance::new(
                        &glyphs,
                        skrifa::instance::Size::unscaled(),
                        skrifa::instance::LocationRef::default(),
                        skrifa::outline::Target::default(),
                    )
                    .ok()
                })
                .flatten();

            #[cfg(feature = "color_fonts")]
            let has_color_glyphs = {
                use skrifa::raw::TableProvider as _;
                skrifa_font.colr().is_ok()
                    || skrifa_font.sbix().is_ok()
                    || skrifa_font.cbdt().is_ok()
                    || skrifa_font.ebdt().is_ok()
            };

            Ok::<DependentFontData<'_>, Box<dyn core::error::Error>>(DependentFontData {
                skrifa: skrifa_font,
                #[cfg(feature = "color_fonts")]
                index,
                #[cfg(feature = "color_fonts")]
                has_color_glyphs,
                charmap,
                outline_glyphs: glyphs,
                metrics,
                hinting_instance,
            })
        })?;

        let shaper_data = harfrust::ShaperData::new(&font.borrow_dependent().skrifa);

        let subpixel_binning = tweak.subpixel_binning.unwrap_or(options.subpixel_binning);

        Ok(Self {
            name,
            font,
            tweak,
            subpixel_binning,
            shaper_data,
            glyph_id_cache: Default::default(),
            advance_width_cache: Default::default(),
        })
    }

    /// Apply new [`TextOptions`]: hinting on/off and sub-pixel binning.
    ///
    /// Anything cached about glyph ids and advances stays valid, since neither affects them.
    pub(crate) fn set_options(&mut self, options: TextOptions) {
        let Self {
            font,
            tweak,
            subpixel_binning,
            ..
        } = self;
        *subpixel_binning = tweak.subpixel_binning.unwrap_or(options.subpixel_binning);
        let hinting_enabled = tweak.hinting.unwrap_or(options.font_hinting);
        font.with_dependent_mut(|_, font_data| {
            font_data.hinting_instance = hinting_enabled
                .then(|| {
                    skrifa::outline::HintingInstance::new(
                        &font_data.outline_glyphs,
                        skrifa::instance::Size::unscaled(),
                        skrifa::instance::LocationRef::default(),
                        skrifa::outline::Target::default(),
                    )
                    .ok()
                })
                .flatten();
        });
    }

    /// Code points that will always be replaced by the `.notdef` glyph ("tofu").
    ///
    /// See also [`invisible_char`].
    fn ignore_character(&self, chr: char) -> bool {
        use crate::text::FontDefinitions;

        if !FontDefinitions::builtin_font_names().contains(&self.name.as_str()) {
            return false;
        }

        matches!(
            chr,
            // Strip out a religious symbol with secondary nefarious interpretation:
            '\u{534d}' | '\u{5350}' |

            // Ignore ubuntu-specific stuff in `Ubuntu-Light.ttf`:
            '\u{E0FF}' | '\u{EFFD}' | '\u{F0FF}' | '\u{F200}'
        )
    }

    /// The name the font was installed under, i.e. its key in `FontDefinitions::font_data`.
    #[inline]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Scale factor from the font's unscaled units to `scale` (points or pixels).
    #[inline]
    pub(crate) fn px_scale_factor(&self, scale: f32) -> f32 {
        self.font.px_scale_factor(scale)
    }

    /// An un-ordered iterator over all supported characters.
    pub fn characters(&self) -> impl Iterator<Item = char> + '_ {
        self.font
            .borrow_dependent()
            .charmap
            .mappings()
            .filter_map(|(chr, _)| char::from_u32(chr).filter(|c| !self.ignore_character(*c)))
    }

    /// Resolve a `char` to a [`GlyphId`] within this face.
    ///
    /// Location-independent. Returns `None` when this face cannot represent
    /// the char (the caller should try the fallback chain).
    ///
    /// `\t` and thin spaces share `' '`s glyph id (they just have a custom advance).
    pub(super) fn glyph_id_resolution(&mut self, c: char) -> Option<GlyphIdResolution> {
        if let Some(resolution) = self.glyph_id_cache.get(&c) {
            return Some(*resolution);
        }

        if self.ignore_character(c) {
            return None; // these will result in the `.notdef` glyph ("tofu") when rendering
        }

        let resolution = if c == '\t' || c == '\u{2009}' || c == '\u{202F}' {
            // `\t` and thin spaces are rendered as a space glyph with a custom advance.
            self.glyph_id_resolution(' ')?
        } else if invisible_char(c) {
            GlyphIdResolution::Invisible
        } else {
            let glyph_id = self
                .font
                .borrow_dependent()
                .charmap
                .map(c)
                .filter(|id| *id != GlyphId::NOTDEF)?;
            GlyphIdResolution::Glyph(glyph_id)
        };

        self.glyph_id_cache.insert(c, resolution);
        Some(resolution)
    }

    /// Unscaled advance width for `c` at the given variation location.
    ///
    /// Location-dependent (variable fonts can vary advances via HVAR).
    /// Cached per `(char, LocationHash)`.
    fn advance_width_unscaled(&mut self, c: char, metrics: &StyledMetrics) -> f32 {
        let cache_key = (c, metrics.location_hash);
        if let Some(advance) = self.advance_width_cache.get(&cache_key) {
            return advance.0;
        }

        let advance = match c {
            '\t' => self.tweak.tab_size * self.advance_width_unscaled(' ', metrics),
            '\u{2009}' | '\u{202F}' => {
                // Thin space (U+2009) and narrow no-break space (U+202F),
                // often used as thousands separator.
                self.tweak.thin_space_width * self.advance_width_unscaled(' ', metrics)
            }
            _ => {
                let Some(GlyphIdResolution::Glyph(glyph_id)) = self.glyph_id_resolution(c) else {
                    return 0.0;
                };
                let font_data = self.font.borrow_dependent();
                let glyph_metrics = font_data
                    .skrifa
                    .glyph_metrics(skrifa::instance::Size::unscaled(), &metrics.location);
                glyph_metrics.advance_width(glyph_id).unwrap_or_default()
            }
        };

        self.advance_width_cache.insert(cache_key, advance.into());
        advance
    }

    /// `\n` will result in `None`.
    ///
    /// Caller must pass [`StyledMetrics`] resolved against *this* face so that
    /// variable-font advance widths are looked up at the correct location.
    pub(super) fn glyph_info(&mut self, c: char, metrics: &StyledMetrics) -> Option<GlyphInfo> {
        let resolution = self.glyph_id_resolution(c)?;
        let glyph_info = match resolution {
            GlyphIdResolution::Invisible => GlyphInfo::INVISIBLE,
            GlyphIdResolution::Glyph(glyph_id) => GlyphInfo {
                id: Some(glyph_id),
                advance_width_unscaled: self.advance_width_unscaled(c, metrics).into(),
            },
        };
        Some(glyph_info)
    }

    /// The `.notdef` glyph ("tofu"), rendered in place of chars that no face has.
    pub(super) fn notdef_glyph_info(&self, metrics: &StyledMetrics) -> GlyphInfo {
        let font_data = self.font.borrow_dependent();
        let glyph_metrics = font_data
            .skrifa
            .glyph_metrics(skrifa::instance::Size::unscaled(), &metrics.location);
        GlyphInfo {
            id: Some(GlyphId::NOTDEF),
            advance_width_unscaled: glyph_metrics
                .advance_width(GlyphId::NOTDEF)
                .unwrap_or_default()
                .into(),
        }
    }

    #[inline(always)]
    pub fn styled_metrics(
        &self,
        pixels_per_point: f32,
        font_size: f32,
        coords: &VariationCoords,
    ) -> StyledMetrics {
        let pt_scale_factor = self.font.px_scale_factor(font_size * self.tweak.scale);
        let font_data = self.font.borrow_dependent();
        let ascent = (font_data.metrics.ascent * pt_scale_factor).round_ui();
        let descent = (font_data.metrics.descent * pt_scale_factor).round_ui();
        let line_gap = (font_data.metrics.leading * pt_scale_factor).round_ui();

        let scale = font_size * self.tweak.scale * pixels_per_point;
        let px_scale_factor = self.font.px_scale_factor(scale);

        let y_offset_in_points = ((font_size * self.tweak.scale * self.tweak.y_offset_factor)
            + self.tweak.y_offset)
            .round_ui();

        let axes = font_data.skrifa.axes();
        // Override the default coordinates with ones specified via FontTweak, then the ones specified directly via the
        // argument (probably from TextFormat).
        let settings = core::iter::chain(self.tweak.coords.as_ref(), coords.as_ref());
        let location = axes.location(settings);
        let location_hash = LocationHash::new(&location);

        StyledMetrics {
            pixels_per_point,
            px_scale_factor,
            scale,
            y_offset_in_points,
            ascent,
            row_height: ascent - descent + line_gap,
            location,
            location_hash,
        }
    }

    pub(crate) fn skrifa_font_ref(&self) -> &skrifa::FontRef<'_> {
        &self.font.borrow_dependent().skrifa
    }

    pub(crate) fn tweak(&self) -> &FontTweak {
        &self.tweak
    }

    pub(crate) fn shaper_data(&self) -> &harfrust::ShaperData {
        &self.shaper_data
    }

    /// Whether to render this face at up to four sub-pixel offsets.
    #[inline]
    pub(crate) fn subpixel_binning(&self) -> bool {
        self.subpixel_binning
    }

    /// Will this glyph be rendered as a color bitmap or `COLR` glyph, e.g. a color emoji?
    pub(crate) fn is_color_glyph(&self, metrics: &StyledMetrics, glyph_id: GlyphId) -> bool {
        core::cfg_select! {
            feature = "color_fonts" => {
                self.font
                    .has_color_glyph(glyph_id, skrifa::instance::Size::new(metrics.scale))
            }
            _ => {
                let _ = (self, metrics, glyph_id);
                false
            }
        }
    }

    /// Render a glyph to a bitmap: a color glyph if the font has one, else the outline as coverage.
    ///
    /// Not cached: see [`crate::text::glyph_atlas::GlyphAtlas::allocate_outline`].
    pub(crate) fn rasterize_glyph(
        &mut self,
        metrics: &StyledMetrics,
        glyph_id: GlyphId,
        bin: SubpixelBin,
    ) -> Option<GlyphBitmap> {
        let hinting_target = self.tweak.hinting_target.into();
        self.font
            .rasterize_glyph(metrics, glyph_id, bin, hinting_target)
    }
}

/// Positioning info for a single glyph, ready for atlas allocation.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ShapedGlyph {
    pub glyph_id: GlyphId,

    /// Horizontal position of the glyph origin, in physical pixels.
    pub h_pos: f32,

    /// CJK glyphs skip subpixel positioning to save atlas space.
    pub is_cjk: bool,
}