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
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
use alloc::{collections::BTreeMap, sync::Arc};

use crate::{
    Color32, ColorImage, TextureAtlas,
    text::{
        FontDefinitions, FontFamily, FontId, FontInsert, FontPriority, FontProvider, Galley,
        GlyphBitmap, GlyphRasterizer, GlyphRasterizerRequest, LayoutJob, RasterizedGlyph,
        TextOptions, VariationCoords,
        face_store::{FaceStore, FontFaceKey},
        family::{Family, FamilyKey},
        font_face::{FontFace, GlyphInfo, ShapedGlyph},
        font_provider::FontProviders,
        galley_cache::GalleyCache,
        glyph_atlas::{GlyphAllocation, GlyphAtlas, OutlineGlyph, RasterGlyphAllocation},
        styled_metrics::StyledMetrics,
        text_layout::layout,
    },
};

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

/// Maximum width or height of a glyph rasterized into the font atlas.
///
/// Must not exceed the minimum width of the [`TextureAtlas`] (1024).
pub const MAX_GLYPH_SIZE: usize = 1024;

/// Identifies an independently rendered viewport's text-layout cache.
///
/// [`Fonts`] shares font faces and its glyph atlas between all viewports, but each
/// viewport needs a separate layout cache. A galley cache evicts layouts that
/// were not used in its immediately preceding pass. If independently scheduled
/// viewports shared that eviction generation, each viewport pass would make the
/// other viewports' layouts look unused and evict them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ViewportKey(u64);

impl ViewportKey {
    /// Create a stable cache key for an independently rendered viewport.
    #[inline]
    pub const fn new(value: u64) -> Self {
        Self(value)
    }
}

#[derive(Default)]
struct ViewportGalleyCache {
    cache: GalleyCache,
    used_since_begin_pass: bool,
}

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

/// What to do with a character that nothing can draw: no installed font has it,
/// no [`FontProvider`] finds a font for it, and no [`GlyphRasterizer`] handles it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub enum MissingGlyphPolicy {
    /// Draw a box ("tofu"): the `.notdef` glyph of the family's primary font,
    /// or a synthetic box if the family has no font at all.
    #[default]
    Tofu,

    /// Panic, naming the character and the font family.
    ///
    /// For tests: a missing glyph is usually a bug, and tofu in a snapshot is easy to miss.
    /// Control characters (e.g. `\t`, `\n`) never panic: fonts have no glyphs for them.
    Panic,
}

/// 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_pass`] once per viewport pass, and
/// [`Self::font_image_delta`] once every frame.
pub struct Fonts {
    fonts: FontsImpl,
    // `GalleyCache::flush_cache` assumes consecutive calls are consecutive passes
    // of the same UI. Viewports are independently scheduled, so sharing one cache
    // would advance its eviction generation once per *viewport* pass. Alternating
    // root/child passes would then continuously evict one another's working sets.
    // Keep only the layout caches separate; font data and the glyph atlas stay shared.
    galley_caches: BTreeMap<ViewportKey, ViewportGalleyCache>,
}

impl Fonts {
    /// Create a new [`Fonts`] for text layout.
    ///
    /// This call is expensive, so only create one [`Fonts`] and then reuse it.
    pub fn new(options: TextOptions, definitions: FontDefinitions) -> Self {
        Self {
            fonts: FontsImpl::new(options, definitions),
            galley_caches: Default::default(),
        }
    }

    /// Also use this glyph rasterizer, e.g. the browser on web, or for custom glyphs.
    ///
    /// See [`GlyphRasterizer`].
    #[inline]
    pub fn with_glyph_rasterizer(mut self, glyph_rasterizer: GlyphRasterizer) -> Self {
        self.add_glyph_rasterizer(glyph_rasterizer);
        self
    }

    /// Also use this glyph rasterizer, e.g. the browser on web, or for custom glyphs.
    ///
    /// Adding a rasterizer whose [`GlyphRasterizer::key`] is already installed is a no-op,
    /// so this is safe to call every frame.
    ///
    /// Returns `true` if it was added.
    ///
    /// See [`GlyphRasterizer`].
    pub fn add_glyph_rasterizer(&mut self, glyph_rasterizer: GlyphRasterizer) -> bool {
        let changed = self.fonts.add_glyph_rasterizer(glyph_rasterizer);
        if changed {
            self.galley_caches.clear();
        }
        changed
    }

    /// Replace all [`GlyphRasterizer`]s.
    ///
    /// Pass an empty list to only use the installed fonts.
    pub fn set_glyph_rasterizers(&mut self, glyph_rasterizers: Vec<GlyphRasterizer>) {
        self.fonts.set_glyph_rasterizers(glyph_rasterizers);
        self.galley_caches.clear();
    }

    /// Ask these for fonts, after the [`FontDefinitions`].
    ///
    /// The providers are asked in order, and the first font found is used.
    #[inline]
    pub fn with_font_providers(mut self, font_providers: Vec<Arc<dyn FontProvider>>) -> Self {
        self.fonts.set_font_providers(font_providers);
        self
    }

    /// The fonts discovered by the [`FontProvider`]s so far, in the order they were found.
    ///
    /// These are not part of [`Self::definitions`].
    pub fn discovered_fonts(&self) -> &[FontInsert] {
        self.fonts.discovered_fonts()
    }

    /// What to do with characters that nothing can draw. See [`MissingGlyphPolicy`].
    #[inline]
    pub fn with_missing_glyph_policy(mut self, policy: MissingGlyphPolicy) -> Self {
        self.set_missing_glyph_policy(policy);
        self
    }

    /// What to do with characters that nothing can draw. See [`MissingGlyphPolicy`].
    pub fn set_missing_glyph_policy(&mut self, policy: MissingGlyphPolicy) {
        if self.fonts.missing_glyph_policy != policy {
            self.fonts.missing_glyph_policy = policy;
            self.galley_caches.clear(); // Cached galleys may contain tofu.
        }
    }

    /// See [`MissingGlyphPolicy`].
    #[inline]
    pub fn missing_glyph_policy(&self) -> MissingGlyphPolicy {
        self.fonts.missing_glyph_policy
    }

    /// Call at the start of each viewport pass with the latest known [`TextOptions`].
    ///
    /// Call after painting the previous frame, but before using [`Fonts`] for the new frame.
    ///
    /// This function will react to changes in [`TextOptions`],
    /// as well as notice when the font atlas is getting full, and handle that.
    pub fn begin_pass(&mut self, options: TextOptions, viewport_key: ViewportKey) {
        if self.fonts.options() != &options {
            self.fonts.set_options(options);
            self.galley_caches.clear(); // Galleys point into the old atlas.
        } else if 0.8 < self.fonts.glyphs.fill_ratio() {
            // The parsed faces are still fine; only the bitmaps need to go.
            self.fonts.glyphs.clear();
            self.galley_caches.clear(); // Galleys point into the old atlas.
        }

        let viewport_cache = self.galley_caches.entry(viewport_key).or_default();
        viewport_cache.cache.flush_cache();
        viewport_cache.used_since_begin_pass = false;
    }

    /// Has any text been laid out in this viewport since its last [`Self::begin_pass`]?
    ///
    /// While this is `false`, fonts can still be swapped out for this pass without
    /// leaving anything laid out with the old ones.
    #[inline]
    pub fn used_since_begin_pass(&self, viewport_key: ViewportKey) -> bool {
        self.galley_caches
            .get(&viewport_key)
            .is_some_and(|cache| cache.used_since_begin_pass)
    }

    /// 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(&mut self) -> Option<crate::ImageDelta> {
        self.fonts.glyphs.take_delta()
    }

    #[inline]
    pub fn options(&self) -> &TextOptions {
        self.texture_atlas().options()
    }

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

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

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

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

    /// Do the installed fonts have this glyph?
    ///
    /// This does not consult the [`GlyphRasterizer`]s, so it can return `false`
    /// for a character that would still render via a rasterizer (e.g. the browser on web).
    pub fn has_glyph(&mut self, font_id: &FontId, c: char) -> bool {
        self.fonts.has_glyph(&font_id.family, c)
    }

    /// Do the installed fonts have all the glyphs in this text?
    ///
    /// See [`Self::has_glyph`] for the caveat about the [`GlyphRasterizer`]s.
    pub fn has_glyphs(&mut self, font_id: &FontId, s: &str) -> bool {
        self.fonts.has_glyphs(&font_id.family, s)
    }

    pub fn num_galleys_in_cache(&self) -> usize {
        self.galley_caches
            .values()
            .map(|viewport| viewport.cache.num_galleys_in_cache())
            .sum()
    }

    /// Drop cached layouts belonging to viewports that are no longer alive.
    pub fn retain_galley_caches(&mut self, mut keep: impl FnMut(ViewportKey) -> bool) {
        self.galley_caches
            .retain(|&viewport_key, _| keep(viewport_key));
    }

    /// 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_pass`].
    pub fn font_atlas_fill_ratio(&self) -> f32 {
        self.fonts.glyphs.fill_ratio()
    }

    /// Lay out some text, bypassing the galley cache.
    ///
    /// Prefer [`FontsView::layout_job`], which memoizes.
    /// This is mostly useful for benchmarking the layout code.
    pub fn layout_uncached(&mut self, pixels_per_point: f32, job: Arc<LayoutJob>) -> Galley {
        self.layout_uncached_for_viewport(pixels_per_point, ViewportKey::default(), job)
    }

    /// Lay out text without caching it in the given viewport's cache.
    pub fn layout_uncached_for_viewport(
        &mut self,
        pixels_per_point: f32,
        viewport_key: ViewportKey,
        job: Arc<LayoutJob>,
    ) -> Galley {
        self.galley_caches
            .entry(viewport_key)
            .or_default()
            .used_since_begin_pass = true;
        layout(&mut self.fonts, pixels_per_point, job)
    }

    /// Returns a [`FontsView`] with the given `pixels_per_point` that can be used to do text layout.
    ///
    /// This uses the default layout-cache namespace. Integrations that render multiple
    /// independently scheduled viewports must use [`Self::with_pixels_per_point_for_viewport`].
    pub fn with_pixels_per_point(&mut self, pixels_per_point: f32) -> FontsView<'_> {
        self.with_pixels_per_point_for_viewport(pixels_per_point, ViewportKey::default())
    }

    /// Returns a [`FontsView`] with the given `pixels_per_point` for the specified
    /// viewport that can be used to do text layout with a viewport-specific galley cache.
    pub fn with_pixels_per_point_for_viewport(
        &mut self,
        pixels_per_point: f32,
        viewport_key: ViewportKey,
    ) -> FontsView<'_> {
        let viewport_cache = self.galley_caches.entry(viewport_key).or_default();
        FontsView {
            fonts: &mut self.fonts,
            galley_cache: &mut viewport_cache.cache,
            pixels_per_point,
            used_since_begin_pass: &mut viewport_cache.used_since_begin_pass,
        }
    }
}

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

/// The context's collection of fonts, with this context's `pixels_per_point`. This is what you use to do text layout.
pub struct FontsView<'a> {
    fonts: &'a mut FontsImpl,
    galley_cache: &'a mut GalleyCache,
    pixels_per_point: f32,
    used_since_begin_pass: &'a mut bool,
}

impl FontsView<'_> {
    #[inline]
    pub fn options(&self) -> &TextOptions {
        self.fonts.options()
    }

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

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

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

    /// Width of this character in points.
    ///
    /// If the font doesn't exist, this will return `0.0`.
    pub fn glyph_width(&mut self, font_id: &FontId, c: char) -> f32 {
        self.fonts.glyph_width(&font_id.family, c, font_id.size)
    }

    /// Do the installed fonts have this glyph?
    ///
    /// This does not consult the [`GlyphRasterizer`]s, so it can return `false`
    /// for a character that would still render via a rasterizer (e.g. the browser on web).
    pub fn has_glyph(&mut self, font_id: &FontId, c: char) -> bool {
        self.fonts.has_glyph(&font_id.family, c)
    }

    /// Do the installed fonts have all the glyphs in this text?
    ///
    /// See [`Self::has_glyph`] for the caveat about the [`GlyphRasterizer`]s.
    pub fn has_glyphs(&mut self, font_id: &FontId, s: &str) -> bool {
        self.fonts.has_glyphs(&font_id.family, s)
    }

    /// All characters the fonts of this family support, and the names of the fonts that have each.
    ///
    /// This does not consult the [`GlyphRasterizer`]s.
    pub fn characters(&mut self, family: &FontFamily) -> &BTreeMap<char, Vec<String>> {
        self.fonts.characters(family)
    }

    /// Height of one row of text in points.
    ///
    /// Returns a value rounded to [`emath::GUI_ROUNDING`].
    #[inline]
    pub fn row_height(&mut self, font_id: &FontId) -> f32 {
        let family = self.fonts.family_key(&font_id.family);
        self.fonts
            .family_metrics(
                family,
                self.pixels_per_point,
                font_id.size,
                // TODO(valadaptive): use font variation coords when calculating row height
                &VariationCoords::default(),
            )
            .row_height
    }

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

    /// The fonts discovered by the [`FontProvider`]s so far, in the order they were found.
    ///
    /// These are not part of [`Self::definitions`].
    pub fn discovered_fonts(&self) -> &[FontInsert] {
        self.fonts.discovered_fonts()
    }

    /// 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(&mut self, job: LayoutJob) -> Arc<Galley> {
        *self.used_since_begin_pass = true;
        let allow_split_paragraphs = true; // Optimization for editing text with many paragraphs.
        self.galley_cache.layout(
            self.fonts,
            self.pixels_per_point,
            job,
            allow_split_paragraphs,
        )
    }

    pub fn num_galleys_in_cache(&self) -> usize {
        self.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 [`Fonts::begin_pass`].
    pub fn font_atlas_fill_ratio(&self) -> f32 {
        self.fonts.glyphs.fill_ratio()
    }

    /// Will wrap text at the given width and line break at `\n`.
    ///
    /// The implementation uses memoization so repeated calls are cheap.
    #[inline]
    pub fn layout(
        &mut self,
        text: String,
        font_id: FontId,
        color: 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.
    #[inline]
    pub fn layout_no_wrap(&mut self, text: String, font_id: FontId, color: 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.
    #[inline]
    pub fn layout_delayed_color(
        &mut self,
        text: String,
        font_id: FontId,
        wrap_width: f32,
    ) -> Arc<Galley> {
        self.layout(text, font_id, Color32::PLACEHOLDER, wrap_width)
    }
}

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

/// The collection of fonts used by `epaint`.
///
/// Required in order to paint text.
pub(crate) struct FontsImpl {
    definitions: Arc<FontDefinitions>,
    glyphs: GlyphAtlas,
    faces: FaceStore,

    /// Indexed by [`FamilyKey`].
    families: Vec<Family>,
    family_keys: ahash::HashMap<FontFamily, FamilyKey>,

    /// Recycled `harfrust` shaping buffer to avoid per-layout allocations.
    shape_buffer: Option<harfrust::UnicodeBuffer>,

    /// In the order they were added. See [`GlyphRasterizer`].
    glyph_rasterizers: Vec<GlyphRasterizer>,
    font_providers: FontProviders,

    missing_glyph_policy: MissingGlyphPolicy,

    /// Draws the synthetic tofu box for families that have no font at all.
    ///
    /// Kept as a [`GlyphRasterizer`] so its glyphs share the atlas cache with the other rasterized glyphs.
    synthetic_tofu: GlyphRasterizer,
}

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(options: TextOptions, definitions: FontDefinitions) -> Self {
        let mut slf = Self {
            definitions: Arc::new(definitions),
            glyphs: GlyphAtlas::new(options),
            faces: FaceStore::new(options),
            families: Default::default(),
            family_keys: Default::default(),
            shape_buffer: Some(harfrust::UnicodeBuffer::new()),
            glyph_rasterizers: Vec::new(),
            font_providers: Default::default(),
            missing_glyph_policy: Default::default(),
            synthetic_tofu: GlyphRasterizer::new(
                "epaint::synthetic_tofu",
                |request: &GlyphRasterizerRequest<'_>| Some(synthetic_tofu(request.font_size_px)),
            ),
        };
        slf.set_font_providers(Vec::new());
        slf
    }

    /// Ask these for fonts, after the configured [`FontDefinitions`].
    ///
    /// Forgets the fallback chains, so the providers are asked again for each family.
    pub fn set_font_providers(&mut self, font_providers: Vec<Arc<dyn FontProvider>>) {
        let configured: Arc<dyn FontProvider> = Arc::<FontDefinitions>::clone(&self.definitions);
        let providers = core::iter::chain(core::iter::once(configured), font_providers).collect();
        self.font_providers = FontProviders::new(providers);
        self.families.clear();
        self.family_keys.clear();
    }

    /// The fonts discovered by the [`FontProvider`]s so far, in the order they were found.
    pub fn discovered_fonts(&self) -> &[FontInsert] {
        self.font_providers.discovered()
    }

    /// Apply new [`TextOptions`].
    ///
    /// The parsed faces and the fallback chains survive; only the atlas starts over.
    pub fn set_options(&mut self, options: TextOptions) {
        self.faces.set_options(options);
        self.glyphs = GlyphAtlas::new(options);
    }

    /// Also use this glyph rasterizer.
    #[cfg(test)]
    #[inline]
    pub fn with_glyph_rasterizer(mut self, glyph_rasterizer: GlyphRasterizer) -> Self {
        self.add_glyph_rasterizer(glyph_rasterizer);
        self
    }

    /// Also use this glyph rasterizer, e.g. the browser on web, or for custom glyphs.
    ///
    /// See [`Fonts::add_glyph_rasterizer`].
    pub fn add_glyph_rasterizer(&mut self, glyph_rasterizer: GlyphRasterizer) -> bool {
        let changed = glyph_rasterizer.insert_into(&mut self.glyph_rasterizers);
        if changed {
            self.glyphs.clear_raster_glyphs();
        }
        changed
    }

    /// Replace all [`GlyphRasterizer`]s.
    ///
    /// Pass an empty list to only use the installed fonts.
    pub fn set_glyph_rasterizers(&mut self, glyph_rasterizers: Vec<GlyphRasterizer>) {
        self.glyph_rasterizers = glyph_rasterizers;
        self.glyphs.clear_raster_glyphs();
    }

    /// Is there any [`GlyphRasterizer`] with this priority?
    #[inline]
    pub fn has_glyph_rasterizer(&self, priority: FontPriority) -> bool {
        self.glyph_rasterizers
            .iter()
            .any(|rasterizer| rasterizer.priority == priority)
    }

    pub fn options(&self) -> &TextOptions {
        self.glyphs.options()
    }

    /// Take the recycled shaping buffer (or create a new one if already taken).
    pub fn take_shape_buffer(&mut self) -> harfrust::UnicodeBuffer {
        self.shape_buffer.take().unwrap_or_default()
    }

    /// Return a shaping buffer for reuse.
    pub fn return_shape_buffer(&mut self, buffer: harfrust::UnicodeBuffer) {
        self.shape_buffer = Some(buffer);
    }

    // ------------------------------------------------------------------------
    // Families

    /// Look up (or build) the fallback chain of a family.
    ///
    /// Panics if the family is not in the [`FontDefinitions`].
    pub fn family_key(&mut self, family: &FontFamily) -> FamilyKey {
        if let Some(key) = self.family_keys.get(family) {
            return *key;
        }
        let key = FamilyKey(self.families.len());
        self.families
            .push(Family::new(family, &mut self.faces, &self.font_providers));
        self.family_keys.insert(family.clone(), key);
        key
    }

    #[inline]
    fn family(&self, key: FamilyKey) -> &Family {
        &self.families[key.0]
    }

    /// Find which face in the fallback chain owns `c`.
    ///
    /// See [`Family::resolve`].
    #[inline]
    pub fn resolve_face(&mut self, family: FamilyKey, c: char) -> FontFaceKey {
        self.families[family.0].resolve(&mut self.faces, &mut self.font_providers, c)
    }

    /// Like [`Self::resolve_face`] for the first char of `cluster`,
    /// but lets the [`FontProvider`]s see the whole grapheme cluster.
    #[inline]
    pub fn resolve_cluster_face(&mut self, family: FamilyKey, cluster: &str) -> FontFaceKey {
        self.families[family.0].resolve_cluster(&mut self.faces, &mut self.font_providers, cluster)
    }

    /// Resolve `c` to its (face, [`GlyphInfo`]) at the given face's location.
    ///
    /// `\n` will (intentionally) show up as the `.notdef` glyph ("tofu").
    ///
    /// `metrics` must be the resolved [`StyledMetrics`] for the face that ends
    /// up owning `c`. Most callers pass the metrics of their text run's primary
    /// face, which is correct as long as `c` is in that face. For correct
    /// fallback-face advances, resolve the face first with [`Self::resolve_face`]
    /// and build metrics for that face.
    pub fn glyph_info(
        &mut self,
        family: FamilyKey,
        c: char,
        metrics: &StyledMetrics,
    ) -> (FontFaceKey, GlyphInfo) {
        let face_key = self.resolve_face(family, c);
        let Some(face) = self.faces.get_mut(face_key) else {
            return (face_key, GlyphInfo::INVISIBLE);
        };
        if let Some(glyph_info) = face.glyph_info(c, metrics) {
            return (face_key, glyph_info);
        }

        // `c` is in no face: render the face's `.notdef` glyph ("tofu") instead.
        let glyph_info = self
            .faces
            .get(face_key)
            .map(|face| face.notdef_glyph_info(metrics))
            .unwrap_or(GlyphInfo::INVISIBLE);
        (face_key, glyph_info)
    }

    /// Metrics of the primary face of the family,
    /// or [`StyledMetrics::without_font`] if the family has no font.
    pub fn family_metrics(
        &self,
        family: FamilyKey,
        pixels_per_point: f32,
        font_size: f32,
        coords: &VariationCoords,
    ) -> StyledMetrics {
        self.family(family)
            .primary()
            .and_then(|key| self.faces.get(key))
            .map_or_else(
                || StyledMetrics::without_font(pixels_per_point, font_size),
                |face| face.styled_metrics(pixels_per_point, font_size, coords),
            )
    }

    /// Width of this character in points, at the font's default variation location.
    ///
    /// Returns `0.0` if no font has the character.
    pub fn glyph_width(&mut self, family: &FontFamily, c: char, font_size: f32) -> f32 {
        let family = self.family_key(family);
        let face_key = self.resolve_face(family, c);
        let Some(face) = self.faces.get_mut(face_key) else {
            return 0.0;
        };
        let metrics = face.styled_metrics(1.0, font_size, &VariationCoords::default());
        let Some(glyph_info) = face.glyph_info(c, &metrics) else {
            return 0.0;
        };
        glyph_info.advance_width_unscaled.0 * face.px_scale_factor(font_size)
    }

    /// Do the installed fonts have this glyph?
    ///
    /// This does not consult the [`GlyphRasterizer`]s, so it can return `false`
    /// for a character that would still render via a rasterizer (e.g. the browser on web).
    pub fn has_glyph(&mut self, family: &FontFamily, c: char) -> bool {
        let family = self.family_key(family);
        let face_key = self.resolve_face(family, c);
        self.faces
            .get_mut(face_key)
            .is_some_and(|face| face.glyph_id_resolution(c).is_some())
    }

    /// Do the installed fonts have all the glyphs in this text?
    ///
    /// See [`Self::has_glyph`] for the caveat about the glyph rasterizer.
    pub fn has_glyphs(&mut self, family: &FontFamily, s: &str) -> bool {
        s.chars().all(|c| self.has_glyph(family, c))
    }

    /// All characters the fonts of this family support, and the names of the fonts that have each.
    pub fn characters(&mut self, family: &FontFamily) -> &BTreeMap<char, Vec<String>> {
        let family = self.family_key(family);
        self.families[family.0].characters(&self.faces)
    }

    // ------------------------------------------------------------------------
    // Faces and glyphs

    #[inline]
    pub fn face(&self, key: FontFaceKey) -> Option<&FontFace> {
        self.faces.get(key)
    }

    /// Get or render the glyph of a face, and put it in the atlas.
    ///
    /// See [`GlyphAtlas::allocate_outline`].
    pub fn allocate_glyph(
        &mut self,
        face_key: FontFaceKey,
        metrics: &StyledMetrics,
        shaped: &ShapedGlyph,
    ) -> OutlineGlyph {
        let Some(face) = self.faces.get_mut(face_key) else {
            return Default::default();
        };
        self.glyphs
            .allocate_outline(face_key, face, metrics, shaped)
    }

    /// Rasterize a grapheme cluster using the [`GlyphRasterizer`]s of the given priority.
    ///
    /// Returns `None` if there is no such rasterizer, or none of them could handle the cluster.
    pub fn rasterize_cluster(
        &mut self,
        priority: FontPriority,
        family: FamilyKey,
        cluster: &str,
        pixels_per_point: f32,
        font_size: f32,
    ) -> Option<RasterGlyphAllocation> {
        if !self.has_glyph_rasterizer(priority) {
            return None;
        }
        let family_name = self.families[family.0].name();
        self.glyphs.allocate_raster(
            &self.glyph_rasterizers,
            priority,
            cluster,
            family_name,
            pixels_per_point,
            font_size,
        )
    }

    /// Nothing can draw `cluster`: no font, provider, or rasterizer.
    ///
    /// Call right before drawing tofu for it, so [`MissingGlyphPolicy::Panic`] can act.
    /// Control characters are exempt: fonts have no glyphs for them, and drawing tofu
    /// for e.g. a `\n` in a single-line layout is intentional.
    pub fn on_missing_glyph(&self, family: FamilyKey, cluster: &str) {
        if self.missing_glyph_policy != MissingGlyphPolicy::Panic {
            return;
        }
        let Some(chr) = cluster.chars().next() else {
            return;
        };
        if chr.is_control() {
            return;
        }

        let family = &self.families[family.0];
        let faces = family.face_names(&self.faces);
        let hint = if faces.is_empty() {
            "The family has no fonts at all: install some with `FontDefinitions`, \
             or enable the `default_fonts` feature to bundle egui's."
        } else {
            "Install a font that has it, add a `FontProvider` or `GlyphRasterizer` that can draw it, \
             or allow tofu with `MissingGlyphPolicy::Tofu`."
        };
        panic!(
            "No glyph for {cluster:?} (U+{:04X}) in {:?}. Installed fonts: {faces:?}. {hint}",
            chr as u32,
            family.name(),
        );
    }

    /// The glyph for `cluster` in a family that has no font at all.
    ///
    /// From a fallback [`GlyphRasterizer`] if one handles it, else a synthetic tofu box.
    pub fn fontless_cluster(
        &mut self,
        family: FamilyKey,
        cluster: &str,
        pixels_per_point: f32,
        font_size: f32,
    ) -> RasterGlyphAllocation {
        if let Some(raster) = self.rasterize_cluster(
            FontPriority::Lowest,
            family,
            cluster,
            pixels_per_point,
            font_size,
        ) {
            return raster;
        }

        self.on_missing_glyph(family, cluster);

        let family_name = self.families[family.0].name();
        self.glyphs
            .allocate_raster(
                core::iter::once(&self.synthetic_tofu),
                FontPriority::Lowest,
                SYNTHETIC_TOFU_KEY,
                family_name,
                pixels_per_point,
                font_size,
            )
            .unwrap_or_else(|| {
                // Only if the atlas cannot hold a tiny box: advance, but draw nothing.
                RasterGlyphAllocation {
                    allocation: GlyphAllocation::default(),
                    advance_px: 0.0,
                }
            })
    }
}

/// Cache key for the synthetic tofu box in the atlas.
///
/// Never a real grapheme cluster, so it cannot collide with one.
const SYNTHETIC_TOFU_KEY: &str = "";

/// A hollow box the size of a typical glyph, standing on the baseline.
///
/// Drawn for a character when no font has it and the family has no
/// primary font whose `.notdef` glyph we could draw instead.
fn synthetic_tofu(font_size_px: f32) -> RasterizedGlyph {
    let width = (0.5 * font_size_px).round().max(2.0) as usize;
    let height = (0.7 * font_size_px).round().max(2.0) as usize;
    let stroke = (font_size_px / 14.0).round().max(1.0) as usize;
    let side_bearing = (0.1 * font_size_px).round();

    let mut image = ColorImage::filled([width, height], Color32::TRANSPARENT);
    for y in 0..height {
        for x in 0..width {
            let on_edge = x < stroke || width - stroke <= x || y < stroke || height - stroke <= y;
            if on_edge {
                image[(x, y)] = Color32::WHITE;
            }
        }
    }

    RasterizedGlyph {
        bitmap: GlyphBitmap {
            image,
            // The pen is at the baseline; the box stands on it.
            offset_px: emath::vec2(side_bearing, -(height as f32)),
            is_color: false,
        },
        advance_px: width as f32 + 2.0 * side_bearing,
    }
}

#[cfg(feature = "default_fonts")]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn viewport_passes_do_not_evict_each_others_galleys() {
        let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default());
        let root = ViewportKey::new(1);
        let child = ViewportKey::new(2);
        let font_id = FontId::proportional(14.0);

        fonts.begin_pass(TextOptions::default(), root);
        let root_galley = fonts
            .with_pixels_per_point_for_viewport(1.0, root)
            .layout_no_wrap("root viewport".to_owned(), font_id.clone(), Color32::WHITE);
        assert!(fonts.used_since_begin_pass(root));

        // A shared GalleyCache would advance its generation here. When the root
        // began its next pass, the child's generation would make the root galley
        // look unused and evict it.
        fonts.begin_pass(TextOptions::default(), child);
        assert!(fonts.used_since_begin_pass(root));
        assert!(!fonts.used_since_begin_pass(child));
        fonts
            .with_pixels_per_point_for_viewport(1.0, child)
            .layout_no_wrap("child viewport".to_owned(), font_id.clone(), Color32::WHITE);
        assert!(fonts.used_since_begin_pass(child));

        fonts.begin_pass(TextOptions::default(), root);
        assert!(!fonts.used_since_begin_pass(root));
        assert!(fonts.used_since_begin_pass(child));
        let root_galley_next_pass = fonts
            .with_pixels_per_point_for_viewport(1.0, root)
            .layout_no_wrap("root viewport".to_owned(), font_id, Color32::WHITE);

        assert!(Arc::ptr_eq(&root_galley, &root_galley_next_pass));
    }

    /// The special emojis are in the private use area, so only our own bundled
    /// `egui-icons.ttf` has them.
    #[test]
    fn special_emojis_come_from_the_bundled_icon_font() {
        use epaint_default_fonts::special_emojis::{GIT, GITHUB, OS_ANDROID, OS_APPLE, OS_WINDOWS};

        let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default());
        let mut view = fonts.with_pixels_per_point(1.0);
        let characters = view.characters(&FontFamily::Proportional).clone();

        for chr in [GIT, GITHUB, OS_ANDROID, OS_APPLE, OS_WINDOWS] {
            let faces = characters.get(&chr);
            assert!(
                faces.is_some_and(|faces| faces.iter().any(|name| name == "egui-icons")),
                "{chr:?} (U+{:04X}) should be in egui-icons, but was only in {faces:?}",
                chr as u32
            );
        }
    }

    #[test]
    fn test_fallback_glyph_width() {
        let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::empty());
        let mut view = fonts.with_pixels_per_point(1.0);

        let width = view.glyph_width(&FontId::new(12.0, FontFamily::Proportional), ' ');
        assert_eq!(width, 0.0);
    }
}