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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
use std::{collections::BTreeMap, sync::Arc};

use crate::{
    mutex::{Mutex, MutexGuard},
    text::{
        font::{Font, FontImpl},
        Galley, LayoutJob,
    },
    TextureAtlas,
};
use emath::NumExt as _;

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

/// How to select a sized font.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct FontId {
    /// Height in points.
    pub size: f32,

    /// What font family to use.
    pub family: FontFamily,
    // TODO(emilk): weight (bold), italics, …
}

impl Default for FontId {
    #[inline]
    fn default() -> Self {
        Self {
            size: 14.0,
            family: FontFamily::Proportional,
        }
    }
}

impl FontId {
    #[inline]
    pub const fn new(size: f32, family: FontFamily) -> Self {
        Self { size, family }
    }

    #[inline]
    pub const fn proportional(size: f32) -> Self {
        Self::new(size, FontFamily::Proportional)
    }

    #[inline]
    pub const fn monospace(size: f32) -> Self {
        Self::new(size, FontFamily::Monospace)
    }
}

#[allow(clippy::derived_hash_with_manual_eq)]
impl std::hash::Hash for FontId {
    #[inline(always)]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        let Self { size, family } = self;
        crate::f32_hash(state, *size);
        family.hash(state);
    }
}

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

/// Font of unknown size.
///
/// Which style of font: [`Monospace`][`FontFamily::Monospace`], [`Proportional`][`FontFamily::Proportional`],
/// or by user-chosen name.
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum FontFamily {
    /// A font where some characters are wider than other (e.g. 'w' is wider than 'i').
    ///
    /// Proportional fonts are easier to read and should be the preferred choice in most situations.
    #[default]
    Proportional,

    /// A font where each character is the same width (`w` is the same width as `i`).
    ///
    /// Useful for code snippets, or when you need to align numbers or text.
    Monospace,

    /// One of the names in [`FontDefinitions::families`].
    ///
    /// ```
    /// # use epaint::FontFamily;
    /// // User-chosen names:
    /// FontFamily::Name("arial".into());
    /// FontFamily::Name("serif".into());
    /// ```
    Name(Arc<str>),
}

impl std::fmt::Display for FontFamily {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Monospace => "Monospace".fmt(f),
            Self::Proportional => "Proportional".fmt(f),
            Self::Name(name) => (*name).fmt(f),
        }
    }
}

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

/// A `.ttf` or `.otf` file and a font face index.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct FontData {
    /// The content of a `.ttf` or `.otf` file.
    pub font: std::borrow::Cow<'static, [u8]>,

    /// Which font face in the file to use.
    /// When in doubt, use `0`.
    pub index: u32,

    /// Extra scale and vertical tweak to apply to all text of this font.
    pub tweak: FontTweak,
}

impl FontData {
    pub fn from_static(font: &'static [u8]) -> Self {
        Self {
            font: std::borrow::Cow::Borrowed(font),
            index: 0,
            tweak: Default::default(),
        }
    }

    pub fn from_owned(font: Vec<u8>) -> Self {
        Self {
            font: std::borrow::Cow::Owned(font),
            index: 0,
            tweak: Default::default(),
        }
    }

    pub fn tweak(self, tweak: FontTweak) -> Self {
        Self { tweak, ..self }
    }
}

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

/// Extra scale and vertical tweak to apply to all text of a certain font.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct FontTweak {
    /// Scale the font's glyphs by this much.
    /// this is only a visual effect and does not affect the text layout.
    ///
    /// Default: `1.0` (no scaling).
    pub scale: f32,

    /// Shift font's glyphs downwards by this fraction of the font size (in points).
    /// this is only a visual effect and does not affect the text layout.
    ///
    /// A positive value shifts the text downwards.
    /// A negative value shifts it upwards.
    ///
    /// Example value: `-0.2`.
    pub y_offset_factor: f32,

    /// Shift font's glyphs downwards by this amount of logical points.
    /// this is only a visual effect and does not affect the text layout.
    ///
    /// Example value: `2.0`.
    pub y_offset: f32,

    /// When using this font's metrics to layout a row,
    /// shift the entire row downwards by this fraction of the font size (in points).
    ///
    /// A positive value shifts the text downwards.
    /// A negative value shifts it upwards.
    pub baseline_offset_factor: f32,
}

impl Default for FontTweak {
    fn default() -> Self {
        Self {
            scale: 1.0,
            y_offset_factor: 0.0,
            y_offset: 0.0,
            baseline_offset_factor: -0.0333, // makes the default fonts look more centered in buttons and such
        }
    }
}

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

fn ab_glyph_font_from_font_data(name: &str, data: &FontData) -> ab_glyph::FontArc {
    match &data.font {
        std::borrow::Cow::Borrowed(bytes) => {
            ab_glyph::FontRef::try_from_slice_and_index(bytes, data.index)
                .map(ab_glyph::FontArc::from)
        }
        std::borrow::Cow::Owned(bytes) => {
            ab_glyph::FontVec::try_from_vec_and_index(bytes.clone(), data.index)
                .map(ab_glyph::FontArc::from)
        }
    }
    .unwrap_or_else(|err| panic!("Error parsing {name:?} TTF/OTF font file: {err}"))
}

/// Describes the font data and the sizes to use.
///
/// Often you would start with [`FontDefinitions::default()`] and then add/change the contents.
///
/// This is how you install your own custom fonts:
/// ```
/// # use {epaint::text::{FontDefinitions, FontFamily, FontData}};
/// # struct FakeEguiCtx {};
/// # impl FakeEguiCtx { fn set_fonts(&self, _: FontDefinitions) {} }
/// # let egui_ctx = FakeEguiCtx {};
/// let mut fonts = FontDefinitions::default();
///
/// // Install my own font (maybe supporting non-latin characters):
/// fonts.font_data.insert("my_font".to_owned(),
///    FontData::from_static(include_bytes!("../../fonts/Ubuntu-Light.ttf"))); // .ttf and .otf supported
///
/// // Put my font first (highest priority):
/// fonts.families.get_mut(&FontFamily::Proportional).unwrap()
///     .insert(0, "my_font".to_owned());
///
/// // Put my font as last fallback for monospace:
/// fonts.families.get_mut(&FontFamily::Monospace).unwrap()
///     .push("my_font".to_owned());
///
/// egui_ctx.set_fonts(fonts);
/// ```
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct FontDefinitions {
    /// List of font names and their definitions.
    ///
    /// `epaint` has built-in-default for these, but you can override them if you like.
    pub font_data: BTreeMap<String, FontData>,

    /// Which fonts (names) to use for each [`FontFamily`].
    ///
    /// The list should be a list of keys into [`Self::font_data`].
    /// When looking for a character glyph `epaint` will start with
    /// the first font and then move to the second, and so on.
    /// So the first font is the primary, and then comes a list of fallbacks in order of priority.
    pub families: BTreeMap<FontFamily, Vec<String>>,
}

impl Default for FontDefinitions {
    /// Specifies the default fonts if the feature `default_fonts` is enabled,
    /// otherwise this is the same as [`Self::empty`].
    #[cfg(not(feature = "default_fonts"))]
    fn default() -> Self {
        Self::empty()
    }

    /// Specifies the default fonts if the feature `default_fonts` is enabled,
    /// otherwise this is the same as [`Self::empty`].
    #[cfg(feature = "default_fonts")]
    fn default() -> Self {
        let mut font_data: BTreeMap<String, FontData> = BTreeMap::new();

        let mut families = BTreeMap::new();

        font_data.insert(
            "Hack".to_owned(),
            FontData::from_static(include_bytes!("../../fonts/Hack-Regular.ttf")),
        );
        font_data.insert(
            "Ubuntu-Light".to_owned(),
            FontData::from_static(include_bytes!("../../fonts/Ubuntu-Light.ttf")),
        );

        // Some good looking emojis. Use as first priority:
        font_data.insert(
            "NotoEmoji-Regular".to_owned(),
            FontData::from_static(include_bytes!("../../fonts/NotoEmoji-Regular.ttf")).tweak(
                FontTweak {
                    scale: 0.81, // make it smaller
                    ..Default::default()
                },
            ),
        );

        // Bigger emojis, and more. <http://jslegers.github.io/emoji-icon-font/>:
        font_data.insert(
            "emoji-icon-font".to_owned(),
            FontData::from_static(include_bytes!("../../fonts/emoji-icon-font.ttf")).tweak(
                FontTweak {
                    scale: 0.88, // make it smaller

                    // probably not correct, but this does make texts look better (#2724 for details)
                    y_offset_factor: 0.11, // move glyphs down to better align with common fonts
                    baseline_offset_factor: -0.11, // ...now the entire row is a bit down so shift it back
                    ..Default::default()
                },
            ),
        );

        families.insert(
            FontFamily::Monospace,
            vec![
                "Hack".to_owned(),
                "Ubuntu-Light".to_owned(), // fallback for √ etc
                "NotoEmoji-Regular".to_owned(),
                "emoji-icon-font".to_owned(),
            ],
        );
        families.insert(
            FontFamily::Proportional,
            vec![
                "Ubuntu-Light".to_owned(),
                "NotoEmoji-Regular".to_owned(),
                "emoji-icon-font".to_owned(),
            ],
        );

        Self {
            font_data,
            families,
        }
    }
}

impl FontDefinitions {
    /// No fonts.
    pub fn empty() -> Self {
        let mut families = BTreeMap::new();
        families.insert(FontFamily::Monospace, vec![]);
        families.insert(FontFamily::Proportional, vec![]);

        Self {
            font_data: Default::default(),
            families,
        }
    }

    /// List of all the builtin font names used by `epaint`.
    #[cfg(feature = "default_fonts")]
    pub fn builtin_font_names() -> &'static [&'static str] {
        &[
            "Ubuntu-Light",
            "NotoEmoji-Regular",
            "emoji-icon-font",
            "Hack",
        ]
    }

    /// List of all the builtin font names used by `epaint`.
    #[cfg(not(feature = "default_fonts"))]
    pub fn builtin_font_names() -> &'static [&'static str] {
        &[]
    }
}

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

/// The collection of fonts used by `epaint`.
///
/// Required in order to paint text. Create one and reuse. Cheap to clone.
///
/// Each [`Fonts`] comes with a font atlas textures that needs to be used when painting.
///
/// If you are using `egui`, use `egui::Context::set_fonts` and `egui::Context::fonts`.
///
/// You need to call [`Self::begin_frame`] and [`Self::font_image_delta`] once every frame.
#[derive(Clone)]
pub struct Fonts(Arc<Mutex<FontsAndCache>>);

impl Fonts {
    /// Create a new [`Fonts`] for text layout.
    /// This call is expensive, so only create one [`Fonts`] and then reuse it.
    ///
    /// * `pixels_per_point`: how many physical pixels per logical "point".
    /// * `max_texture_side`: largest supported texture size (one side).
    pub fn new(
        pixels_per_point: f32,
        max_texture_side: usize,
        definitions: FontDefinitions,
    ) -> Self {
        let fonts_and_cache = FontsAndCache {
            fonts: FontsImpl::new(pixels_per_point, max_texture_side, definitions),
            galley_cache: Default::default(),
        };
        Self(Arc::new(Mutex::new(fonts_and_cache)))
    }

    /// Call at the start of each frame with the latest known
    /// `pixels_per_point` and `max_texture_side`.
    ///
    /// Call after painting the previous frame, but before using [`Fonts`] for the new frame.
    ///
    /// This function will react to changes in `pixels_per_point` and `max_texture_side`,
    /// as well as notice when the font atlas is getting full, and handle that.
    pub fn begin_frame(&self, pixels_per_point: f32, max_texture_side: usize) {
        let mut fonts_and_cache = self.0.lock();

        let pixels_per_point_changed = fonts_and_cache.fonts.pixels_per_point != pixels_per_point;
        let max_texture_side_changed = fonts_and_cache.fonts.max_texture_side != max_texture_side;
        let font_atlas_almost_full = fonts_and_cache.fonts.atlas.lock().fill_ratio() > 0.8;
        let needs_recreate =
            pixels_per_point_changed || max_texture_side_changed || font_atlas_almost_full;

        if needs_recreate {
            let definitions = fonts_and_cache.fonts.definitions.clone();

            *fonts_and_cache = FontsAndCache {
                fonts: FontsImpl::new(pixels_per_point, max_texture_side, definitions),
                galley_cache: Default::default(),
            };
        }

        fonts_and_cache.galley_cache.flush_cache();
    }

    /// Call at the end of each frame (before painting) to get the change to the font texture since last call.
    pub fn font_image_delta(&self) -> Option<crate::ImageDelta> {
        self.lock().fonts.atlas.lock().take_delta()
    }

    /// Access the underlying [`FontsAndCache`].
    #[doc(hidden)]
    #[inline]
    pub fn lock(&self) -> MutexGuard<'_, FontsAndCache> {
        self.0.lock()
    }

    #[inline]
    pub fn pixels_per_point(&self) -> f32 {
        self.lock().fonts.pixels_per_point
    }

    #[inline]
    pub fn max_texture_side(&self) -> usize {
        self.lock().fonts.max_texture_side
    }

    /// The font atlas.
    /// Pass this to [`crate::Tessellator`].
    pub fn texture_atlas(&self) -> Arc<Mutex<TextureAtlas>> {
        self.lock().fonts.atlas.clone()
    }

    /// The full font atlas image.
    #[inline]
    pub fn image(&self) -> crate::FontImage {
        self.lock().fonts.atlas.lock().image().clone()
    }

    /// Current size of the font image.
    /// Pass this to [`crate::Tessellator`].
    pub fn font_image_size(&self) -> [usize; 2] {
        self.lock().fonts.atlas.lock().size()
    }

    /// Width of this character in points.
    #[inline]
    pub fn glyph_width(&self, font_id: &FontId, c: char) -> f32 {
        self.lock().fonts.glyph_width(font_id, c)
    }

    /// Can we display this glyph?
    #[inline]
    pub fn has_glyph(&self, font_id: &FontId, c: char) -> bool {
        self.lock().fonts.has_glyph(font_id, c)
    }

    /// Can we display all the glyphs in this text?
    pub fn has_glyphs(&self, font_id: &FontId, s: &str) -> bool {
        self.lock().fonts.has_glyphs(font_id, s)
    }

    /// Height of one row of text in points
    #[inline]
    pub fn row_height(&self, font_id: &FontId) -> f32 {
        self.lock().fonts.row_height(font_id)
    }

    /// List of all known font families.
    pub fn families(&self) -> Vec<FontFamily> {
        self.lock()
            .fonts
            .definitions
            .families
            .keys()
            .cloned()
            .collect()
    }

    /// Layout some text.
    ///
    /// This is the most advanced layout function.
    /// See also [`Self::layout`], [`Self::layout_no_wrap`] and
    /// [`Self::layout_delayed_color`].
    ///
    /// The implementation uses memoization so repeated calls are cheap.
    #[inline]
    pub fn layout_job(&self, job: LayoutJob) -> Arc<Galley> {
        self.lock().layout_job(job)
    }

    pub fn num_galleys_in_cache(&self) -> usize {
        self.lock().galley_cache.num_galleys_in_cache()
    }

    /// How full is the font atlas?
    ///
    /// This increases as new fonts and/or glyphs are used,
    /// but can also decrease in a call to [`Self::begin_frame`].
    pub fn font_atlas_fill_ratio(&self) -> f32 {
        self.lock().fonts.atlas.lock().fill_ratio()
    }

    /// Will wrap text at the given width and line break at `\n`.
    ///
    /// The implementation uses memoization so repeated calls are cheap.
    pub fn layout(
        &self,
        text: String,
        font_id: FontId,
        color: crate::Color32,
        wrap_width: f32,
    ) -> Arc<Galley> {
        let job = LayoutJob::simple(text, font_id, color, wrap_width);
        self.layout_job(job)
    }

    /// Will line break at `\n`.
    ///
    /// The implementation uses memoization so repeated calls are cheap.
    pub fn layout_no_wrap(
        &self,
        text: String,
        font_id: FontId,
        color: crate::Color32,
    ) -> Arc<Galley> {
        let job = LayoutJob::simple(text, font_id, color, f32::INFINITY);
        self.layout_job(job)
    }

    /// Like [`Self::layout`], made for when you want to pick a color for the text later.
    ///
    /// The implementation uses memoization so repeated calls are cheap.
    pub fn layout_delayed_color(
        &self,
        text: String,
        font_id: FontId,
        wrap_width: f32,
    ) -> Arc<Galley> {
        self.layout(text, font_id, crate::Color32::PLACEHOLDER, wrap_width)
    }
}

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

pub struct FontsAndCache {
    pub fonts: FontsImpl,
    galley_cache: GalleyCache,
}

impl FontsAndCache {
    fn layout_job(&mut self, job: LayoutJob) -> Arc<Galley> {
        self.galley_cache.layout(&mut self.fonts, job)
    }
}

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

#[derive(Clone, Copy, Debug, PartialEq)]
struct HashableF32(f32);

#[allow(clippy::derived_hash_with_manual_eq)]
impl std::hash::Hash for HashableF32 {
    #[inline(always)]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        crate::f32_hash(state, self.0);
    }
}

impl Eq for HashableF32 {}

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

/// The collection of fonts used by `epaint`.
///
/// Required in order to paint text.
pub struct FontsImpl {
    pixels_per_point: f32,
    max_texture_side: usize,
    definitions: FontDefinitions,
    atlas: Arc<Mutex<TextureAtlas>>,
    font_impl_cache: FontImplCache,
    sized_family: ahash::HashMap<(HashableF32, FontFamily), Font>,
}

impl FontsImpl {
    /// Create a new [`FontsImpl`] for text layout.
    /// This call is expensive, so only create one [`FontsImpl`] and then reuse it.
    pub fn new(
        pixels_per_point: f32,
        max_texture_side: usize,
        definitions: FontDefinitions,
    ) -> Self {
        assert!(
            0.0 < pixels_per_point && pixels_per_point < 100.0,
            "pixels_per_point out of range: {pixels_per_point}"
        );

        let texture_width = max_texture_side.at_most(8 * 1024);
        let initial_height = 32; // Keep initial font atlas small, so it is fast to upload to GPU. This will expand as needed anyways.
        let atlas = TextureAtlas::new([texture_width, initial_height]);

        let atlas = Arc::new(Mutex::new(atlas));

        let font_impl_cache =
            FontImplCache::new(atlas.clone(), pixels_per_point, &definitions.font_data);

        Self {
            pixels_per_point,
            max_texture_side,
            definitions,
            atlas,
            font_impl_cache,
            sized_family: Default::default(),
        }
    }

    #[inline(always)]
    pub fn pixels_per_point(&self) -> f32 {
        self.pixels_per_point
    }

    #[inline]
    pub fn definitions(&self) -> &FontDefinitions {
        &self.definitions
    }

    /// Get the right font implementation from size and [`FontFamily`].
    pub fn font(&mut self, font_id: &FontId) -> &mut Font {
        let FontId { size, family } = font_id;

        self.sized_family
            .entry((HashableF32(*size), family.clone()))
            .or_insert_with(|| {
                let fonts = &self.definitions.families.get(family);
                let fonts = fonts
                    .unwrap_or_else(|| panic!("FontFamily::{family:?} is not bound to any fonts"));

                let fonts: Vec<Arc<FontImpl>> = fonts
                    .iter()
                    .map(|font_name| self.font_impl_cache.font_impl(*size, font_name))
                    .collect();

                Font::new(fonts)
            })
    }

    /// Width of this character in points.
    fn glyph_width(&mut self, font_id: &FontId, c: char) -> f32 {
        self.font(font_id).glyph_width(c)
    }

    /// Can we display this glyph?
    pub fn has_glyph(&mut self, font_id: &FontId, c: char) -> bool {
        self.font(font_id).has_glyph(c)
    }

    /// Can we display all the glyphs in this text?
    pub fn has_glyphs(&mut self, font_id: &FontId, s: &str) -> bool {
        self.font(font_id).has_glyphs(s)
    }

    /// Height of one row of text in points.
    fn row_height(&mut self, font_id: &FontId) -> f32 {
        self.font(font_id).row_height()
    }
}

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

struct CachedGalley {
    /// When it was last used
    last_used: u32,
    galley: Arc<Galley>,
}

#[derive(Default)]
struct GalleyCache {
    /// Frame counter used to do garbage collection on the cache
    generation: u32,
    cache: nohash_hasher::IntMap<u64, CachedGalley>,
}

impl GalleyCache {
    fn layout(&mut self, fonts: &mut FontsImpl, job: LayoutJob) -> Arc<Galley> {
        let hash = crate::util::hash(&job); // TODO(emilk): even faster hasher?

        match self.cache.entry(hash) {
            std::collections::hash_map::Entry::Occupied(entry) => {
                let cached = entry.into_mut();
                cached.last_used = self.generation;
                cached.galley.clone()
            }
            std::collections::hash_map::Entry::Vacant(entry) => {
                let galley = super::layout(fonts, job.into());
                let galley = Arc::new(galley);
                entry.insert(CachedGalley {
                    last_used: self.generation,
                    galley: galley.clone(),
                });
                galley
            }
        }
    }

    pub fn num_galleys_in_cache(&self) -> usize {
        self.cache.len()
    }

    /// Must be called once per frame to clear the [`Galley`] cache.
    pub fn flush_cache(&mut self) {
        let current_generation = self.generation;
        self.cache.retain(|_key, cached| {
            cached.last_used == current_generation // only keep those that were used this frame
        });
        self.generation = self.generation.wrapping_add(1);
    }
}

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

struct FontImplCache {
    atlas: Arc<Mutex<TextureAtlas>>,
    pixels_per_point: f32,
    ab_glyph_fonts: BTreeMap<String, (FontTweak, ab_glyph::FontArc)>,

    /// Map font pixel sizes and names to the cached [`FontImpl`].
    cache: ahash::HashMap<(u32, String), Arc<FontImpl>>,
}

impl FontImplCache {
    pub fn new(
        atlas: Arc<Mutex<TextureAtlas>>,
        pixels_per_point: f32,
        font_data: &BTreeMap<String, FontData>,
    ) -> Self {
        let ab_glyph_fonts = font_data
            .iter()
            .map(|(name, font_data)| {
                let tweak = font_data.tweak;
                let ab_glyph = ab_glyph_font_from_font_data(name, font_data);
                (name.clone(), (tweak, ab_glyph))
            })
            .collect();

        Self {
            atlas,
            pixels_per_point,
            ab_glyph_fonts,
            cache: Default::default(),
        }
    }

    pub fn font_impl(&mut self, scale_in_points: f32, font_name: &str) -> Arc<FontImpl> {
        use ab_glyph::Font as _;

        let (tweak, ab_glyph_font) = self
            .ab_glyph_fonts
            .get(font_name)
            .unwrap_or_else(|| panic!("No font data found for {font_name:?}"))
            .clone();

        let scale_in_pixels = self.pixels_per_point * scale_in_points;

        // Scale the font properly (see https://github.com/emilk/egui/issues/2068).
        let units_per_em = ab_glyph_font.units_per_em().unwrap_or_else(|| {
            panic!("The font unit size of {font_name:?} exceeds the expected range (16..=16384)")
        });
        let font_scaling = ab_glyph_font.height_unscaled() / units_per_em;
        let scale_in_pixels = scale_in_pixels * font_scaling;

        self.cache
            .entry((
                (scale_in_pixels * tweak.scale).round() as u32,
                font_name.to_owned(),
            ))
            .or_insert_with(|| {
                Arc::new(FontImpl::new(
                    self.atlas.clone(),
                    self.pixels_per_point,
                    font_name.to_owned(),
                    ab_glyph_font,
                    scale_in_pixels,
                    tweak,
                ))
            })
            .clone()
    }
}