Skip to main content

egui_pop_core/
fonts.rs

1//! Text fonts from the theme: the families named by `font.family.ui` and
2//! `font.family.mono`, at several weights.
3//!
4//! Each name of a token's list is looked for in order:
5//!
6//! 1. faces the application registered ([`register`]): bytes it embeds or
7//!    reads from disk;
8//! 2. the system's fonts by family name (feature `system-fonts`, or the
9//!    faces given by [`set_system_faces`]);
10//! 3. the faces bundled by name: egui-pop's own pair with the
11//!    `bundled-fonts` feature ([`bundled`]: `Inter`, `JetBrains Mono
12//!    NL`), then egui's (`Ubuntu` is egui's Ubuntu-Light, `Hack` its
13//!    Hack). A bundled face is reached by its name only when the system
14//!    has no family of that name, as platforms resolve a font stack.
15//!
16//! The first found is the primary, the others its fallbacks, and egui's
17//! bundled fonts always come last so text never vanishes. A generic name
18//! (`sans-serif`, `serif`, `system-ui`; `monospace`, `ui-monospace`)
19//! stands for the bundled fonts: egui-pop's pair with `bundled-fonts`
20//! (Inter for the proportional names, JetBrains Mono NL for the
21//! monospace ones, at every weight), else egui's own faces. The built-in
22//! themes name only generic families, so the default pair is egui-pop's
23//! with the feature and egui's without it. A name found nowhere is a problem in the [`Report`]
24//! (ADR 0003), never replaced in silence; the report says where each
25//! name was found ([`Report::resolved`]: `Ubuntu → bundled Ubuntu-Light`).
26//!
27//! egui's `FontId` has no weight: each weight of [`WEIGHTS`] is an egui
28//! family of its own, [`family`]`(role, weight)`, and [`font_id`] gives
29//! the `FontId` to draw with ([`font_at`] at a [`Step`] of the theme's
30//! size scale). A variable face (a `wght` axis) serves
31//! every weight its axis covers, set on the face (`FontTweak::coords`);
32//! a static face serves its own weight, and a weight a family lacks takes
33//! its nearest one, said in the report. egui's `Proportional` and `Monospace` families are
34//! the regular weight of `ui` and `mono`, so egui's own widgets follow the
35//! theme too.
36//!
37//! Where a role's glyphs sit in their row is the theme's too
38//! (`font.baseline-offset.ui`, `font.baseline-offset.mono`, a share of
39//! the size, 0 by default): every face of the role's chain, egui's
40//! fallbacks included, is drawn that much lower (`FontTweak::y_offset_factor`),
41//! under a key of its own ([`BaselineOffsets`]). It moves the glyphs, not
42//! the row: the layout keeps its sizes.
43//!
44//! [`install_with_offsets`] runs with the theme (`theme::install_tokens`);
45//! it replaces egui's font definitions only when the families, their
46//! offsets or the registered faces changed (one slow frame: egui rebuilds
47//! its atlas).
48//!
49//! Any family can also be drawn by name, outside the theme's roles, as a
50//! [`specimen`] (a picker drawing each name in its own face, a page
51//! comparing fonts); [`families`] lists the families there are, with
52//! their [`Origin`].
53//!
54//! A face is previewed before it is applied through the preview
55//! families ([`set_preview`]): every install defines them, so they never
56//! vanish while a preview draws (egui panics on an unknown family). They
57//! draw the role's families as installed, or the list a preview gives;
58//! [`with_preview`] draws a `Ui` in them, the rest of the application
59//! keeping the theme's fonts.
60//!
61//! The system's fonts come from fontdb (feature `system-fonts`), unless
62//! faces are given in their place ([`set_system_faces`]: tests, or an
63//! application finding fonts its own way).
64
65use std::sync::Arc;
66
67use egui::text::{LayoutJob, LayoutSection, TextFormat};
68use egui::{Color32, Context, FontData, FontDefinitions, FontFamily, FontId, Galley};
69
70use crate::state::Slot;
71
72/// Which text a family is for.
73#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub enum Role {
75    /// Interface text (`font.family.ui`).
76    Ui,
77    /// Values, code, logs (`font.family.mono`).
78    Mono,
79}
80
81impl Role {
82    pub const ALL: [Role; 2] = [Role::Ui, Role::Mono];
83
84    fn key(self) -> &'static str {
85        match self {
86            Role::Ui => "ui",
87            Role::Mono => "mono",
88        }
89    }
90
91    fn token(self) -> &'static str {
92        match self {
93            Role::Ui => "font.family.ui",
94            Role::Mono => "font.family.mono",
95        }
96    }
97}
98
99/// How far each role's glyphs are drawn below their place, a share of
100/// the text's size (`font.baseline-offset.ui`, `font.baseline-offset.mono`):
101/// 0.1 at 14 points moves them 1.4 points down, a negative share moves
102/// them up. The text's row keeps its height; only the glyphs move, as
103/// egui's `FontTweak::y_offset_factor` does. 0 for both by default.
104#[derive(Clone, Copy, Debug, Default, PartialEq)]
105pub struct BaselineOffsets {
106    pub ui: f32,
107    pub mono: f32,
108}
109
110impl BaselineOffsets {
111    /// A role's offset.
112    pub fn get(self, role: Role) -> f32 {
113        match role {
114            Role::Ui => self.ui,
115            Role::Mono => self.mono,
116        }
117    }
118}
119
120/// A font weight, as CSS and OpenType number them (100 to 900).
121#[derive(
122    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
123)]
124#[serde(transparent)]
125pub struct Weight(pub u16);
126
127impl Weight {
128    pub const REGULAR: Weight = Weight(400);
129    pub const MEDIUM: Weight = Weight(500);
130    pub const SEMIBOLD: Weight = Weight(600);
131    pub const BOLD: Weight = Weight(700);
132
133    /// The weight of [`WEIGHTS`] nearest to this one.
134    pub fn nearest_installed(self) -> Weight {
135        nearest(self, WEIGHTS.iter().copied()).unwrap_or(Weight::REGULAR)
136    }
137}
138
139/// The weights each family is installed at.
140pub const WEIGHTS: [Weight; 4] = [
141    Weight::REGULAR,
142    Weight::MEDIUM,
143    Weight::SEMIBOLD,
144    Weight::BOLD,
145];
146
147/// The egui family of a role at a weight (`pop.ui.700`); a weight not in
148/// [`WEIGHTS`] gives the nearest installed one.
149pub fn family(role: Role, weight: Weight) -> FontFamily {
150    let w = weight.nearest_installed();
151    FontFamily::Name(format!("pop.{}.{}", role.key(), w.0).into())
152}
153
154/// The font to draw a role's text at a weight and a size (points).
155pub fn font_id(role: Role, weight: Weight, size: f32) -> FontId {
156    FontId::new(size, family(role, weight))
157}
158
159/// A step of the theme's size scale (`font.size.xs` to `font.size.xl`).
160#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
161pub enum Step {
162    Xs,
163    S,
164    M,
165    L,
166    Xl,
167}
168
169impl Step {
170    pub const ALL: [Step; 5] = [Step::Xs, Step::S, Step::M, Step::L, Step::Xl];
171
172    /// Its name in the tokens (`xs`, `s`, `m`, `l`, `xl`).
173    pub fn name(self) -> &'static str {
174        match self {
175            Step::Xs => "xs",
176            Step::S => "s",
177            Step::M => "m",
178            Step::L => "l",
179            Step::Xl => "xl",
180        }
181    }
182
183    /// Its token (`font.size.m`).
184    pub fn token(self) -> &'static str {
185        match self {
186            Step::Xs => "font.size.xs",
187            Step::S => "font.size.s",
188            Step::M => "font.size.m",
189            Step::L => "font.size.l",
190            Step::Xl => "font.size.xl",
191        }
192    }
193}
194
195/// The font to draw a role's text at a weight and a step of the theme's
196/// size scale ([`font_id`] at the step's size).
197pub fn font_at(tokens: &crate::theme::Tokens, role: Role, weight: Weight, step: Step) -> FontId {
198    font_id(role, weight, tokens.font.scale.get(step))
199}
200
201/// The `fonts` collector of the debug bridge (among the core ones):
202/// what the theme asked, the faces registered with their origin, each
203/// egui family's chain, the sizes, the atlas; and `check`, the chars of
204/// a text no face of a family covers. Read after the first frame (egui
205/// has no fonts before).
206pub fn collector() -> crate::debug::FnCollector {
207    use serde_json::{Value as Json, json};
208    crate::debug::FnCollector::new(
209        "fonts",
210        "The fonts: the families the theme asks for and where each name was found (registered, system or bundled), the faces registered (family, weight, origin, size, tabular digits, monospace), each egui family's faces in fallback order, the specimens, the sizes of the scale and of egui's text styles, the text size, how values line up, the atlas and the problems.",
211    )
212    .snapshot(|ctx| {
213        let t = crate::theme::Tokens::of(ctx);
214        let (ui, mono) = installed_families(ctx).unwrap_or_default();
215        let report = report(ctx).unwrap_or_default();
216        let faces: Vec<Json> = registered(ctx)
217            .iter()
218            .map(|f| {
219                json!({
220                    "family": f.family,
221                    "weight": f.weight.0,
222                    "origin": f.origin,
223                    "bytes": f.len(),
224                    "tabular_digits": f.tabular_digits(),
225                    "monospace": f.monospace(),
226                })
227            })
228            .collect();
229        let primary: std::collections::BTreeMap<&str, &Option<String>> = report
230            .primary
231            .iter()
232            .map(|(f, p)| (f.as_str(), p))
233            .collect();
234        let families: Vec<Json> = report
235            .chains
236            .iter()
237            .map(|(f, chain)| {
238                json!({
239                    "family": f,
240                    "primary": primary.get(f.as_str()).copied().cloned().flatten(),
241                    "chain": chain,
242                })
243            })
244            .collect();
245        let s = &t.font.scale;
246        let ppp = ctx.pixels_per_point();
247        // egui has no fonts before its first pass.
248        let (atlas, fill) = if ctx.cumulative_pass_nr() == 0 {
249            (None, None)
250        } else {
251            ctx.fonts(|f| (Some(f.font_image_size()), Some(f.font_atlas_fill_ratio())))
252        };
253        json!({
254            "requested": { "ui": ui, "mono": mono },
255            "faces": faces,
256            "families": families,
257            "specimens": report.specimens,
258            "resolved": report
259                .resolved
260                .iter()
261                .map(|r| json!({
262                    "list": r.list,
263                    "name": r.name,
264                    "origin": r.origin,
265                    "face": r.face,
266                    "says": r.to_string(),
267                }))
268                .collect::<Vec<_>>(),
269            "tabular_digits": {
270                "ui": report.tabular_digits(Role::Ui),
271                "mono": report.tabular_digits(Role::Mono),
272            },
273            "numeric": t.font.numeric,
274            "text_size": t.resolved().spec().text_size,
275            "sizes": {
276                "scale": { "xs": s.xs, "s": s.s, "m": s.m, "l": s.l, "xl": s.xl },
277                "text_styles": {
278                    "small": t.font.small,
279                    "body": t.font.body,
280                    "button": t.font.button,
281                    "heading": t.font.heading,
282                    "monospace": t.font.mono,
283                },
284            },
285            "pixels_per_point": ppp,
286            "atlas": { "size": atlas, "fill_ratio": fill },
287            "problems": report.problems,
288        })
289    })
290    .action(
291        "check",
292        "The chars of `text` no face of a family covers (`family`: `ui` or `mono`, the default `ui`, or a family's name drawn as a specimen); drawn as a box.",
293        false,
294        |ctx, args| {
295            let text = args
296                .get("text")
297                .and_then(Json::as_str)
298                .ok_or("`text` is missing")?;
299            let asked = args.get("family").and_then(Json::as_str).unwrap_or("ui");
300            let family = match asked {
301                "ui" => FontFamily::Proportional,
302                "mono" => FontFamily::Monospace,
303                name => specimen(ctx, name, Weight::REGULAR).ok_or_else(|| {
304                    format!("`{name}` is being installed as a specimen: ask again after a frame")
305                })?,
306            };
307            if ctx.cumulative_pass_nr() == 0 {
308                return Err("egui has no fonts before its first frame".into());
309            }
310            let id = FontId::new(13.0, family);
311            let missing: Vec<String> = uncovered(ctx, &id, text)
312                .into_iter()
313                .map(String::from)
314                .collect();
315            Ok(json!({ "family": asked, "missing": missing }))
316        },
317    )
318    .args(json!({ "text": "Ελληνικά 日本語", "family": "ui" }))
319}
320
321/// The fonts egui-pop bundles (feature `bundled-fonts`, on by default):
322/// Inter for interface text, JetBrains Mono NL (without ligatures) for
323/// values and code, subset to Latin, Greek and Cyrillic. They are under
324/// the SIL Open Font License 1.1, whose text ships with them (the
325/// crate's `fonts/` folder). The generic family names draw them, and a
326/// theme or a user may name them.
327#[cfg(feature = "bundled-fonts")]
328pub mod bundled {
329    /// The interface family, as a theme names it.
330    pub const UI_FAMILY: &str = "Inter";
331    /// The monospace family, as a theme names it.
332    pub const MONO_FAMILY: &str = "JetBrains Mono NL";
333    /// Inter, variable (`wght` 100 to 900), `opsz` pinned at 14.
334    pub static INTER: &[u8] = include_bytes!("../fonts/inter/Inter-subset.ttf");
335    /// JetBrains Mono NL Regular (400).
336    pub static JETBRAINS_MONO_NL_REGULAR: &[u8] =
337        include_bytes!("../fonts/jetbrains-mono/JetBrainsMonoNL-Regular-subset.ttf");
338    /// JetBrains Mono NL Bold (700).
339    pub static JETBRAINS_MONO_NL_BOLD: &[u8] =
340        include_bytes!("../fonts/jetbrains-mono/JetBrainsMonoNL-Bold-subset.ttf");
341}
342
343/// egui-pop's bundled faces, [`Origin::Bundled`]; none without
344/// `bundled-fonts`.
345fn pop_bundled() -> &'static [Face] {
346    #[cfg(feature = "bundled-fonts")]
347    {
348        static FACES: std::sync::OnceLock<Vec<Face>> = std::sync::OnceLock::new();
349        FACES.get_or_init(|| {
350            let face = |family: &str, weight, bytes| Face {
351                origin: Origin::Bundled,
352                ..Face::from_static(family, weight, bytes)
353            };
354            vec![
355                face(bundled::UI_FAMILY, Weight::REGULAR, bundled::INTER),
356                face(
357                    bundled::MONO_FAMILY,
358                    Weight::REGULAR,
359                    bundled::JETBRAINS_MONO_NL_REGULAR,
360                ),
361                face(
362                    bundled::MONO_FAMILY,
363                    Weight::BOLD,
364                    bundled::JETBRAINS_MONO_NL_BOLD,
365                ),
366            ]
367        })
368    }
369    #[cfg(not(feature = "bundled-fonts"))]
370    {
371        &[]
372    }
373}
374
375/// The bundled family a generic name stands for: egui-pop's interface
376/// family for `sans-serif`, `serif` and `system-ui`, its monospace one
377/// for `monospace` and `ui-monospace`; `None` without `bundled-fonts`
378/// (egui's own faces behind every chain draw it).
379fn generic_family(name: &str) -> Option<&'static str> {
380    if !is_generic(name) {
381        return None;
382    }
383    #[cfg(feature = "bundled-fonts")]
384    {
385        let mono = ["monospace", "ui-monospace"]
386            .iter()
387            .any(|g| g.eq_ignore_ascii_case(name));
388        Some(if mono {
389            bundled::MONO_FAMILY
390        } else {
391            bundled::UI_FAMILY
392        })
393    }
394    #[cfg(not(feature = "bundled-fonts"))]
395    {
396        None
397    }
398}
399
400/// Where a face comes from.
401#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize)]
402#[serde(rename_all = "lowercase")]
403pub enum Origin {
404    /// The fonts bundled: egui-pop's (`Inter`, `JetBrains Mono NL`, with
405    /// `bundled-fonts`) and egui's own (`Ubuntu`, `Hack`).
406    Bundled,
407    /// A face the application registered ([`register`]).
408    Registered,
409    /// A font file the user added ([`register_files`]).
410    File,
411    /// The system's fonts (feature `system-fonts`).
412    System,
413}
414
415impl Origin {
416    /// Its name in reports: `bundled`, `registered`, `file`, `system`.
417    pub fn name(self) -> &'static str {
418        match self {
419            Origin::Bundled => "bundled",
420            Origin::Registered => "registered",
421            Origin::File => "file",
422            Origin::System => "system",
423        }
424    }
425}
426
427/// How values line their digits up (`font.numeric`): egui applies no
428/// OpenType feature, so tabular figures (`tnum`) cannot be asked of a
429/// face whose default digits are proportional.
430#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize)]
431#[serde(rename_all = "lowercase")]
432pub enum Numeric {
433    /// In the monospace family (`font.family.mono`), its size matched to
434    /// the interface text's: the default.
435    #[default]
436    Mono,
437    /// In the interface family: its own digits when they are tabular,
438    /// else each digit laid in a cell as wide as the widest digit.
439    Ui,
440}
441
442impl Numeric {
443    /// From the token's value: `mono` or `ui`.
444    pub fn parse(s: &str) -> Option<Numeric> {
445        match s.trim() {
446            "mono" => Some(Numeric::Mono),
447            "ui" => Some(Numeric::Ui),
448            _ => None,
449        }
450    }
451
452    pub fn name(self) -> &'static str {
453        match self {
454            Numeric::Mono => "mono",
455            Numeric::Ui => "ui",
456        }
457    }
458}
459
460/// How a value is drawn at a size: the font, and whether its digits are
461/// laid in cells (a proportional face asked for numbers).
462#[derive(Clone, Debug, PartialEq)]
463pub struct NumberFont {
464    pub font: FontId,
465    /// Each digit in a cell as wide as the widest, right-aligned in it.
466    pub cells: bool,
467}
468
469/// How values are drawn at `size` (the size of the text around them),
470/// from `font.numeric` and the installed faces: the monospace family at
471/// the size matching the interface text's x-height, or the interface
472/// family (its digits in cells when they are not tabular).
473pub fn number_font(ctx: &Context, size: f32) -> NumberFont {
474    let t = crate::theme::Tokens::of(ctx);
475    match t.font.numeric {
476        Numeric::Mono => {
477            let ratio = if t.font.body > 0.0 {
478                t.font.mono / t.font.body
479            } else {
480                1.0
481            };
482            NumberFont {
483                font: FontId::new(
484                    whole_pixel_advance(ctx, size * ratio),
485                    FontFamily::Monospace,
486                ),
487                cells: false,
488            }
489        }
490        Numeric::Ui => NumberFont {
491            font: FontId::new(size, FontFamily::Proportional),
492            cells: !report(ctx).is_some_and(|r| r.tabular_digits(Role::Ui)),
493        },
494    }
495}
496
497/// The largest size, not above `size`, at which the monospace family's
498/// advance is a whole number of physical pixels at the context's
499/// `pixels_per_point`: with a fractional advance, glyphs snap to pixels
500/// differently from one row to the next and a column drifts by a pixel.
501/// Before egui's first pass (no fonts yet), `size` to half a point.
502fn whole_pixel_advance(ctx: &Context, size: f32) -> f32 {
503    if ctx.cumulative_pass_nr() == 0 || size <= 0.0 {
504        return (size * 2.0).round() / 2.0;
505    }
506    let ppp = ctx.pixels_per_point();
507    let advance =
508        ctx.fonts_mut(|f| f.glyph_width(&FontId::new(size, FontFamily::Monospace), '0')) * ppp;
509    if advance <= 0.0 {
510        return size;
511    }
512    // A hair over, so an advance already whole stays.
513    let whole = (advance + 1e-3).floor().max(1.0);
514    size * whole / advance
515}
516
517/// A value's text laid out so its digits line up with the values above
518/// and below it ([`number_font`]): what sliders, readouts and tables of
519/// numbers draw. In cells, each digit is its own section, right-aligned
520/// in a cell as wide as the face's widest digit.
521pub fn number_job(ctx: &Context, text: &str, size: f32, color: Color32) -> LayoutJob {
522    let NumberFont { font, cells } = number_font(ctx, size);
523    if !cells {
524        return LayoutJob::simple_singleline(text.to_string(), font, color);
525    }
526    let widths: Vec<f32> =
527        ctx.fonts_mut(|f| ('0'..='9').map(|c| f.glyph_width(&font, c)).collect());
528    let cell = widths.iter().copied().fold(0.0_f32, f32::max);
529    digit_cells(text, &font, color, |c| {
530        c.to_digit(10).map(|d| cell - widths[d as usize])
531    })
532}
533
534/// The job of [`number_job`] in cells: `pad` gives the space before a
535/// digit (`None` for any other char).
536fn digit_cells(
537    text: &str,
538    font: &FontId,
539    color: Color32,
540    pad: impl Fn(char) -> Option<f32>,
541) -> LayoutJob {
542    let mut job = LayoutJob {
543        text: text.to_string(),
544        break_on_newline: false,
545        ..LayoutJob::default()
546    };
547    let format = TextFormat::simple(font.clone(), color);
548    let mut run_start: Option<usize> = None;
549    for (at, c) in text.char_indices() {
550        match pad(c) {
551            Some(leading) => {
552                if let Some(s) = run_start.take() {
553                    job.sections.push(LayoutSection {
554                        leading_space: 0.0,
555                        byte_range: span(s, at),
556                        format: format.clone(),
557                    });
558                }
559                job.sections.push(LayoutSection {
560                    leading_space: leading.max(0.0),
561                    byte_range: span(at, at + c.len_utf8()),
562                    format: format.clone(),
563                });
564            }
565            None => {
566                run_start.get_or_insert(at);
567            }
568        }
569    }
570    if let Some(s) = run_start {
571        job.sections.push(LayoutSection {
572            leading_space: 0.0,
573            byte_range: span(s, text.len()),
574            format,
575        });
576    }
577    job
578}
579
580fn span(from: usize, to: usize) -> std::ops::Range<egui::text::ByteIndex> {
581    egui::text::ByteIndex(from)..egui::text::ByteIndex(to)
582}
583
584/// [`number_job`] laid out.
585pub fn number_galley(ctx: &Context, text: &str, size: f32, color: Color32) -> Arc<Galley> {
586    let job = number_job(ctx, text, size, color);
587    ctx.fonts_mut(|f| f.layout_job(job))
588}
589
590/// The chars of `text` no face of `font`'s family covers, each once, in
591/// order (whitespace and control chars aside): what egui draws as a box,
592/// or panics on under `MissingGlyphPolicy::Panic` (kittest's default).
593/// Empty before egui's first pass (no fonts yet).
594pub fn uncovered(ctx: &Context, font: &FontId, text: &str) -> Vec<char> {
595    if ctx.cumulative_pass_nr() == 0 {
596        return Vec::new();
597    }
598    let mut missing: Vec<char> = Vec::new();
599    ctx.fonts_mut(|f| {
600        for c in text
601            .chars()
602            .filter(|c| !c.is_whitespace() && !c.is_control())
603        {
604            if !missing.contains(&c) && !f.has_glyph(font, c) {
605                missing.push(c);
606            }
607        }
608    });
609    missing
610}
611
612/// A label drawing `text` in `font`, the chars no face of its family
613/// covers ([`uncovered`]) drawn as boxes in the text's colour.
614///
615/// For a sample showing what a face covers, such as a [`specimen`]: its
616/// family is the face then egui's bundled fonts, never the theme's, so a
617/// letter the face lacks is shown missing rather than borrowed. egui draws
618/// the same box (the `.notdef` glyph) but panics instead under
619/// `MissingGlyphPolicy::Panic`; here a missing letter is drawn, never a
620/// panic, whatever the policy.
621pub fn sample_label(ui: &mut egui::Ui, text: &str, font: FontId) -> egui::Response {
622    let missing = uncovered(ui.ctx(), &font, text);
623    let color = ui.visuals().text_color();
624    if missing.is_empty() {
625        return ui.label(egui::RichText::new(text).font(font).color(color));
626    }
627    // Each missing char becomes a space, widened to a box's width, where
628    // the box is then drawn.
629    let size = font.size;
630    let plain = TextFormat::simple(font, color);
631    let gap = TextFormat {
632        extra_letter_spacing: size * 0.3,
633        ..plain.clone()
634    };
635    let mut job = LayoutJob::default();
636    let mut boxes: Vec<usize> = Vec::new();
637    for (i, c) in text.chars().enumerate() {
638        if missing.contains(&c) {
639            boxes.push(i);
640            job.append(" ", 0.0, gap.clone());
641        } else {
642            let mut s = [0u8; 4];
643            job.append(c.encode_utf8(&mut s), 0.0, plain.clone());
644        }
645    }
646    job.wrap.max_width = ui.available_width();
647    let galley = ui.fonts_mut(|f| f.layout_job(job));
648    let (rect, response) = ui.allocate_exact_size(galley.size(), egui::Sense::hover());
649    response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, ui.is_enabled(), text));
650    if ui.is_rect_visible(rect) {
651        let painter = ui.painter();
652        painter.galley(rect.min, galley.clone(), color);
653        let stroke = egui::Stroke::new((size / 14.0).max(1.0), color);
654        for i in boxes {
655            let at = galley.pos_from_cursor(egui::text::CCursor::new(i));
656            let next = galley.pos_from_cursor(egui::text::CCursor::new(i + 1));
657            // The next char's left edge, unless the row wraps there.
658            let right = if (next.min.y - at.min.y).abs() < 0.5 {
659                next.min.x
660            } else {
661                at.min.x + size * 0.55
662            };
663            let (w, h) = ((right - at.min.x - size * 0.15).max(size * 0.3), size * 0.7);
664            let top = at.min.y + (at.height() - h) * 0.5;
665            let r = egui::Rect::from_min_size(
666                rect.min + egui::vec2(at.min.x + size * 0.08, top),
667                egui::vec2(w, h),
668            );
669            painter.rect_stroke(r, 0.0, stroke, egui::StrokeKind::Inside);
670        }
671    }
672    response
673}
674
675/// A font face the application gives: its family name (as a theme names
676/// it), its weight and the bytes of a `.ttf` or `.otf` file.
677#[derive(Clone)]
678pub struct Face {
679    pub family: String,
680    pub weight: Weight,
681    data: Arc<FontData>,
682    origin: Origin,
683}
684
685impl Face {
686    /// A face from bytes the binary embeds.
687    pub fn from_static(family: &str, weight: Weight, bytes: &'static [u8]) -> Self {
688        Self {
689            family: family.into(),
690            weight,
691            data: Arc::new(FontData::from_static(bytes)),
692            origin: Origin::Registered,
693        }
694    }
695
696    /// A face from bytes read at run time.
697    pub fn from_owned(family: &str, weight: Weight, bytes: Vec<u8>) -> Self {
698        Self {
699            family: family.into(),
700            weight,
701            data: Arc::new(FontData::from_owned(bytes)),
702            origin: Origin::Registered,
703        }
704    }
705
706    /// Where it comes from: [`Origin::Registered`], or [`Origin::File`]
707    /// for a user's font file.
708    pub fn origin(&self) -> Origin {
709        self.origin
710    }
711
712    /// Its file's size, in bytes.
713    pub fn len(&self) -> usize {
714        self.data.bytes().len()
715    }
716
717    /// Whether its file is empty (it never draws).
718    pub fn is_empty(&self) -> bool {
719        self.data.bytes().is_empty()
720    }
721
722    /// Whether its digits `0` to `9` share one advance (tabular figures
723    /// by default); `false` when it cannot be read.
724    pub fn tabular_digits(&self) -> bool {
725        tabular_digits(&self.data)
726    }
727
728    /// Whether every glyph has the same advance (a monospace face, as
729    /// far as `i`, `W`, `m` and `0` tell).
730    pub fn monospace(&self) -> bool {
731        monospace(&self.data)
732    }
733}
734
735/// The advances of chars in a face, in font units; `None` when one is
736/// missing or the face cannot be read.
737fn advances(data: &FontData, chars: &[char]) -> Option<Vec<f32>> {
738    use skrifa::MetadataProvider as _;
739    let font = skrifa::FontRef::from_index(data.bytes(), data.index).ok()?;
740    let charmap = font.charmap();
741    let metrics = font.glyph_metrics(
742        skrifa::instance::Size::unscaled(),
743        skrifa::instance::LocationRef::default(),
744    );
745    chars
746        .iter()
747        .map(|c| charmap.map(*c).and_then(|g| metrics.advance_width(g)))
748        .collect()
749}
750
751fn same_advance(data: &FontData, chars: &[char]) -> bool {
752    advances(data, chars).is_some_and(|a| a.windows(2).all(|w| (w[0] - w[1]).abs() < 0.5))
753}
754
755/// Whether a face's default digits are tabular (one advance for `0` to
756/// `9`): egui applies no OpenType feature, so `tnum` cannot be asked.
757fn tabular_digits(data: &FontData) -> bool {
758    same_advance(data, &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
759}
760
761fn monospace(data: &FontData) -> bool {
762    same_advance(data, &['i', 'W', 'm', '0', '.'])
763}
764
765impl std::fmt::Debug for Face {
766    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
767        f.debug_struct("Face")
768            .field("family", &self.family)
769            .field("weight", &self.weight)
770            .finish_non_exhaustive()
771    }
772}
773
774/// A font file a user added: where it is, and the family and weight
775/// its tables give. What settings keep (paths, not bytes): the file is
776/// read again when registered ([`register_files`]).
777#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
778pub struct FontFile {
779    pub path: std::path::PathBuf,
780    /// The family a theme names it by (the file's typographic family,
781    /// else its family name).
782    pub family: String,
783    pub weight: Weight,
784}
785
786impl FontFile {
787    /// Reads a font file (`.ttf`, `.otf`, the first face of a `.ttc`):
788    /// checks it parses, and reads its family and weight. The bytes are
789    /// not kept.
790    pub fn read(path: &std::path::Path) -> Result<FontFile, String> {
791        let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
792        let (family, weight) = inspect(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
793        Ok(FontFile {
794            path: path.to_path_buf(),
795            family,
796            weight,
797        })
798    }
799}
800
801/// A font's family and weight, from its `name` and `OS/2` tables; an
802/// error when it does not parse as a font.
803fn inspect(bytes: &[u8]) -> Result<(String, Weight), String> {
804    use skrifa::MetadataProvider as _;
805    use skrifa::string::StringId;
806    let font = skrifa::FontRef::from_index(bytes, 0).map_err(|e| format!("not a font ({e})"))?;
807    let name = |id| {
808        font.localized_strings(id)
809            .english_or_first()
810            .map(|s| s.chars().collect::<String>())
811            .filter(|s| !s.trim().is_empty())
812    };
813    let family = name(StringId::TYPOGRAPHIC_FAMILY_NAME)
814        .or_else(|| name(StringId::FAMILY_NAME))
815        .ok_or("a font without a family name")?;
816    let weight = font.attributes().weight.value().round().clamp(1.0, 1000.0) as u16;
817    Ok((family, Weight(weight)))
818}
819
820/// Registers the faces of font files a user added (paths, as settings
821/// keep them), installed with the next theme install or [`install`]:
822/// each file is read again, checked and registered under its family
823/// and weight. A file that cannot be read or parsed is reported, and
824/// the face registered before for it, if any, stays.
825pub fn register_files(ctx: &Context, files: &[FontFile]) -> Vec<String> {
826    let mut problems = Vec::new();
827    for f in files {
828        match std::fs::read(&f.path) {
829            Ok(bytes) => match inspect(&bytes) {
830                Ok(_) => register(
831                    ctx,
832                    Face {
833                        origin: Origin::File,
834                        ..Face::from_owned(&f.family, f.weight, bytes)
835                    },
836                ),
837                Err(e) => problems.push(format!("{}: {e}", f.path.display())),
838            },
839            Err(e) => problems.push(format!("{}: {e}", f.path.display())),
840        }
841    }
842    for p in &problems {
843        log::warn!(target: "egui_pop", "fonts: {p}");
844    }
845    problems
846}
847
848/// Installs the families again with the faces registered since (after
849/// [`register_files`]), keeping the families installed; the atlas is
850/// rebuilt once, from the next pass. Nothing happens when nothing
851/// changed.
852pub fn reinstall(ctx: &Context) -> Option<Arc<Report>> {
853    let (key, _) = INSTALLED.get(ctx)?;
854    Some(install_with_offsets(ctx, &key.ui, &key.mono, key.offsets))
855}
856
857/// The egui family drawing a family by its name at a weight, outside
858/// the theme's roles: a face registered, egui's or the system's, egui's
859/// bundled fonts behind it. `None` until it is installed: the first ask
860/// installs the fonts again (one slow frame, from the next pass) and
861/// asks for a repaint; draw with another font meanwhile. A name found
862/// nowhere draws egui's bundled fonts, and is said in the [`Report`].
863///
864/// Only the face and egui's bundled fonts draw it, never the theme's: a
865/// sample shows what the face covers. Text it may not cover (other
866/// scripts, a name read from a file) goes through [`sample_label`], which
867/// draws the missing letters as boxes, or is checked with [`uncovered`]
868/// first: laid out as is, a letter no face has panics under kittest's
869/// `MissingGlyphPolicy::Panic`.
870pub fn specimen(ctx: &Context, name: &str, weight: Weight) -> Option<FontFamily> {
871    let installed = INSTALLED
872        .get(ctx)
873        .is_some_and(|(k, _)| k.specimens.iter().any(|s| s.eq_ignore_ascii_case(name)));
874    if installed {
875        // Installed, but egui takes new fonts at its next pass: asked
876        // again in the same frame, it is not drawn yet.
877        let family = specimen_family(name, weight);
878        if bound(ctx, &family) {
879            return Some(family);
880        }
881        ctx.request_repaint();
882        return None;
883    }
884    SPECIMENS.update(ctx, |s| {
885        if !s.iter().any(|x| x.eq_ignore_ascii_case(name)) {
886            s.push(name.to_string());
887        }
888    });
889    reinstall(ctx);
890    ctx.request_repaint();
891    None
892}
893
894/// Previews a role's families before they are applied: the preview
895/// families ([`preview_family`], drawn by [`with_preview`]) draw the
896/// faces found for `names` in priority order, the role's families as
897/// installed behind them (so a name found nowhere draws the role's
898/// families, never nothing), or the role's families alone with `None`. The theme's own families are
899/// untouched. Installed again at once when it changes (one slow frame,
900/// from the next pass); every install defines the preview families, so
901/// a theme switched while a preview is shown keeps it.
902pub fn set_preview(ctx: &Context, role: Role, names: Option<Vec<String>>) {
903    let at = role_index(role);
904    let mut previews = PREVIEW.get_or_default(ctx);
905    if previews[at] == names {
906        return;
907    }
908    previews[at] = names;
909    PREVIEW.set(ctx, previews);
910    reinstall(ctx);
911    ctx.request_repaint();
912}
913
914/// What a role's preview draws ([`set_preview`]): `None` for the role's
915/// families as installed.
916pub fn preview(ctx: &Context, role: Role) -> Option<Vec<String>> {
917    PREVIEW.get_or_default(ctx)[role_index(role)].clone()
918}
919
920fn role_index(role: Role) -> usize {
921    match role {
922        Role::Ui => 0,
923        Role::Mono => 1,
924    }
925}
926
927/// The egui family drawing a role's preview at a weight
928/// ([`set_preview`]); `None` until egui's fonts in use have it (before
929/// the first install's pass).
930pub fn preview_family(ctx: &Context, role: Role, weight: Weight) -> Option<FontFamily> {
931    let family = preview_family_name(role, weight);
932    bound(ctx, &family).then_some(family)
933}
934
935/// Draws `add` in a child `Ui` in the preview families ([`set_preview`]):
936/// its text styles draw the interface preview (the monospace style, the
937/// monospace one), and inside it [`shown_font_id`] and the text roles of
938/// [`crate::ui`] give the preview families too. What draws with an
939/// explicit `FontId` keeps the theme's fonts. Scopes nest; the previous
940/// state comes back when `add` returns, even when it panics.
941pub fn with_preview<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
942    struct Restore {
943        ctx: Context,
944        previous: Option<bool>,
945    }
946    impl Drop for Restore {
947        fn drop(&mut self) {
948            match self.previous.take() {
949                Some(p) => PREVIEWING.set(&self.ctx, p),
950                None => {
951                    PREVIEWING.remove(&self.ctx);
952                }
953            }
954        }
955    }
956    let ctx = ui.ctx().clone();
957    let previous = PREVIEWING.get(&ctx);
958    PREVIEWING.set(&ctx, true);
959    let _restore = Restore {
960        ctx: ctx.clone(),
961        previous,
962    };
963    ui.scope(|ui| {
964        let ui_family = preview_family(&ctx, Role::Ui, Weight::REGULAR);
965        let mono_family = preview_family(&ctx, Role::Mono, Weight::REGULAR);
966        let style = ui.style_mut();
967        for font in style.text_styles.values_mut() {
968            let family = match font.family {
969                FontFamily::Monospace => mono_family.clone(),
970                FontFamily::Proportional => ui_family.clone(),
971                FontFamily::Name(_) => None,
972            };
973            if let Some(f) = family {
974                font.family = f;
975            }
976        }
977        add(ui)
978    })
979    .inner
980}
981
982/// Whether a `Ui` drawing now is in [`with_preview`].
983pub fn previewing(ctx: &Context) -> bool {
984    PREVIEWING.get(ctx).unwrap_or(false)
985}
986
987/// The font a role's text draws at a weight and a size where it is
988/// drawn: the preview family inside [`with_preview`] (once egui has
989/// it), else [`font_id`].
990pub fn shown_font_id(ctx: &Context, role: Role, weight: Weight, size: f32) -> FontId {
991    if previewing(ctx)
992        && let Some(family) = preview_family(ctx, role, weight)
993    {
994        return FontId::new(size, family);
995    }
996    font_id(role, weight, size)
997}
998
999/// Whether egui's fonts in use have a family: asking for one they do not
1000/// have panics. `false` before egui's first pass (no fonts yet).
1001fn bound(ctx: &Context, family: &FontFamily) -> bool {
1002    ctx.cumulative_pass_nr() > 0 && ctx.fonts(|f| f.definitions().families.contains_key(family))
1003}
1004
1005fn specimen_family(name: &str, weight: Weight) -> FontFamily {
1006    FontFamily::Name(
1007        format!(
1008            "pop.specimen.{}.{}",
1009            name.to_lowercase(),
1010            weight.nearest_installed().0
1011        )
1012        .into(),
1013    )
1014}
1015
1016/// A family there is to draw with: its name (as a theme names it),
1017/// where its faces come from and whether it is monospace.
1018#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
1019pub struct FamilyInfo {
1020    pub name: String,
1021    pub origin: Origin,
1022    pub monospace: bool,
1023}
1024
1025/// The families a theme or a user may name: the bundled ones (egui-pop's
1026/// with `bundled-fonts`, then egui's), the
1027/// faces registered (the application's, then the user's files), then
1028/// the system's (feature `system-fonts`), each once. A name in several
1029/// places is listed at its first place with the origin the install
1030/// finds it at ([`origin_of`]): a registered face before the system's,
1031/// the system's before egui's.
1032pub fn families(ctx: &Context) -> Vec<FamilyInfo> {
1033    // The install's order: registered (and files), system, bundled.
1034    let rank = |o: Origin| match o {
1035        Origin::Registered | Origin::File => 0,
1036        Origin::System => 1,
1037        Origin::Bundled => 2,
1038    };
1039    let mut out: Vec<FamilyInfo> = Vec::new();
1040    let mut push = |info: FamilyInfo| match out
1041        .iter_mut()
1042        .find(|f| f.name.eq_ignore_ascii_case(&info.name))
1043    {
1044        Some(f) if rank(info.origin) < rank(f.origin) => {
1045            f.origin = info.origin;
1046            f.monospace = info.monospace;
1047        }
1048        Some(_) => {}
1049        None => out.push(info),
1050    };
1051    for f in pop_bundled() {
1052        push(FamilyInfo {
1053            name: f.family.clone(),
1054            origin: Origin::Bundled,
1055            monospace: f.monospace(),
1056        });
1057    }
1058    for (name, monospace) in [("Ubuntu", false), ("Hack", true)] {
1059        push(FamilyInfo {
1060            name: name.into(),
1061            origin: Origin::Bundled,
1062            monospace,
1063        });
1064    }
1065    let registered = REGISTERED.get_or_default(ctx);
1066    for origin in [Origin::Registered, Origin::File] {
1067        for f in registered.faces.iter().filter(|f| f.origin == origin) {
1068            push(FamilyInfo {
1069                name: f.family.clone(),
1070                origin,
1071                monospace: f.monospace(),
1072            });
1073        }
1074    }
1075    for (name, monospace) in System::get(ctx).families().iter() {
1076        push(FamilyInfo {
1077            name: name.clone(),
1078            origin: Origin::System,
1079            monospace: *monospace,
1080        });
1081    }
1082    out
1083}
1084
1085/// Where the family a theme names would be found, in the order the
1086/// install looks ([`install`]): registered, then the system's, then
1087/// the bundled faces (egui-pop's, then egui's); `Some(Origin::Bundled)` for a generic name
1088/// (`sans-serif`), `None` for a name found nowhere on this machine (its
1089/// list's next name draws).
1090pub fn origin_of(ctx: &Context, name: &str) -> Option<Origin> {
1091    if is_generic(name) {
1092        return Some(Origin::Bundled);
1093    }
1094    let registered = REGISTERED.get_or_default(ctx);
1095    if let Some(f) = registered
1096        .faces
1097        .iter()
1098        .find(|f| f.family.eq_ignore_ascii_case(name))
1099    {
1100        return Some(f.origin);
1101    }
1102    let on_system = System::get(ctx)
1103        .families()
1104        .iter()
1105        .any(|(n, _)| n.eq_ignore_ascii_case(name));
1106    if on_system {
1107        return Some(Origin::System);
1108    }
1109    if pop_bundled()
1110        .iter()
1111        .any(|f| f.family.eq_ignore_ascii_case(name))
1112    {
1113        return Some(Origin::Bundled);
1114    }
1115    FontDefinitions::default()
1116        .font_data
1117        .keys()
1118        .any(|k| bundled_key_matches(k, name))
1119        .then_some(Origin::Bundled)
1120}
1121
1122/// Whether a name is a generic one (`sans-serif`, `serif`, `monospace`,
1123/// `system-ui`, `ui-monospace`): it stands for the bundled fonts
1124/// (egui-pop's with `bundled-fonts`, else egui's), so it is always found. A list ending with one always draws.
1125pub fn is_generic(name: &str) -> bool {
1126    GENERIC.iter().any(|g| g.eq_ignore_ascii_case(name))
1127}
1128
1129/// Gives the system's fonts in this context in place of those
1130/// `system-fonts` finds (tests, so what is drawn never depends on the
1131/// machine; or an application finding fonts its own way): the faces,
1132/// their family as a theme names it. `None` goes back to the system's.
1133/// Installed with the next theme install, or at once with [`reinstall`].
1134pub fn set_system_faces(ctx: &Context, faces: Option<Vec<Face>>) {
1135    static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1136    match faces {
1137        None => {
1138            SYSTEM.remove(ctx);
1139        }
1140        Some(faces) => {
1141            let faces: Vec<Face> = faces
1142                .into_iter()
1143                .map(|f| Face {
1144                    origin: Origin::System,
1145                    ..f
1146                })
1147                .collect();
1148            let mut families: Vec<(String, bool)> = Vec::new();
1149            for f in &faces {
1150                if !families
1151                    .iter()
1152                    .any(|(n, _)| n.eq_ignore_ascii_case(&f.family))
1153                {
1154                    families.push((f.family.clone(), f.monospace()));
1155                }
1156            }
1157            families.sort_by_key(|(n, _)| n.to_lowercase());
1158            SYSTEM.set(
1159                ctx,
1160                SystemList {
1161                    faces: faces.into(),
1162                    families: families.into(),
1163                    generation: GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
1164                },
1165            );
1166        }
1167    }
1168}
1169
1170/// The faces registered, in order: the application's and the user's
1171/// files.
1172pub fn registered(ctx: &Context) -> Vec<Face> {
1173    REGISTERED.get_or_default(ctx).faces
1174}
1175
1176/// The families installed last: `font.family.ui` and `font.family.mono`
1177/// as asked.
1178pub fn installed_families(ctx: &Context) -> Option<(Vec<String>, Vec<String>)> {
1179    INSTALLED.get(ctx).map(|(k, _)| (k.ui, k.mono))
1180}
1181
1182/// What [`install`] did: the face each family starts with, and what it
1183/// could not do.
1184#[derive(Clone, Debug, Default, PartialEq)]
1185pub struct Report {
1186    /// Per egui family (`pop.ui.700`): the face drawn first, as
1187    /// "Family weight (source)", or `None` for egui's bundled fonts.
1188    pub primary: Vec<(String, Option<String>)>,
1189    /// Per egui family, the faces it falls back through, in order (keys
1190    /// of egui's font definitions): the roles', the preview families'
1191    /// (`pop.preview.ui.400`) and the specimens'.
1192    pub chains: Vec<(String, Vec<String>)>,
1193    /// Per role (`ui`, `mono`): whether the face drawing its regular
1194    /// weight has tabular digits by default.
1195    pub tabular: Vec<(String, bool)>,
1196    /// The names drawn as specimens ([`specimen`]).
1197    pub specimens: Vec<String>,
1198    /// Where each name of the roles' lists and of the specimens was
1199    /// found, at the regular weight, in list order.
1200    pub resolved: Vec<Resolved>,
1201    pub problems: Vec<String>,
1202}
1203
1204/// Where a family name was found by an install: so a theme author sees
1205/// `Ubuntu → bundled Ubuntu-Light` where the system has no Ubuntu.
1206#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
1207pub struct Resolved {
1208    /// The list it is in: `ui`, `mono` or `specimen`.
1209    pub list: String,
1210    /// The name as the list gives it.
1211    pub name: String,
1212    /// Where its face comes from; `None` for a name found nowhere. A
1213    /// generic name (`sans-serif`) is egui's bundled fonts.
1214    pub origin: Option<Origin>,
1215    /// The face drawn: egui's key for a bundled one (`Ubuntu-Light`),
1216    /// the PostScript name for a system one when it has one, else its
1217    /// family and weight (`Inter 400`); `None` for a generic name or a
1218    /// name found nowhere.
1219    pub face: Option<String>,
1220}
1221
1222impl std::fmt::Display for Resolved {
1223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1224        match (self.origin, &self.face) {
1225            (Some(o), Some(face)) => write!(f, "{} → {} {face}", self.name, o.name()),
1226            (Some(o), None) => write!(f, "{} → {}", self.name, o.name()),
1227            (None, _) => write!(f, "{} → missing", self.name),
1228        }
1229    }
1230}
1231
1232impl Report {
1233    /// Where a name of a list (`ui`, `mono` or `specimen`) was found.
1234    pub fn resolved(&self, list: &str, name: &str) -> Option<&Resolved> {
1235        self.resolved
1236            .iter()
1237            .find(|r| r.list == list && r.name.eq_ignore_ascii_case(name))
1238    }
1239
1240    /// Whether the face drawing a role's regular text has tabular
1241    /// digits by default (one advance for `0` to `9`).
1242    pub fn tabular_digits(&self, role: Role) -> bool {
1243        self.tabular.iter().any(|(r, t)| r == role.key() && *t)
1244    }
1245}
1246
1247#[derive(Clone, Default)]
1248struct Registered {
1249    faces: Vec<Face>,
1250    generation: u64,
1251}
1252
1253/// The faces registered for the next install.
1254const REGISTERED: Slot<Registered> = Slot::opaque("core.fonts.registered");
1255/// The names asked as specimens.
1256const SPECIMENS: Slot<Vec<String>> = Slot::opaque("core.fonts.specimens");
1257/// What the last install was asked, and its report.
1258const INSTALLED: Slot<(Key, Arc<Report>)> = Slot::opaque("core.fonts.installed");
1259/// The families each role's preview draws ([`set_preview`]), by role.
1260const PREVIEW: Slot<Previews> = Slot::opaque("core.fonts.preview");
1261/// The system's fonts given in place of fontdb's ([`set_system_faces`]).
1262const SYSTEM: Slot<SystemList> = Slot::opaque("core.fonts.system");
1263/// Whether a `Ui` draws in the preview families ([`with_preview`]).
1264const PREVIEWING: Slot<bool> = Slot::opaque("core.fonts.previewing");
1265
1266/// What each role's preview draws: `[ui, mono]`, `None` for the role's
1267/// families as installed.
1268type Previews = [Option<Vec<String>>; 2];
1269
1270/// Faces given as the system's ([`set_system_faces`]).
1271#[derive(Clone)]
1272struct SystemList {
1273    faces: Arc<[Face]>,
1274    /// Each family once, sorted, with whether it is monospace.
1275    families: Arc<[(String, bool)]>,
1276    generation: u64,
1277}
1278
1279/// Registers a face for the families a theme names; installed with the
1280/// next theme install. A face of the same family and weight is replaced.
1281pub fn register(ctx: &Context, face: Face) {
1282    REGISTERED.update(ctx, |r| {
1283        r.faces
1284            .retain(|f| !(f.family.eq_ignore_ascii_case(&face.family) && f.weight == face.weight));
1285        r.faces.push(face);
1286        r.generation += 1;
1287    });
1288}
1289
1290/// The faces drawing each role's regular text, as installed last.
1291const FACES: Slot<Arc<[Vec<InstalledFace>; 2]>> = Slot::opaque("core.fonts.faces");
1292
1293/// A face drawing a role's text, as installed: the family the theme
1294/// names it by (`None` for egui's bundled faces behind the theme's),
1295/// and its file.
1296#[derive(Clone, Debug, PartialEq)]
1297pub struct InstalledFace {
1298    pub family: Option<String>,
1299    pub data: Arc<FontData>,
1300}
1301
1302/// The faces drawing a role's regular text, as installed last, in
1303/// order: the theme's families found (registered, egui's or the
1304/// system's), then egui's bundled faces behind them. For a renderer
1305/// outside egui (an SVG rasteriser, a PDF writer) to draw the same text
1306/// as the screen. `None` before the first install.
1307pub fn installed_faces(ctx: &Context, role: Role) -> Option<Vec<InstalledFace>> {
1308    FACES.get(ctx).map(|f| f[role as usize].clone())
1309}
1310
1311/// The last install's report.
1312pub fn report(ctx: &Context) -> Option<Arc<Report>> {
1313    INSTALLED.get(ctx).map(|(_, r)| r)
1314}
1315
1316#[derive(Clone, PartialEq)]
1317struct Key {
1318    ui: Vec<String>,
1319    mono: Vec<String>,
1320    specimens: Vec<String>,
1321    preview: Previews,
1322    generation: u64,
1323    /// The faces given as the system's ([`set_system_faces`]), 0 for
1324    /// the system's own.
1325    system: u64,
1326    offsets: BaselineOffsets,
1327}
1328
1329const GENERIC: [&str; 5] = [
1330    "sans-serif",
1331    "serif",
1332    "monospace",
1333    "system-ui",
1334    "ui-monospace",
1335];
1336
1337/// Installs the families named by the theme's tokens, with the
1338/// registered faces, unless they are already installed. In use from the
1339/// next pass. The icon font (`icon::install`) is kept, and so are the
1340/// baseline offsets installed last ([`install_with_offsets`]; none at
1341/// first).
1342pub fn install(ctx: &Context, ui: &[String], mono: &[String]) -> Arc<Report> {
1343    let offsets = INSTALLED
1344        .get(ctx)
1345        .map(|(k, _)| k.offsets)
1346        .unwrap_or_default();
1347    install_with_offsets(ctx, ui, mono, offsets)
1348}
1349
1350/// [`install`], each role's glyphs drawn `offsets` of their size lower
1351/// ([`BaselineOffsets`]): what the theme's `font.baseline-offset.*`
1352/// tokens give.
1353pub fn install_with_offsets(
1354    ctx: &Context,
1355    ui: &[String],
1356    mono: &[String],
1357    offsets: BaselineOffsets,
1358) -> Arc<Report> {
1359    let registered = REGISTERED.get_or_default(ctx);
1360    let specimens = SPECIMENS.get_or_default(ctx);
1361    let preview = PREVIEW.get_or_default(ctx);
1362    let system = System::get(ctx);
1363    let key = Key {
1364        ui: ui.to_vec(),
1365        mono: mono.to_vec(),
1366        specimens: specimens.clone(),
1367        preview: preview.clone(),
1368        generation: registered.generation,
1369        system: system.generation(),
1370        offsets,
1371    };
1372    if let Some((k, report)) = INSTALLED.get(ctx)
1373        && k == key
1374    {
1375        return report;
1376    }
1377    let (mut defs, mut report, drawing) =
1378        definitions_and_faces(&registered.faces, ui, mono, &preview, &system, offsets);
1379    add_specimens(
1380        &mut defs,
1381        &mut report,
1382        &registered.faces,
1383        &specimens,
1384        &system,
1385    );
1386    for p in &report.problems {
1387        log::warn!(target: "egui_pop", "fonts: {p}");
1388    }
1389    ctx.set_fonts(defs);
1390    let report = Arc::new(report);
1391    INSTALLED.set(ctx, (key, report.clone()));
1392    FACES.set(ctx, Arc::new(drawing));
1393    report
1394}
1395
1396/// A face found for a name at a weight: its key in the definitions, its
1397/// data, the weight it has, where it came from and the face it is, as
1398/// reports name it (`Ubuntu-Light`, `Inter 400`).
1399struct Found {
1400    key: String,
1401    data: Arc<FontData>,
1402    weight: Weight,
1403    origin: Origin,
1404    face: String,
1405}
1406
1407/// Whether a key of egui's bundled faces is a family's: the family itself
1408/// (`Hack`) or one of its styles (`Ubuntu-Light`).
1409fn bundled_key_matches(key: &str, name: &str) -> bool {
1410    let (k, lower) = (key.to_ascii_lowercase(), name.to_ascii_lowercase());
1411    k == lower
1412        || k.strip_prefix(&lower)
1413            .is_some_and(|rest| rest.starts_with('-'))
1414}
1415
1416fn find(
1417    name: &str,
1418    weight: Weight,
1419    faces: &[Face],
1420    bundled: &std::collections::BTreeMap<String, Arc<FontData>>,
1421    system: &System,
1422) -> Option<Found> {
1423    if let Some(found) = among(faces, name, weight) {
1424        return Some(found);
1425    }
1426    // The system's before the bundled ones: a theme naming `Ubuntu` gets
1427    // the system's Ubuntu where it is installed, as the platform would.
1428    if let Some(found) = system.find(name, weight) {
1429        return Some(on_axis(found, weight));
1430    }
1431    if let Some(found) = among(pop_bundled(), name, weight) {
1432        return Some(found);
1433    }
1434    // egui's faces have one weight each: the others draw it.
1435    let (key, data) = bundled.iter().find(|(k, _)| bundled_key_matches(k, name))?;
1436    Some(Found {
1437        key: key.clone(),
1438        data: data.clone(),
1439        weight,
1440        origin: Origin::Bundled,
1441        face: key.clone(),
1442    })
1443}
1444
1445/// The face of a family among `faces` nearest `weight`, drawn at
1446/// `weight` through its axis when it has one.
1447fn among(faces: &[Face], name: &str, weight: Weight) -> Option<Found> {
1448    let own: Vec<&Face> = faces
1449        .iter()
1450        .filter(|f| f.family.eq_ignore_ascii_case(name))
1451        .collect();
1452    let w = nearest(weight, own.iter().map(|f| f.weight))?;
1453    let face = own.iter().find(|f| f.weight == w)?;
1454    let key = match face.origin {
1455        Origin::Bundled => format!("pop:{}:{}:bundled", face.family, w.0),
1456        _ => format!("pop:{}:{}", face.family, w.0),
1457    };
1458    Some(on_axis(
1459        Found {
1460            key,
1461            data: face.data.clone(),
1462            weight: w,
1463            origin: face.origin,
1464            face: format!("{} {}", face.family, w.0),
1465        },
1466        weight,
1467    ))
1468}
1469
1470/// The bundled face a generic name draws at a weight ([`generic_family`]):
1471/// `None` without `bundled-fonts`.
1472fn generic_face(name: &str, weight: Weight) -> Option<(&'static str, Found)> {
1473    let family = generic_family(name)?;
1474    among(pop_bundled(), family, weight).map(|found| (family, found))
1475}
1476
1477/// A face drawn at `weight` through its `wght` axis when it has one that
1478/// covers it and is not already at that weight: the same bytes, with the
1479/// axis set on the face, under a key of their own. Owned bytes are
1480/// copied per weight (`FontData` holds them in a `Cow`), at install only.
1481fn on_axis(found: Found, weight: Weight) -> Found {
1482    if found.weight == weight {
1483        return found;
1484    }
1485    let target = f32::from(weight.0);
1486    let covers = found
1487        .data
1488        .variation_axes()
1489        .iter()
1490        .any(|a| a.tag.to_be_bytes() == *b"wght" && a.range.contains(target));
1491    if !covers {
1492        return found;
1493    }
1494    let mut data = (*found.data).clone();
1495    data.tweak.coords.push(b"wght", target);
1496    Found {
1497        key: format!("{}@wght{}", found.key, weight.0),
1498        data: Arc::new(data),
1499        weight,
1500        origin: found.origin,
1501        face: found.face,
1502    }
1503}
1504
1505fn nearest(weight: Weight, among: impl Iterator<Item = Weight>) -> Option<Weight> {
1506    // CSS's rule, simplified: the closest, the heavier one on a tie.
1507    among.min_by_key(|w| (w.0.abs_diff(weight.0), std::cmp::Reverse(w.0)))
1508}
1509
1510/// A chain of faces at a weight: the faces found for `names` (generic
1511/// ones skipped), in order, each added to `defs`.
1512struct Chain {
1513    keys: Vec<String>,
1514    /// The name each key was found by, in the same order.
1515    names: Vec<String>,
1516    /// The first face found: the name it was found by (the bundled
1517    /// family for a generic name), its weight and where it came from.
1518    first: Option<(String, Weight, Origin)>,
1519    /// Whether the first face was found by a generic name: it draws
1520    /// what the bundled fonts have, its weight said by no problem.
1521    first_generic: bool,
1522    /// The names found nowhere.
1523    missing: Vec<String>,
1524    /// Each name of the list, in order, with where it was found and the
1525    /// face (generic ones too).
1526    resolved: Vec<(String, Option<Origin>, Option<String>)>,
1527}
1528
1529fn chain_at(
1530    defs: &mut FontDefinitions,
1531    names: &[String],
1532    weight: Weight,
1533    faces: &[Face],
1534    bundled: &std::collections::BTreeMap<String, Arc<FontData>>,
1535    system: &System,
1536) -> Chain {
1537    let mut chain = Chain {
1538        keys: Vec::new(),
1539        names: Vec::new(),
1540        first: None,
1541        first_generic: false,
1542        missing: Vec::new(),
1543        resolved: Vec::new(),
1544    };
1545    for name in names {
1546        if is_generic(name) {
1547            // The bundled family it stands for, unless the list found
1548            // that family already (`Inter` installed, then `sans-serif`).
1549            let found = generic_face(name, weight)
1550                .filter(|(family, _)| !chain.names.iter().any(|n| n.eq_ignore_ascii_case(family)));
1551            let Some((family, found)) = found else {
1552                chain
1553                    .resolved
1554                    .push((name.clone(), Some(Origin::Bundled), None));
1555                continue;
1556            };
1557            chain
1558                .resolved
1559                .push((name.clone(), Some(found.origin), Some(found.face.clone())));
1560            if chain.first.is_none() {
1561                chain.first = Some((family.to_string(), found.weight, found.origin));
1562                chain.first_generic = true;
1563            }
1564            defs.font_data
1565                .entry(found.key.clone())
1566                .or_insert(found.data);
1567            if !chain.keys.contains(&found.key) {
1568                chain.keys.push(found.key);
1569                chain.names.push(family.to_string());
1570            }
1571            continue;
1572        }
1573        let Some(found) = find(name, weight, faces, bundled, system) else {
1574            chain.missing.push(name.clone());
1575            chain.resolved.push((name.clone(), None, None));
1576            continue;
1577        };
1578        chain
1579            .resolved
1580            .push((name.clone(), Some(found.origin), Some(found.face.clone())));
1581        if chain.first.is_none() {
1582            chain.first = Some((name.clone(), found.weight, found.origin));
1583        }
1584        defs.font_data
1585            .entry(found.key.clone())
1586            .or_insert(found.data);
1587        if !chain.keys.contains(&found.key) {
1588            chain.keys.push(found.key);
1589            chain.names.push(name.clone());
1590        }
1591    }
1592    chain
1593}
1594
1595/// The egui family a role's preview draws at a weight
1596/// (`pop.preview.ui.400`): defined by every install ([`set_preview`]).
1597fn preview_family_name(role: Role, weight: Weight) -> FontFamily {
1598    FontFamily::Name(
1599        format!(
1600            "pop.preview.{}.{}",
1601            role.key(),
1602            weight.nearest_installed().0
1603        )
1604        .into(),
1605    )
1606}
1607
1608/// A chain's faces drawn `offset` of their size lower: each face under a
1609/// key of its own (`<key>@y<offset>`), the same bytes with the offset
1610/// added to its tweak, so a face both roles share moves for one only.
1611/// The keys unchanged at 0.
1612fn offset_keys(defs: &mut FontDefinitions, keys: Vec<String>, offset: f32) -> Vec<String> {
1613    if offset == 0.0 {
1614        return keys;
1615    }
1616    keys.into_iter()
1617        .map(|k| {
1618            let moved = format!("{k}@y{offset}");
1619            if !defs.font_data.contains_key(&moved) {
1620                let Some(data) = defs.font_data.get(&k) else {
1621                    return k;
1622                };
1623                let mut data = (**data).clone();
1624                data.tweak.y_offset_factor += offset;
1625                defs.font_data.insert(moved.clone(), Arc::new(data));
1626            }
1627            moved
1628        })
1629        .collect()
1630}
1631
1632/// Adds faces to a chain, each once: a face already in it (egui's
1633/// Ubuntu named by the theme, then reached again through `sans-serif`)
1634/// keeps its first place, so egui never gets the same face twice in a
1635/// family.
1636fn extend_unique(chain: &mut Vec<String>, more: &[String]) {
1637    for k in more {
1638        if !chain.contains(k) {
1639            chain.push(k.clone());
1640        }
1641    }
1642}
1643
1644#[cfg(test)]
1645fn definitions(
1646    faces: &[Face],
1647    ui: &[String],
1648    mono: &[String],
1649    preview: &Previews,
1650    system: &System,
1651) -> (FontDefinitions, Report) {
1652    let (defs, report, _) =
1653        definitions_and_faces(faces, ui, mono, preview, system, BaselineOffsets::default());
1654    (defs, report)
1655}
1656
1657/// [`definitions`], with the faces drawing each role's regular text
1658/// ([`installed_faces`]), `ui` then `mono`.
1659fn definitions_and_faces(
1660    faces: &[Face],
1661    ui: &[String],
1662    mono: &[String],
1663    preview: &Previews,
1664    system: &System,
1665    offsets: BaselineOffsets,
1666) -> (FontDefinitions, Report, [Vec<InstalledFace>; 2]) {
1667    let mut drawing: [Vec<InstalledFace>; 2] = Default::default();
1668    let mut defs = FontDefinitions::default();
1669    let bundled_faces = defs.font_data.clone();
1670    crate::icon::insert(&mut defs);
1671    let bundled = |f: &FontFamily| defs.families.get(f).cloned().unwrap_or_default();
1672    let bundled_ui = bundled(&FontFamily::Proportional);
1673    let bundled_mono = bundled(&FontFamily::Monospace);
1674    let mut report = Report::default();
1675    for (at, role) in Role::ALL.into_iter().enumerate() {
1676        let (names, tail) = match role {
1677            Role::Ui => (ui, &bundled_ui),
1678            Role::Mono => (mono, &bundled_mono),
1679        };
1680        let mut missing: Vec<String> = Vec::new();
1681        for weight in WEIGHTS {
1682            let found = chain_at(&mut defs, names, weight, faces, &bundled_faces, system);
1683            let mut primary = None;
1684            if let Some((name, w, origin)) = &found.first {
1685                primary = Some(format!("{name} {} ({})", w.0, origin.name()));
1686                if *w != weight && !found.first_generic {
1687                    report.problems.push(format!(
1688                        "{}: {name} has no weight {}, {} is drawn",
1689                        role.token(),
1690                        weight.0,
1691                        w.0
1692                    ));
1693                }
1694            }
1695            let named = found.names;
1696            let mut chain = found.keys;
1697            if weight == Weight::REGULAR {
1698                missing = found.missing;
1699                report
1700                    .resolved
1701                    .extend(
1702                        found
1703                            .resolved
1704                            .into_iter()
1705                            .map(|(name, origin, face)| Resolved {
1706                                list: role.key().to_string(),
1707                                name,
1708                                origin,
1709                                face,
1710                            }),
1711                    );
1712                // The face drawing the digits: the first of the chain.
1713                let first = chain.first().or(tail.first());
1714                let tabular = first
1715                    .and_then(|k| defs.font_data.get(k))
1716                    .is_some_and(|d| tabular_digits(d));
1717                report.tabular.push((role.key().to_string(), tabular));
1718            }
1719            let theirs = chain.len();
1720            extend_unique(&mut chain, tail);
1721            if weight == Weight::REGULAR {
1722                // What egui draws the role's regular text with: the same
1723                // chain, each face once, the theme's by the name they
1724                // were found by, then egui's bundled ones.
1725                for (i, key) in chain.iter().enumerate() {
1726                    if let Some(data) = defs.font_data.get(key) {
1727                        drawing[at].push(InstalledFace {
1728                            family: (i < theirs).then(|| named[i].clone()),
1729                            data: data.clone(),
1730                        });
1731                    }
1732                }
1733            }
1734            let offset = offsets.get(role);
1735            let chain = offset_keys(&mut defs, chain, offset);
1736            let fam = family(role, weight);
1737            if let FontFamily::Name(n) = &fam {
1738                report.primary.push((n.to_string(), primary));
1739                report.chains.push((n.to_string(), chain.clone()));
1740            }
1741            if weight == Weight::REGULAR {
1742                let egui_family = match role {
1743                    Role::Ui => FontFamily::Proportional,
1744                    Role::Mono => FontFamily::Monospace,
1745                };
1746                defs.families.insert(egui_family, chain.clone());
1747            }
1748            // The preview family: the preview's faces before the role's
1749            // chain (its fallbacks), or the role's chain alone when the
1750            // preview finds no face (names unknown here, generic ones):
1751            // never empty, never less than what the role draws.
1752            let previewed = match &preview[at] {
1753                Some(list) => {
1754                    let c = chain_at(&mut defs, list, weight, faces, &bundled_faces, system).keys;
1755                    let mut c = offset_keys(&mut defs, c, offset);
1756                    extend_unique(&mut c, &chain);
1757                    c
1758                }
1759                None => chain.clone(),
1760            };
1761            let pf = preview_family_name(role, weight);
1762            if let FontFamily::Name(n) = &pf {
1763                report.chains.push((n.to_string(), previewed.clone()));
1764            }
1765            defs.families.insert(pf, previewed);
1766            defs.families.insert(fam, chain);
1767        }
1768        for name in missing {
1769            report.problems.push(format!(
1770                "{}: no font named {name} (registered{})",
1771                role.token(),
1772                if cfg!(feature = "system-fonts") {
1773                    " or on the system"
1774                } else {
1775                    "; the system's fonts need the system-fonts feature"
1776                }
1777            ));
1778        }
1779    }
1780    (defs, report, drawing)
1781}
1782
1783/// Adds a family per specimen name and weight: the face found for the
1784/// name, egui's bundled proportional fonts behind it.
1785fn add_specimens(
1786    defs: &mut FontDefinitions,
1787    report: &mut Report,
1788    faces: &[Face],
1789    names: &[String],
1790    system: &System,
1791) {
1792    let bundled_faces = FontDefinitions::default().font_data;
1793    let tail = defs
1794        .families
1795        .get(&FontFamily::Proportional)
1796        .cloned()
1797        .unwrap_or_default();
1798    // egui's own tail, not the theme's faces in front of it.
1799    let egui_tail: Vec<String> = FontDefinitions::default()
1800        .families
1801        .get(&FontFamily::Proportional)
1802        .cloned()
1803        .unwrap_or_default();
1804    let tail: Vec<String> = tail.into_iter().filter(|k| egui_tail.contains(k)).collect();
1805    for name in names {
1806        let mut found_any = false;
1807        for weight in WEIGHTS {
1808            let mut chain = Vec::new();
1809            let found = (!is_generic(name))
1810                .then(|| find(name, weight, faces, &bundled_faces, system))
1811                .flatten();
1812            if weight == Weight::REGULAR {
1813                report.resolved.push(Resolved {
1814                    list: "specimen".into(),
1815                    name: name.clone(),
1816                    origin: match &found {
1817                        Some(f) => Some(f.origin),
1818                        None if is_generic(name) => Some(Origin::Bundled),
1819                        None => None,
1820                    },
1821                    face: found.as_ref().map(|f| f.face.clone()),
1822                });
1823            }
1824            if let Some(found) = found {
1825                found_any = true;
1826                defs.font_data
1827                    .entry(found.key.clone())
1828                    .or_insert(found.data);
1829                chain.push(found.key);
1830            }
1831            extend_unique(&mut chain, &tail);
1832            let fam = specimen_family(name, weight);
1833            if let FontFamily::Name(n) = &fam {
1834                report.chains.push((n.to_string(), chain.clone()));
1835            }
1836            defs.families.insert(fam, chain);
1837        }
1838        if !found_any && !is_generic(name) {
1839            report
1840                .problems
1841                .push(format!("specimen: no font named {name}"));
1842        }
1843        report.specimens.push(name.clone());
1844    }
1845}
1846
1847/// The system's fonts: fontdb's, read once per process (feature
1848/// `system-fonts`), or the faces given in their place in a context
1849/// ([`set_system_faces`]).
1850enum System {
1851    #[cfg(feature = "system-fonts")]
1852    Db(&'static fontdb::Database),
1853    Given(SystemList),
1854    /// No system fonts: without `system-fonts`, and in unit tests.
1855    #[cfg_attr(
1856        feature = "system-fonts",
1857        allow(dead_code, reason = "with system-fonts, only unit tests build it")
1858    )]
1859    None,
1860}
1861
1862impl System {
1863    fn get(ctx: &Context) -> Self {
1864        if let Some(given) = SYSTEM.get(ctx) {
1865            return System::Given(given);
1866        }
1867        Self::own()
1868    }
1869
1870    #[cfg(feature = "system-fonts")]
1871    fn own() -> Self {
1872        static DB: std::sync::OnceLock<fontdb::Database> = std::sync::OnceLock::new();
1873        System::Db(DB.get_or_init(|| {
1874            let mut db = fontdb::Database::new();
1875            db.load_system_fonts();
1876            db
1877        }))
1878    }
1879
1880    #[cfg(not(feature = "system-fonts"))]
1881    fn own() -> Self {
1882        System::None
1883    }
1884
1885    /// No system fonts (tests: what is drawn never depends on the
1886    /// machine).
1887    #[cfg(test)]
1888    fn none() -> Self {
1889        System::None
1890    }
1891
1892    /// What an install compares: the faces given, or 0 for the system's.
1893    fn generation(&self) -> u64 {
1894        match self {
1895            System::Given(l) => l.generation,
1896            _ => 0,
1897        }
1898    }
1899
1900    fn find(&self, name: &str, weight: Weight) -> Option<Found> {
1901        match self {
1902            #[cfg(feature = "system-fonts")]
1903            System::Db(db) => {
1904                let id = db.query(&fontdb::Query {
1905                    families: &[fontdb::Family::Name(name)],
1906                    weight: fontdb::Weight(weight.0),
1907                    ..fontdb::Query::default()
1908                })?;
1909                let info = db.face(id)?;
1910                let w = Weight(info.weight.0);
1911                let data = db.with_face_data(id, |bytes, index| {
1912                    let mut data = FontData::from_owned(bytes.to_vec());
1913                    data.index = index;
1914                    data
1915                })?;
1916                Some(Found {
1917                    key: format!("pop:{name}:{}:system", w.0),
1918                    data: Arc::new(data),
1919                    weight: w,
1920                    origin: Origin::System,
1921                    face: if info.post_script_name.is_empty() {
1922                        format!("{name} {}", w.0)
1923                    } else {
1924                        info.post_script_name.clone()
1925                    },
1926                })
1927            }
1928            System::Given(list) => {
1929                let own: Vec<&Face> = list
1930                    .faces
1931                    .iter()
1932                    .filter(|f| f.family.eq_ignore_ascii_case(name))
1933                    .collect();
1934                let w = nearest(weight, own.iter().map(|f| f.weight))?;
1935                let face = own.iter().find(|f| f.weight == w)?;
1936                Some(Found {
1937                    key: format!("pop:{}:{}:system", face.family, w.0),
1938                    data: face.data.clone(),
1939                    weight: w,
1940                    origin: Origin::System,
1941                    face: format!("{} {}", face.family, w.0),
1942                })
1943            }
1944            System::None => {
1945                let _ = (name, weight);
1946                None
1947            }
1948        }
1949    }
1950
1951    /// The system's families, each once, sorted, with whether it is
1952    /// monospace.
1953    fn families(&self) -> Arc<[(String, bool)]> {
1954        match self {
1955            #[cfg(feature = "system-fonts")]
1956            System::Db(db) => {
1957                static LIST: std::sync::OnceLock<Arc<[(String, bool)]>> =
1958                    std::sync::OnceLock::new();
1959                LIST.get_or_init(|| {
1960                    let mut out: Vec<(String, bool)> = Vec::new();
1961                    for face in db.faces() {
1962                        let Some((name, _)) = face.families.first() else {
1963                            continue;
1964                        };
1965                        if !out.iter().any(|(n, _)| n == name) {
1966                            out.push((name.clone(), face.monospaced));
1967                        }
1968                    }
1969                    out.sort_by_key(|(n, _)| n.to_lowercase());
1970                    out.into()
1971                })
1972                .clone()
1973            }
1974            System::Given(list) => list.families.clone(),
1975            System::None => Arc::from(Vec::new()),
1976        }
1977    }
1978}
1979
1980#[cfg(test)]
1981mod tests {
1982    use super::*;
1983
1984    static FAKE: &[u8] = b"not a real font, never rasterised here";
1985
1986    fn names(list: &[&str]) -> Vec<String> {
1987        list.iter().map(|s| s.to_string()).collect()
1988    }
1989
1990    #[test]
1991    fn a_step_of_the_scale_gives_its_size_and_egui_styles_sit_on_steps() {
1992        let t = crate::theme::Tokens::default();
1993        let sizes: Vec<f32> = Step::ALL.iter().map(|s| t.font.scale.get(*s)).collect();
1994        assert!(sizes.windows(2).all(|w| w[0] < w[1]), "{sizes:?}");
1995        let f = font_at(&t, Role::Mono, Weight::BOLD, Step::L);
1996        assert_eq!(f.size, t.font.scale.l);
1997        assert_eq!(f.family, family(Role::Mono, Weight::BOLD));
1998        assert_eq!(Step::Xl.token(), format!("font.size.{}", Step::Xl.name()));
1999        // egui's text styles are steps of the scale.
2000        assert_eq!(t.font.small, t.font.scale.xs);
2001        assert_eq!(t.font.body, t.font.scale.m);
2002        assert_eq!(t.font.button, t.font.scale.m);
2003        assert_eq!(t.font.heading, t.font.scale.xl);
2004        assert_eq!(t.font.mono, t.font.scale.s);
2005        let style = crate::theme::style(&t, &egui::Style::default());
2006        assert_eq!(
2007            style.text_styles[&egui::TextStyle::Button].size,
2008            t.font.button
2009        );
2010    }
2011
2012    #[test]
2013    fn registered_faces_lead_their_families_at_each_weight() {
2014        let faces = vec![
2015            Face::from_static("Inter", Weight::REGULAR, FAKE),
2016            Face::from_static("Inter", Weight::BOLD, FAKE),
2017        ];
2018        let (defs, report) = definitions(
2019            &faces,
2020            &names(&["Inter", "sans-serif"]),
2021            &names(&["monospace"]),
2022            &Previews::default(),
2023            &System::none(),
2024        );
2025        let bold = &defs.families[&family(Role::Ui, Weight::BOLD)];
2026        assert_eq!(bold[0], "pop:Inter:700");
2027        let regular = &defs.families[&FontFamily::Proportional];
2028        assert_eq!(regular[0], "pop:Inter:400");
2029        // Semibold takes the nearest, the heavier on a tie: bold.
2030        let semi = &defs.families[&family(Role::Ui, Weight::SEMIBOLD)];
2031        assert_eq!(semi[0], "pop:Inter:700");
2032        assert!(
2033            report
2034                .problems
2035                .iter()
2036                .any(|p| p.contains("no weight 600, 700")),
2037            "{report:?}"
2038        );
2039        // A generic name is the bundled fonts: no problem said.
2040        assert!(!report.problems.iter().any(|p| p.contains("monospace")));
2041    }
2042
2043    static INTER_VAR: &[u8] = include_bytes!("../tests/fonts/InterVariable-subset.ttf");
2044
2045    #[test]
2046    fn a_variable_face_serves_every_weight_through_its_axis() {
2047        let faces = vec![Face::from_static("Inter", Weight::REGULAR, INTER_VAR)];
2048        let (defs, report) = definitions(
2049            &faces,
2050            &names(&["Inter"]),
2051            &[],
2052            &Previews::default(),
2053            &System::none(),
2054        );
2055        assert!(report.problems.is_empty(), "{report:?}");
2056        assert_eq!(defs.families[&FontFamily::Proportional][0], "pop:Inter:400");
2057        let bold = &defs.families[&family(Role::Ui, Weight::BOLD)][0];
2058        assert_eq!(bold, "pop:Inter:400@wght700");
2059        assert!(format!("{:?}", defs.font_data[bold].tweak.coords).contains("700"));
2060    }
2061
2062    #[test]
2063    fn a_variable_face_draws_heavier_at_a_heavier_weight() {
2064        let ctx = Context::default();
2065        register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2066        install(&ctx, &names(&["Inter"]), &[]);
2067        // Fonts change at the next pass.
2068        ctx.run_ui(egui::RawInput::default(), |_| {})
2069            .textures_delta
2070            .clear();
2071        let width = |w: Weight| {
2072            ctx.fonts_mut(|f| {
2073                f.layout_no_wrap(
2074                    "Hamburgefonstiv".into(),
2075                    font_id(Role::Ui, w, 20.0),
2076                    egui::Color32::WHITE,
2077                )
2078                .size()
2079                .x
2080            })
2081        };
2082        let (regular, bold) = (width(Weight::REGULAR), width(Weight::BOLD));
2083        assert!(bold > regular + 1.0, "regular {regular}, bold {bold}");
2084    }
2085
2086    #[test]
2087    fn a_static_face_keeps_its_weight() {
2088        // Hack has no axis: asked at 700, it stays itself (and says so).
2089        let hack = FontDefinitions::default().font_data["Hack"].clone();
2090        let found = on_axis(
2091            Found {
2092                key: "Hack".into(),
2093                data: hack,
2094                weight: Weight::REGULAR,
2095                origin: Origin::Bundled,
2096                face: "Hack".into(),
2097            },
2098            Weight::BOLD,
2099        );
2100        assert_eq!(found.key, "Hack");
2101        assert_eq!(found.weight, Weight::REGULAR);
2102    }
2103
2104    #[test]
2105    fn a_family_found_nowhere_is_reported_and_text_still_draws() {
2106        let (defs, report) = definitions(
2107            &[],
2108            &names(&["Nowhere Sans"]),
2109            &names(&["Hack"]),
2110            &Previews::default(),
2111            &System::none(),
2112        );
2113        assert!(
2114            report
2115                .problems
2116                .iter()
2117                .any(|p| p.starts_with("font.family.ui: no font named Nowhere Sans")),
2118            "{report:?}"
2119        );
2120        // egui's bundled fonts stay at the end of every chain.
2121        let bundled = FontDefinitions::default();
2122        assert_eq!(
2123            defs.families[&FontFamily::Proportional],
2124            bundled.families[&FontFamily::Proportional]
2125        );
2126    }
2127
2128    #[test]
2129    fn the_built_in_themes_generic_names_draw_the_bundled_pair_at_every_weight() {
2130        let t = crate::theme::Tokens::default();
2131        assert_eq!(t.font.family_ui, names(&["sans-serif"]));
2132        assert_eq!(t.font.family_mono, names(&["monospace"]));
2133        let (defs, report) = definitions(
2134            &[],
2135            &t.font.family_ui,
2136            &t.font.family_mono,
2137            &Previews::default(),
2138            &System::none(),
2139        );
2140        // JetBrains Mono NL has 400 and 700 only: a generic name draws
2141        // what the bundled fonts have, and says no problem.
2142        assert!(report.problems.is_empty(), "{report:?}");
2143        let first = |f: FontFamily| defs.families[&f][0].clone();
2144        let egui_first = |f: FontFamily| FontDefinitions::default().families[&f][0].clone();
2145        if cfg!(feature = "bundled-fonts") {
2146            assert_eq!(first(FontFamily::Proportional), "pop:Inter:400:bundled");
2147            assert_eq!(
2148                first(family(Role::Ui, Weight::BOLD)),
2149                "pop:Inter:400:bundled@wght700"
2150            );
2151            assert_eq!(
2152                first(FontFamily::Monospace),
2153                "pop:JetBrains Mono NL:400:bundled"
2154            );
2155            assert_eq!(
2156                first(family(Role::Mono, Weight::BOLD)),
2157                "pop:JetBrains Mono NL:700:bundled"
2158            );
2159            // Values line up: JetBrains Mono NL's digits are tabular,
2160            // Inter's are not.
2161            assert!(report.tabular_digits(Role::Mono));
2162            assert!(!report.tabular_digits(Role::Ui));
2163            assert_eq!(
2164                report.resolved("ui", "sans-serif").unwrap().to_string(),
2165                "sans-serif → bundled Inter 400"
2166            );
2167            // egui's faces stay behind them.
2168            let regular = &defs.families[&FontFamily::Proportional];
2169            assert!(regular.contains(&egui_first(FontFamily::Proportional)));
2170        } else {
2171            assert_eq!(
2172                first(FontFamily::Proportional),
2173                egui_first(FontFamily::Proportional)
2174            );
2175            assert_eq!(
2176                first(FontFamily::Monospace),
2177                egui_first(FontFamily::Monospace)
2178            );
2179        }
2180    }
2181
2182    #[cfg(feature = "bundled-fonts")]
2183    #[test]
2184    fn the_bundled_pair_parses_and_is_listed_by_name() {
2185        let faces = pop_bundled();
2186        assert_eq!(faces.len(), 3);
2187        for f in faces {
2188            assert!(inspect(f.data.bytes()).is_ok(), "{f:?}");
2189        }
2190        let inter = &faces[0];
2191        assert!(
2192            inter
2193                .data
2194                .variation_axes()
2195                .iter()
2196                .any(|a| a.tag.to_be_bytes() == *b"wght")
2197        );
2198        assert!(faces[1].monospace() && faces[1].tabular_digits());
2199        let ctx = Context::default();
2200        set_system_faces(&ctx, Some(Vec::new()));
2201        let list = families(&ctx);
2202        assert_eq!(list[0].name, bundled::UI_FAMILY);
2203        assert_eq!(list[1].name, bundled::MONO_FAMILY);
2204        assert!(list[1].monospace);
2205        assert_eq!(origin_of(&ctx, "inter"), Some(Origin::Bundled));
2206        // Named, it is found like any family; a system face of the same
2207        // name comes first.
2208        let ctx = fake_system(&[("Inter", "Ubuntu-Light")]);
2209        assert_eq!(origin_of(&ctx, "Inter"), Some(Origin::System));
2210        let (defs, _) = definitions(
2211            &[],
2212            &names(&["Inter", "sans-serif"]),
2213            &[],
2214            &Previews::default(),
2215            &System::get(&ctx),
2216        );
2217        let regular = &defs.families[&FontFamily::Proportional];
2218        assert_eq!(regular[0], "pop:Inter:400:system");
2219        // `sans-serif` adds no second Inter behind the system's.
2220        assert!(
2221            !regular.iter().any(|k| k.ends_with(":bundled")),
2222            "{regular:?}"
2223        );
2224    }
2225
2226    #[test]
2227    fn egui_s_faces_named_draw_egui_s_pair() {
2228        let (defs, report) = definitions(
2229            &[],
2230            &names(&["Ubuntu", "sans-serif"]),
2231            &names(&["Hack", "monospace"]),
2232            &Previews::default(),
2233            &System::none(),
2234        );
2235        assert!(report.problems.is_empty(), "{report:?}");
2236        let bundled = FontDefinitions::default();
2237        if let Some(first) = bundled.families[&FontFamily::Proportional].first() {
2238            assert_eq!(&defs.families[&FontFamily::Proportional][0], first);
2239            assert_eq!(&defs.families[&family(Role::Ui, Weight::BOLD)][0], first);
2240        }
2241    }
2242
2243    #[test]
2244    fn the_icon_font_is_kept() {
2245        let (defs, _) = definitions(&[], &[], &[], &Previews::default(), &System::none());
2246        assert_eq!(
2247            defs.families
2248                .contains_key(&FontFamily::Name(crate::icon::FAMILY.into())),
2249            cfg!(feature = "phosphor")
2250        );
2251    }
2252
2253    #[test]
2254    fn installing_twice_the_same_families_keeps_the_report() {
2255        let ctx = Context::default();
2256        let a = install(&ctx, &names(&["Nowhere"]), &[]);
2257        let b = install(&ctx, &names(&["Nowhere"]), &[]);
2258        assert!(Arc::ptr_eq(&a, &b));
2259        register(&ctx, Face::from_static("Nowhere", Weight::REGULAR, FAKE));
2260        let c = install(&ctx, &names(&["Nowhere"]), &[]);
2261        assert!(!Arc::ptr_eq(&a, &c));
2262        assert!(c.problems.is_empty() || c.problems.iter().all(|p| !p.contains("no font named")));
2263    }
2264
2265    #[test]
2266    fn a_family_is_drawn_by_name_as_a_specimen_once_installed() {
2267        let ctx = Context::default();
2268        install(&ctx, &names(&["Ubuntu"]), &names(&["Hack"]));
2269        register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2270        // Asked once: installed from the next pass.
2271        assert_eq!(specimen(&ctx, "Inter", Weight::REGULAR), None);
2272        ctx.run_ui(egui::RawInput::default(), |_| {})
2273            .textures_delta
2274            .clear();
2275        let fam = specimen(&ctx, "inter", Weight::BOLD).expect("installed");
2276        assert_eq!(fam, specimen_family("Inter", Weight::BOLD));
2277        let said = report(&ctx).unwrap();
2278        assert_eq!(said.specimens, vec!["Inter".to_string()]);
2279        let chain = &said
2280            .chains
2281            .iter()
2282            .find(|(f, _)| fam == FontFamily::Name(f.as_str().into()))
2283            .unwrap()
2284            .1;
2285        assert_eq!(chain[0], "pop:Inter:400@wght700");
2286        // The theme's families are untouched.
2287        assert_eq!(installed_families(&ctx).unwrap().0, names(&["Ubuntu"]));
2288        let width = |f: FontFamily| {
2289            ctx.fonts_mut(|fonts| {
2290                fonts
2291                    .layout_no_wrap(
2292                        "Hamburgefonstiv".into(),
2293                        FontId::new(20.0, f),
2294                        egui::Color32::WHITE,
2295                    )
2296                    .size()
2297                    .x
2298            })
2299        };
2300        let regular = specimen(&ctx, "Inter", Weight::REGULAR).unwrap();
2301        assert!(width(fam) > width(regular) + 1.0);
2302        // A name found nowhere still draws, and is said.
2303        assert_eq!(specimen(&ctx, "Nowhere Sans", Weight::REGULAR), None);
2304        ctx.run_ui(egui::RawInput::default(), |_| {})
2305            .textures_delta
2306            .clear();
2307        assert!(specimen(&ctx, "Nowhere Sans", Weight::REGULAR).is_some());
2308        assert!(
2309            report(&ctx)
2310                .unwrap()
2311                .problems
2312                .iter()
2313                .any(|p| p == "specimen: no font named Nowhere Sans")
2314        );
2315    }
2316
2317    #[test]
2318    fn a_letter_a_specimen_lacks_is_drawn_as_a_box_never_a_panic() {
2319        // kittest's default harness panics on a missing glyph
2320        // (`MissingGlyphPolicy::Panic`): the sample must not.
2321        use egui_kittest::kittest::Queryable as _;
2322        let text = "Tiếng Việt 日本";
2323        let mut h = egui_kittest::Harness::new_ui(move |ui| {
2324            let ctx = ui.ctx().clone();
2325            if installed_families(&ctx).is_none() {
2326                install(&ctx, &names(&["Ubuntu"]), &names(&["Hack"]));
2327            }
2328            if let Some(family) = specimen(&ctx, "Ubuntu", Weight::REGULAR) {
2329                sample_label(ui, text, FontId::new(13.0, family));
2330            }
2331        });
2332        h.run();
2333        let family = specimen(&h.ctx, "Ubuntu", Weight::REGULAR).expect("installed");
2334        // egui's Ubuntu Light has no Vietnamese nor CJK: laid out as is,
2335        // these would panic.
2336        assert_eq!(
2337            uncovered(&h.ctx, &FontId::new(13.0, family), text),
2338            ['ế', 'ệ', '日', '本']
2339        );
2340        assert!(h.query_by_label(text).is_some());
2341    }
2342
2343    #[test]
2344    fn a_specimen_asked_twice_in_a_frame_waits_for_egui_to_have_it() {
2345        let ctx = Context::default();
2346        install(&ctx, &names(&["Ubuntu"]), &names(&["Hack"]));
2347        pass(&ctx);
2348        // Installed by the first ask, but once the pass has laid text out
2349        // egui takes it at its next pass: the second ask in the same frame
2350        // must not hand it out. (egui 0.37 takes it at once before any
2351        // text is laid out.)
2352        let mut asks = Vec::new();
2353        ctx.run_ui(egui::RawInput::default(), |ui| {
2354            ui.label("Text first");
2355            asks.push(specimen(ui.ctx(), "Hack", Weight::REGULAR));
2356            asks.push(specimen(ui.ctx(), "Hack", Weight::REGULAR));
2357        })
2358        .textures_delta
2359        .clear();
2360        assert_eq!(asks, [None, None]);
2361        pass(&ctx);
2362        assert!(specimen(&ctx, "Hack", Weight::REGULAR).is_some());
2363    }
2364
2365    /// The chain of an egui family in the last install's report.
2366    fn chain_of(ctx: &Context, family: &FontFamily) -> Vec<String> {
2367        report(ctx)
2368            .unwrap()
2369            .chains
2370            .iter()
2371            .find(|(f, _)| *family == FontFamily::Name(f.as_str().into()))
2372            .map(|(_, c)| c.clone())
2373            .unwrap_or_default()
2374    }
2375
2376    #[test]
2377    fn a_preview_family_is_always_defined_and_survives_a_theme_install() {
2378        let ctx = Context::default();
2379        install(&ctx, &names(&["Ubuntu"]), &names(&["Hack"]));
2380        // Before egui's first pass: not bound yet, so not handed out.
2381        assert_eq!(preview_family(&ctx, Role::Ui, Weight::REGULAR), None);
2382        pass(&ctx);
2383        let family = preview_family(&ctx, Role::Ui, Weight::REGULAR).expect("always defined");
2384        // Without a preview, it draws the role's families.
2385        assert_eq!(
2386            chain_of(&ctx, &family),
2387            chain_of(&ctx, &FontFamily::Name("pop.ui.400".into()))
2388        );
2389        register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2390        set_preview(&ctx, Role::Ui, Some(names(&["Inter", "sans-serif"])));
2391        assert_eq!(
2392            preview(&ctx, Role::Ui),
2393            Some(names(&["Inter", "sans-serif"]))
2394        );
2395        assert_eq!(chain_of(&ctx, &family)[0], "pop:Inter:400");
2396        // The theme's own families are untouched (the report names
2397        // egui's `Proportional` as the role's regular, `pop.ui.400`), and
2398        // follow the previewed face in the preview, as its fallbacks.
2399        let ui_chain = chain_of(&ctx, &FontFamily::Name("pop.ui.400".into()));
2400        assert_eq!(ui_chain[0], "Ubuntu-Light");
2401        assert_eq!(chain_of(&ctx, &family)[1..], ui_chain[..]);
2402        // The faces reported for renderers outside egui are that chain,
2403        // each face once.
2404        let drawn = installed_faces(&ctx, Role::Ui).unwrap();
2405        assert_eq!(drawn.len(), ui_chain.len());
2406        assert_eq!(drawn[0].family.as_deref(), Some("Ubuntu"));
2407        // No installed family has the same face twice (the theme's
2408        // `Ubuntu` and the bundled fonts behind `sans-serif` are one).
2409        for (f, chain) in &report(&ctx).unwrap().chains {
2410            let mut seen = std::collections::BTreeSet::new();
2411            assert!(chain.iter().all(|k| seen.insert(k)), "{f}: {chain:?}");
2412        }
2413        // A preview naming nothing found here falls back to the role's
2414        // families: a preview family is never empty.
2415        set_preview(&ctx, Role::Ui, Some(names(&["Nowhere Sans"])));
2416        assert_eq!(chain_of(&ctx, &family), ui_chain);
2417        set_preview(&ctx, Role::Ui, Some(Vec::new()));
2418        assert_eq!(chain_of(&ctx, &family), ui_chain);
2419        set_preview(&ctx, Role::Ui, Some(names(&["Inter", "sans-serif"])));
2420        assert_eq!(chain_of(&ctx, &family)[0], "pop:Inter:400");
2421        // A theme switched while the preview draws: the preview is
2422        // defined again by the new install, and drawing with it in the
2423        // same frame and the next never panics.
2424        install(&ctx, &names(&["Hack"]), &names(&["Hack"]));
2425        assert_eq!(chain_of(&ctx, &family)[0], "pop:Inter:400");
2426        let draw = |ctx: &Context| {
2427            ctx.run_ui(egui::RawInput::default(), |ui| {
2428                with_preview(ui, |ui| {
2429                    assert!(previewing(ui.ctx()));
2430                    ui.label("Hamburgefonstiv");
2431                    let font = shown_font_id(ui.ctx(), Role::Ui, Weight::BOLD, 13.0);
2432                    assert_eq!(font.family, preview_family_name(Role::Ui, Weight::BOLD));
2433                    ui.label(egui::RichText::new("Bold").font(font));
2434                    ui.monospace("0123");
2435                });
2436                assert!(!previewing(ui.ctx()));
2437            })
2438            .textures_delta
2439            .clear();
2440        };
2441        draw(&ctx);
2442        draw(&ctx);
2443        // The preview's bold weight is the variable face on its axis.
2444        assert_eq!(
2445            chain_of(&ctx, &preview_family_name(Role::Ui, Weight::BOLD))[0],
2446            "pop:Inter:400@wght700"
2447        );
2448        // Back to the role's families.
2449        set_preview(&ctx, Role::Ui, None);
2450        assert_eq!(
2451            chain_of(&ctx, &family),
2452            chain_of(&ctx, &FontFamily::Name("pop.ui.400".into()))
2453        );
2454    }
2455
2456    #[test]
2457    fn faces_given_as_the_system_s_are_listed_found_and_reported() {
2458        let ctx = Context::default();
2459        let bundled = FontDefinitions::default().font_data;
2460        let hack = bundled["Hack"].bytes().to_vec();
2461        let ubuntu = bundled["Ubuntu-Light"].bytes().to_vec();
2462        set_system_faces(
2463            &ctx,
2464            Some(vec![
2465                Face::from_owned("Fake Sans", Weight::REGULAR, ubuntu),
2466                Face::from_owned("Fake Mono", Weight::REGULAR, hack),
2467            ]),
2468        );
2469        let list = families(&ctx);
2470        let find = |n: &str| list.iter().find(|f| f.name == n).cloned();
2471        assert_eq!(find("Fake Sans").unwrap().origin, Origin::System);
2472        assert!(find("Fake Mono").unwrap().monospace);
2473        assert!(!find("Fake Sans").unwrap().monospace);
2474        assert_eq!(origin_of(&ctx, "fake sans"), Some(Origin::System));
2475        assert_eq!(origin_of(&ctx, "Ubuntu"), Some(Origin::Bundled));
2476        assert_eq!(origin_of(&ctx, "sans-serif"), Some(Origin::Bundled));
2477        assert_eq!(origin_of(&ctx, "Nowhere Sans"), None);
2478        let report = install(&ctx, &names(&["Fake Sans", "sans-serif"]), &[]);
2479        assert!(report.problems.iter().all(|p| !p.contains("no font named")));
2480        let primary = report
2481            .primary
2482            .iter()
2483            .find(|(f, _)| f == "pop.ui.400")
2484            .and_then(|(_, p)| p.clone())
2485            .unwrap();
2486        assert_eq!(primary, "Fake Sans 400 (system)");
2487        // The faces a renderer outside egui draws with are the chain egui
2488        // got, the given system face first, by its name.
2489        let drawn = installed_faces(&ctx, Role::Ui).unwrap();
2490        let chain = &report
2491            .chains
2492            .iter()
2493            .find(|(f, _)| f == "pop.ui.400")
2494            .unwrap()
2495            .1;
2496        assert_eq!(drawn.len(), chain.len());
2497        assert_eq!(drawn[0].family.as_deref(), Some("Fake Sans"));
2498        // Then the bundled face `sans-serif` stands for, by its family,
2499        // and egui's faces behind, unnamed.
2500        let behind = if cfg!(feature = "bundled-fonts") {
2501            assert_eq!(drawn[1].family.as_deref(), Some("Inter"));
2502            2
2503        } else {
2504            1
2505        };
2506        assert!(drawn[behind..].iter().all(|f| f.family.is_none()));
2507        // Another machine, without it: the next name draws, and the
2508        // report says what is missing.
2509        set_system_faces(&ctx, Some(Vec::new()));
2510        let report = reinstall(&ctx).unwrap();
2511        assert!(
2512            report
2513                .problems
2514                .iter()
2515                .any(|p| p.starts_with("font.family.ui: no font named Fake Sans")),
2516            "{report:?}"
2517        );
2518        assert_eq!(origin_of(&ctx, "Fake Sans"), None);
2519    }
2520
2521    /// A context whose system fonts are the faces given (never the
2522    /// machine's), each from one of egui's own files.
2523    fn fake_system(faces: &[(&str, &str)]) -> Context {
2524        let ctx = Context::default();
2525        let bundled = FontDefinitions::default().font_data;
2526        set_system_faces(
2527            &ctx,
2528            Some(
2529                faces
2530                    .iter()
2531                    .map(|(family, file)| {
2532                        Face::from_owned(family, Weight::REGULAR, bundled[*file].bytes().to_vec())
2533                    })
2534                    .collect(),
2535            ),
2536        );
2537        ctx
2538    }
2539
2540    #[test]
2541    fn a_name_on_the_system_and_bundled_resolves_to_the_system_s() {
2542        // The system has an Ubuntu (Hack's file, to tell them apart).
2543        let ctx = fake_system(&[("Ubuntu", "Hack")]);
2544        let (defs, report) = definitions(
2545            &[],
2546            &names(&["Ubuntu", "sans-serif"]),
2547            &names(&["monospace"]),
2548            &Previews::default(),
2549            &System::get(&ctx),
2550        );
2551        // The fake face has weight 400 only: the other weights draw it,
2552        // and the report says so; nothing else is a problem.
2553        assert!(
2554            report
2555                .problems
2556                .iter()
2557                .all(|p| p.starts_with("font.family.ui: Ubuntu has no weight ")
2558                    && p.ends_with(", 400 is drawn")),
2559            "{report:?}"
2560        );
2561        let regular = &defs.families[&FontFamily::Proportional];
2562        assert_eq!(regular[0], "pop:Ubuntu:400:system");
2563        let bold = &defs.families[&family(Role::Ui, Weight::BOLD)];
2564        assert_eq!(bold[0], "pop:Ubuntu:400:system");
2565        // egui's bundled faces stay behind it, each once.
2566        assert!(regular.iter().any(|k| k == "Ubuntu-Light"));
2567        let mut seen = std::collections::BTreeSet::new();
2568        assert!(regular.iter().all(|k| seen.insert(k)), "{regular:?}");
2569        let ubuntu = report.resolved("ui", "Ubuntu").unwrap();
2570        assert_eq!(ubuntu.origin, Some(Origin::System));
2571        assert_eq!(ubuntu.to_string(), "Ubuntu → system Ubuntu 400");
2572        assert_eq!(
2573            report.resolved("ui", "sans-serif").unwrap().origin,
2574            Some(Origin::Bundled)
2575        );
2576        // Asked by name, and listed, it is the system's too.
2577        assert_eq!(origin_of(&ctx, "ubuntu"), Some(Origin::System));
2578        let listed = families(&ctx);
2579        let ubuntu = listed.iter().find(|f| f.name == "Ubuntu").unwrap();
2580        assert_eq!(ubuntu.origin, Origin::System);
2581        assert!(ubuntu.monospace);
2582        assert_eq!(listed.iter().filter(|f| f.name == "Ubuntu").count(), 1);
2583        // A registered face still comes before the system's.
2584        let faces = vec![Face::from_static("Ubuntu", Weight::REGULAR, INTER_VAR)];
2585        let (defs, report) = definitions(
2586            &faces,
2587            &names(&["Ubuntu"]),
2588            &[],
2589            &Previews::default(),
2590            &System::get(&ctx),
2591        );
2592        assert_eq!(
2593            defs.families[&FontFamily::Proportional][0],
2594            "pop:Ubuntu:400"
2595        );
2596        assert_eq!(
2597            report.resolved("ui", "Ubuntu").unwrap().origin,
2598            Some(Origin::Registered)
2599        );
2600    }
2601
2602    #[test]
2603    fn a_name_missing_on_the_system_falls_back_to_the_bundled_face() {
2604        let ctx = fake_system(&[("Fake Sans", "Ubuntu-Light")]);
2605        let (defs, report) = definitions(
2606            &[],
2607            &names(&["Ubuntu"]),
2608            &names(&["Hack"]),
2609            &Previews::default(),
2610            &System::get(&ctx),
2611        );
2612        assert!(report.problems.is_empty(), "{report:?}");
2613        assert_eq!(defs.families[&FontFamily::Proportional][0], "Ubuntu-Light");
2614        let ubuntu = report.resolved("ui", "Ubuntu").unwrap();
2615        assert_eq!(ubuntu.origin, Some(Origin::Bundled));
2616        assert_eq!(ubuntu.face.as_deref(), Some("Ubuntu-Light"));
2617        assert_eq!(ubuntu.to_string(), "Ubuntu → bundled Ubuntu-Light");
2618        assert_eq!(
2619            report.resolved("mono", "Hack").unwrap().to_string(),
2620            "Hack → bundled Hack"
2621        );
2622        assert_eq!(origin_of(&ctx, "Ubuntu"), Some(Origin::Bundled));
2623    }
2624
2625    #[test]
2626    fn a_stack_whose_first_family_is_missing_everywhere_resolves_to_the_next() {
2627        // A platform's stack, on a machine with Adwaita Sans only.
2628        let ctx = fake_system(&[("Adwaita Sans", "Ubuntu-Light")]);
2629        let stack = names(&[
2630            "Helvetica",
2631            "Segoe UI",
2632            "Adwaita Sans",
2633            "Ubuntu",
2634            "sans-serif",
2635        ]);
2636        let (defs, report) =
2637            definitions(&[], &stack, &[], &Previews::default(), &System::get(&ctx));
2638        let regular = &defs.families[&FontFamily::Proportional];
2639        assert_eq!(regular[0], "pop:Adwaita Sans:400:system");
2640        let primary = report
2641            .primary
2642            .iter()
2643            .find(|(f, _)| f == "pop.ui.400")
2644            .and_then(|(_, p)| p.clone());
2645        assert_eq!(primary.as_deref(), Some("Adwaita Sans 400 (system)"));
2646        // The names after it are its fallbacks: egui's Ubuntu, once.
2647        assert_eq!(regular[1], "Ubuntu-Light");
2648        let mut seen = std::collections::BTreeSet::new();
2649        assert!(regular.iter().all(|k| seen.insert(k)), "{regular:?}");
2650        // Every name is said, in order, the missing ones as missing.
2651        let said: Vec<String> = report
2652            .resolved
2653            .iter()
2654            .filter(|r| r.list == "ui")
2655            .map(|r| r.to_string())
2656            .collect();
2657        assert_eq!(
2658            said,
2659            [
2660                "Helvetica → missing",
2661                "Segoe UI → missing",
2662                "Adwaita Sans → system Adwaita Sans 400",
2663                "Ubuntu → bundled Ubuntu-Light",
2664                if cfg!(feature = "bundled-fonts") {
2665                    "sans-serif → bundled Inter 400"
2666                } else {
2667                    "sans-serif → bundled"
2668                },
2669            ]
2670        );
2671        for missing in ["Helvetica", "Segoe UI"] {
2672            assert!(
2673                report
2674                    .problems
2675                    .iter()
2676                    .any(|p| p.starts_with(&format!("font.family.ui: no font named {missing}"))),
2677                "{report:?}"
2678            );
2679        }
2680    }
2681
2682    #[test]
2683    fn the_report_and_the_collector_say_where_each_name_was_found() {
2684        let ctx = fake_system(&[("Ubuntu", "Hack")]);
2685        crate::theme::install(
2686            &ctx,
2687            &crate::theme::ThemeSpec::new("pop-dark").override_token(
2688                "font.family.ui",
2689                serde_json::json!(["Ubuntu", "sans-serif"]),
2690            ),
2691        );
2692        pass(&ctx);
2693        let bridge = crate::debug::DebugBridge::with_core_collectors();
2694        let said = |ctx: &Context| -> Vec<serde_json::Value> {
2695            let d = bridge.snapshot_of(ctx, "fonts").unwrap();
2696            d["resolved"].as_array().unwrap().clone()
2697        };
2698        let ubuntu = |list: &[serde_json::Value]| {
2699            list.iter()
2700                .find(|r| r["list"] == "ui" && r["name"] == "Ubuntu")
2701                .cloned()
2702                .unwrap()
2703        };
2704        let r = ubuntu(&said(&ctx));
2705        assert_eq!(r["origin"], "system");
2706        assert_eq!(r["face"], "Ubuntu 400");
2707        assert_eq!(r["says"], "Ubuntu → system Ubuntu 400");
2708        // Another machine, without Ubuntu: egui's, said as such.
2709        set_system_faces(&ctx, Some(Vec::new()));
2710        reinstall(&ctx);
2711        let r = ubuntu(&said(&ctx));
2712        assert_eq!(r["origin"], "bundled");
2713        assert_eq!(r["says"], "Ubuntu → bundled Ubuntu-Light");
2714        assert_eq!(
2715            report(&ctx)
2716                .unwrap()
2717                .resolved("ui", "Ubuntu")
2718                .unwrap()
2719                .origin,
2720            Some(Origin::Bundled)
2721        );
2722        // A specimen is said too, a name found nowhere as missing.
2723        assert_eq!(specimen(&ctx, "Nowhere Sans", Weight::REGULAR), None);
2724        let r = report(&ctx).unwrap();
2725        let nowhere = r.resolved("specimen", "Nowhere Sans").unwrap();
2726        assert_eq!(nowhere.origin, None);
2727        assert_eq!(nowhere.to_string(), "Nowhere Sans → missing");
2728    }
2729
2730    #[test]
2731    fn families_list_egui_s_the_registered_and_the_user_s_with_their_origin() {
2732        let ctx = Context::default();
2733        register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2734        let hack = FontDefinitions::default().font_data["Hack"]
2735            .bytes()
2736            .to_vec();
2737        register(
2738            &ctx,
2739            Face {
2740                origin: Origin::File,
2741                ..Face::from_owned("My Mono", Weight::REGULAR, hack)
2742            },
2743        );
2744        let list = families(&ctx);
2745        let find = |n: &str| list.iter().find(|f| f.name == n).cloned().unwrap();
2746        assert_eq!(find("Ubuntu").origin, Origin::Bundled);
2747        assert!(find("Hack").monospace);
2748        assert_eq!(find("Inter").origin, Origin::Registered);
2749        assert!(!find("Inter").monospace);
2750        assert_eq!(find("My Mono").origin, Origin::File);
2751        assert!(find("My Mono").monospace);
2752        // The bundled ones first (egui-pop's, then egui's), each name
2753        // once.
2754        let first = if cfg!(feature = "bundled-fonts") {
2755            "Inter"
2756        } else {
2757            "Ubuntu"
2758        };
2759        assert_eq!(list[0].name, first);
2760        let mut names: Vec<_> = list.iter().map(|f| f.name.to_lowercase()).collect();
2761        names.dedup();
2762        assert_eq!(names.len(), list.len());
2763        assert_eq!(registered(&ctx).len(), 2);
2764    }
2765
2766    #[test]
2767    fn the_report_says_whether_each_role_draws_tabular_digits() {
2768        let (_, report) = definitions(
2769            &[],
2770            &names(&["Ubuntu"]),
2771            &names(&["Hack"]),
2772            &Previews::default(),
2773            &System::none(),
2774        );
2775        // A monospace face's digits are tabular.
2776        assert!(report.tabular_digits(Role::Mono));
2777        let hack = FontDefinitions::default().font_data["Hack"].clone();
2778        assert!(tabular_digits(&hack));
2779        assert!(monospace(&hack));
2780        let ubuntu = FontDefinitions::default().font_data["Ubuntu-Light"].clone();
2781        assert!(!monospace(&ubuntu));
2782        assert_eq!(report.tabular_digits(Role::Ui), tabular_digits(&ubuntu));
2783        // Each role and its preview, at each weight.
2784        assert_eq!(report.chains.len(), 4 * WEIGHTS.len());
2785    }
2786
2787    /// The x of each glyph from the right edge, per galley.
2788    fn from_right(g: &Galley) -> Vec<f32> {
2789        let row = &g.rows[0];
2790        let right = row.glyphs.last().map_or(0.0, |l| l.pos.x + l.advance_width);
2791        row.glyphs.iter().map(|gl| right - gl.pos.x).collect()
2792    }
2793
2794    fn pass(ctx: &Context) {
2795        ctx.run_ui(egui::RawInput::default(), |_| {})
2796            .textures_delta
2797            .clear();
2798    }
2799
2800    #[test]
2801    fn values_are_drawn_in_the_monospace_family_by_default_and_line_up() {
2802        let ctx = Context::default();
2803        let t = crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
2804        assert_eq!(t.font.numeric, Numeric::Mono);
2805        assert_eq!(Numeric::parse("ui"), Some(Numeric::Ui));
2806        assert_eq!(Numeric::parse("tabular"), None);
2807        pass(&ctx);
2808        for ppp in [1.0, 1.25, 2.0] {
2809            ctx.set_pixels_per_point(ppp);
2810            pass(&ctx);
2811            let f = number_font(&ctx, t.font.body);
2812            assert_eq!(f.font.family, FontFamily::Monospace);
2813            // About the monospace size that matches the body's x-height,
2814            // never above it, its advance a whole number of pixels.
2815            assert!(f.font.size <= t.font.mono + 1e-3, "{ppp}: {}", f.font.size);
2816            assert!(f.font.size > t.font.mono * 0.8, "{ppp}: {}", f.font.size);
2817            let advance = ctx.fonts_mut(|fonts| fonts.glyph_width(&f.font, '0')) * ppp;
2818            assert!(
2819                (advance - advance.round()).abs() < 0.01,
2820                "{ppp}: {advance} pixels"
2821            );
2822            assert!(!f.cells);
2823            // A column of numbers, right-aligned: each digit's x from the
2824            // right is the same on every row.
2825            let rows: Vec<Vec<f32>> = ["-1234.56", "1111.11", "8888.88", "+0000.00"]
2826                .iter()
2827                .map(|n| from_right(&number_galley(&ctx, n, 13.0, Color32::WHITE)))
2828                .collect();
2829            for r in &rows[1..] {
2830                for (a, b) in r.iter().rev().zip(rows[0].iter().rev()) {
2831                    assert!((a - b).abs() < 0.01, "{ppp}: {rows:?}");
2832                }
2833            }
2834        }
2835    }
2836
2837    #[test]
2838    fn a_proportional_face_s_digits_are_laid_in_cells() {
2839        let ctx = Context::default();
2840        register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2841        let t = crate::theme::install(
2842            &ctx,
2843            &crate::theme::ThemeSpec::new("pop-dark")
2844                .override_token("font.numeric", serde_json::json!("ui"))
2845                .override_token("font.family.ui", serde_json::json!(["Inter"])),
2846        );
2847        assert_eq!(t.font.numeric, Numeric::Ui);
2848        pass(&ctx);
2849        // Inter's default digits are proportional.
2850        assert!(!report(&ctx).unwrap().tabular_digits(Role::Ui));
2851        let f = number_font(&ctx, 20.0);
2852        assert_eq!(f.font, FontId::proportional(20.0));
2853        assert!(f.cells);
2854        let width = |s: &str| number_galley(&ctx, s, 20.0, Color32::WHITE).size().x;
2855        let plain = |s: &str| {
2856            ctx.fonts_mut(|fonts| {
2857                fonts
2858                    .layout_no_wrap(s.into(), FontId::proportional(20.0), Color32::WHITE)
2859                    .size()
2860                    .x
2861            })
2862        };
2863        // Drawn plainly, ones are narrower than zeros; in cells, not.
2864        assert!(plain("1111") + 1.0 < plain("0000"));
2865        assert!((width("1111") - width("0000")).abs() < 0.01);
2866        assert!((width("-11.1") - width("-00.0")).abs() < 0.01);
2867    }
2868
2869    #[test]
2870    fn cells_are_sections_one_per_digit() {
2871        let job = digit_cells(
2872            "-12.5 EV",
2873            &FontId::proportional(10.0),
2874            Color32::WHITE,
2875            |c| c.is_ascii_digit().then_some(1.0),
2876        );
2877        let parts: Vec<(&str, f32)> = job
2878            .sections
2879            .iter()
2880            .map(|s| {
2881                (
2882                    &job.text[s.byte_range.start.0..s.byte_range.end.0],
2883                    s.leading_space,
2884                )
2885            })
2886            .collect();
2887        assert_eq!(
2888            parts,
2889            vec![
2890                ("-", 0.0),
2891                ("1", 1.0),
2892                ("2", 1.0),
2893                (".", 0.0),
2894                ("5", 1.0),
2895                (" EV", 0.0)
2896            ]
2897        );
2898    }
2899
2900    #[test]
2901    fn the_fonts_collector_says_what_is_installed_and_what_a_text_misses() {
2902        let ctx = Context::default();
2903        crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
2904        // Before the first frame: no atlas yet, and no panic.
2905        let early = crate::debug::DebugBridge::with_core_collectors()
2906            .snapshot_of(&ctx, "fonts")
2907            .unwrap();
2908        assert!(early["atlas"]["size"].is_null());
2909        register(&ctx, Face::from_static("Inter", Weight::REGULAR, INTER_VAR));
2910        reinstall(&ctx);
2911        pass(&ctx);
2912        let mut bridge = crate::debug::DebugBridge::with_core_collectors();
2913        assert!(bridge.names().iter().any(|n| n == "fonts"));
2914        let d = &bridge.snapshot_of(&ctx, "fonts").unwrap();
2915        assert_eq!(d["requested"]["ui"], serde_json::json!(["sans-serif"]));
2916        assert_eq!(d["faces"][0]["family"], "Inter");
2917        assert_eq!(d["faces"][0]["origin"], "registered");
2918        assert_eq!(d["faces"][0]["monospace"], false);
2919        assert_eq!(d["numeric"], "mono");
2920        assert_eq!(d["sizes"]["text_styles"]["body"], 13.0);
2921        assert_eq!(d["text_size"], 1.0);
2922        assert_eq!(d["tabular_digits"]["mono"], true);
2923        let families = d["families"].as_array().unwrap();
2924        assert!(
2925            families.iter().any(
2926                |f| f["family"] == "pop.mono.400" && !f["chain"].as_array().unwrap().is_empty()
2927            )
2928        );
2929        assert!(d["atlas"]["fill_ratio"].as_f64().is_some());
2930        // `check`: what no face of the family covers.
2931        let f = bridge.call(
2932            &ctx,
2933            "fonts",
2934            "check",
2935            &serde_json::json!({ "text": "Aé 日本", "family": "ui" }),
2936        );
2937        assert!(f.ok, "{f:?}");
2938        assert_eq!(f.data["missing"], serde_json::json!(["日", "本"]));
2939        let f = bridge.call(&ctx, "fonts", "check", &serde_json::json!({}));
2940        assert!(!f.ok);
2941    }
2942
2943    #[test]
2944    fn a_weight_maps_to_the_nearest_installed_family() {
2945        assert_eq!(
2946            family(Role::Ui, Weight(800)),
2947            family(Role::Ui, Weight::BOLD)
2948        );
2949        assert_eq!(
2950            family(Role::Mono, Weight(450)),
2951            family(Role::Mono, Weight::MEDIUM)
2952        );
2953    }
2954
2955    #[test]
2956    fn a_font_file_is_read_by_path_and_a_broken_one_is_reported() {
2957        let dir = std::env::temp_dir().join(format!("egui-pop-fonts-{}", std::process::id()));
2958        std::fs::create_dir_all(&dir).unwrap();
2959        let good = dir.join("inter.ttf");
2960        std::fs::write(&good, INTER_VAR).unwrap();
2961        let bad = dir.join("broken.ttf");
2962        std::fs::write(&bad, b"not a font at all").unwrap();
2963        let file = FontFile::read(&good).unwrap();
2964        assert!(file.family.starts_with("Inter"), "{file:?}");
2965        assert_eq!(file.weight, Weight::REGULAR);
2966        assert!(FontFile::read(&bad).unwrap_err().contains("not a font"));
2967        assert!(FontFile::read(&dir.join("missing.ttf")).is_err());
2968
2969        let ctx = Context::default();
2970        let broken = FontFile {
2971            path: bad.clone(),
2972            ..file.clone()
2973        };
2974        let problems = register_files(&ctx, &[file.clone(), broken]);
2975        assert_eq!(problems.len(), 1, "{problems:?}");
2976        // The good one is registered: the family is found by its name.
2977        let report = install(&ctx, &names(&[file.family.as_str()]), &[]);
2978        assert!(
2979            report.problems.iter().all(|p| !p.contains("no font named")),
2980            "{:?}",
2981            report.problems
2982        );
2983        assert_eq!(
2984            installed_families(&ctx).unwrap().0,
2985            vec![file.family.clone()]
2986        );
2987        // A path is what is kept.
2988        let json = serde_json::to_value(&file).unwrap();
2989        assert_eq!(json["weight"], 400);
2990        assert!(json["path"].as_str().unwrap().ends_with("inter.ttf"));
2991        let _ = std::fs::remove_dir_all(&dir);
2992    }
2993
2994    /// The first glyph of `text` in a role at `size`: where egui places
2995    /// it in its row, and how far down its image is drawn from there.
2996    fn glyph_at(ctx: &Context, role: Role, size: f32, text: &str) -> (f32, f32, egui::Vec2) {
2997        let galley = ctx.fonts_mut(|f| {
2998            f.layout_no_wrap(
2999                text.into(),
3000                font_id(role, Weight::REGULAR, size),
3001                Color32::WHITE,
3002            )
3003        });
3004        let g = galley.rows[0].glyphs[0];
3005        (g.pos.y, g.uv_rect.offset.y, galley.size())
3006    }
3007
3008    #[test]
3009    fn a_baseline_offset_moves_a_role_s_glyphs_by_its_share_of_the_size() {
3010        let ctx = Context::default();
3011        let t = crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
3012        // The built-in themes move nothing: the faces keep their keys.
3013        assert_eq!(t.font.baseline_offsets, BaselineOffsets::default());
3014        assert!(
3015            report(&ctx)
3016                .unwrap()
3017                .chains
3018                .iter()
3019                .all(|(_, keys)| keys.iter().all(|k| !k.contains("@y"))),
3020            "no face moved by default"
3021        );
3022        pass(&ctx);
3023        let ui_before = glyph_at(&ctx, Role::Ui, 20.0, "H");
3024        let mono_before = glyph_at(&ctx, Role::Mono, 20.0, "H");
3025        let t = crate::theme::install(
3026            &ctx,
3027            &crate::theme::ThemeSpec::new("pop-dark")
3028                .override_token("font.baseline-offset.ui", serde_json::json!(0.1)),
3029        );
3030        assert_eq!(t.font.baseline_offsets.ui, 0.1);
3031        assert_eq!(t.font.baseline_offsets.mono, 0.0);
3032        pass(&ctx);
3033        let ui_after = glyph_at(&ctx, Role::Ui, 20.0, "H");
3034        let mono_after = glyph_at(&ctx, Role::Mono, 20.0, "H");
3035        // 0.1 of 20 points: the glyph's image 2 points lower, its place
3036        // in the row and the row's size unchanged.
3037        assert!(
3038            (ui_after.1 - ui_before.1 - 2.0).abs() < 0.05,
3039            "{ui_before:?} -> {ui_after:?}"
3040        );
3041        assert_eq!(ui_after.0, ui_before.0);
3042        assert_eq!(ui_after.2, ui_before.2);
3043        // The other role does not move.
3044        assert_eq!(mono_after, mono_before);
3045        // A reinstall (a face registered since) keeps the offset; a theme
3046        // without it puts the glyphs back.
3047        reinstall(&ctx);
3048        pass(&ctx);
3049        assert_eq!(glyph_at(&ctx, Role::Ui, 20.0, "H"), ui_after);
3050        crate::theme::install(&ctx, &crate::theme::ThemeSpec::new("pop-dark"));
3051        pass(&ctx);
3052        assert_eq!(glyph_at(&ctx, Role::Ui, 20.0, "H"), ui_before);
3053    }
3054}