Skip to main content

egui_pop_core/
theme.rs

1//! Themes for egui: resolved design tokens turned into egui's [`Visuals`]
2//! and [`Style`], installed into a [`Context`], and kept there as a typed
3//! [`Tokens`] set for custom widgets.
4//!
5//! ```
6//! use egui_pop_core::theme::{self, Density, ThemeSpec, Tokens};
7//!
8//! let ctx = egui::Context::default();
9//! let tokens = theme::install(&ctx, &ThemeSpec::new("pop-light").density(Density::Compact));
10//! assert!(tokens.resolved().problems().is_empty());
11//! assert_eq!(ctx.global_style().visuals.panel_fill, tokens.surface.panel);
12//! // Any widget reads the same set back from the context.
13//! assert_eq!(Tokens::of(&ctx).accent.default, tokens.accent.default);
14//! ```
15//!
16//! # Where tokens go
17//!
18//! egui's own widgets (and other crates' widgets) are drawn from the
19//! generated style: `surface.*` become panel, window and field fills,
20//! `button.*` the widget states (rest, hovered, pressed), `text.*` the
21//! widget strokes, `border.*` outlines and separators, `focus.ring` the
22//! stroke of a focused or pressed widget, `selection` the fill behind
23//! selected text and items, `space.*` and `size.*` the spacing,
24//! `font.text-style.*` (steps of the `font.size.*` scale) egui's text
25//! styles, `shadow.window` and `shadow.popup` egui's window and popup
26//! shadows, `motion.duration` the animation time, and the kit's
27//! `scroll-bar` every scroll area's `ScrollStyle` (its width, margin,
28//! placement and visibility).
29//!
30//! egui uses one colour (`selection.stroke`) for both the text of a
31//! selected label and the frame of a focused text field: egui-pop gives it
32//! `text.strong`, which stays legible on the selection fill. egui's slider
33//! paints its rail with the resting widget fill and its optional trailing
34//! fill with the selection fill; the `slider.*` tokens are for egui-pop's
35//! own slider.
36//!
37//! Font families (`font.family.*`) become egui's fonts at several weights
38//! (`fonts`): faces the application registers, the system's (feature
39//! `system-fonts`), then egui's bundled fonts.
40//!
41//! # Never per widget
42//!
43//! A theme is installed for the whole context, between frames. Never
44//! change the global style in the middle of a frame to theme one widget:
45//! read [`Tokens::of`] and paint with its values, or scope a style change
46//! to a child `Ui` (`ui.scope(|ui| { ui.style_mut()... })`), which does
47//! not leak to the rest of the frame.
48
49use std::sync::{Arc, Mutex};
50
51use egui::{
52    Color32, Context, CornerRadius, Margin, Shadow, Stroke, Style, TextStyle, Theme,
53    ThemePreference, Visuals,
54    style::{KineticScrollStyle, ScrollAnimation},
55};
56
57use crate::kit::{Kit, Shapes, State};
58use crate::state::Slot;
59pub use egui_pop_tokens::{
60    BUILT_IN_ACCENTS, BUILT_IN_THEMES, Counterpart, Density, FALLBACK_THEME, POP_THEMES,
61    ResolvedTokens, ScrollBars, ThemeSpec, Themes, theme_label,
62};
63
64/// A token colour as an egui colour.
65pub fn color32(c: egui_pop_tokens::Color) -> Color32 {
66    let [r, g, b, a] = c.to_srgba_u8();
67    Color32::from_rgba_unmultiplied(r, g, b, a)
68}
69
70/// The surfaces, from the deepest to the topmost.
71#[derive(Clone, Debug, PartialEq)]
72#[non_exhaustive]
73pub struct Surface {
74    pub canvas: Color32,
75    pub panel: Color32,
76    pub raised: Color32,
77    pub hover: Color32,
78    pub active: Color32,
79    pub overlay: Color32,
80    pub sunken: Color32,
81}
82
83#[derive(Clone, Debug, PartialEq)]
84#[non_exhaustive]
85pub struct Text {
86    pub default: Color32,
87    pub muted: Color32,
88    pub strong: Color32,
89    pub on_accent: Color32,
90}
91
92#[derive(Clone, Debug, PartialEq)]
93#[non_exhaustive]
94pub struct Border {
95    pub default: Color32,
96    pub strong: Color32,
97}
98
99#[derive(Clone, Debug, PartialEq)]
100#[non_exhaustive]
101pub struct Accent {
102    pub default: Color32,
103    pub hover: Color32,
104    pub active: Color32,
105    pub subtle: Color32,
106}
107
108/// Status colours, legible as text on panels and overlays.
109#[derive(Clone, Debug, PartialEq)]
110#[non_exhaustive]
111pub struct Status {
112    pub danger: Color32,
113    pub warning: Color32,
114    pub success: Color32,
115    pub info: Color32,
116}
117
118/// Corner radii in points.
119#[derive(Clone, Debug, PartialEq)]
120#[non_exhaustive]
121pub struct Radius {
122    pub widget: f32,
123    pub window: f32,
124}
125
126/// Spacing in points: the scale's steps (`space.xs` to `space.xl`), and
127/// spacing by intent (`space.inline`, `group`, `section`, `page`), each
128/// an alias of a step, so densities scale it.
129#[derive(Clone, Debug, PartialEq)]
130#[non_exhaustive]
131pub struct Space {
132    pub xs: f32,
133    pub s: f32,
134    pub m: f32,
135    pub l: f32,
136    pub xl: f32,
137    /// Between items on one line.
138    pub inline: f32,
139    /// Between related groups of items.
140    pub group: f32,
141    /// Before a section of a panel or a page.
142    pub section: f32,
143    /// Around a page's content and between its main blocks.
144    pub page: f32,
145}
146
147/// A text role: what a piece of text is (`text-role.*`), each a size,
148/// a colour and a weight over the size scale and the text colours.
149#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
150pub enum TextRole {
151    /// A page's or a dialog's title.
152    Title,
153    /// A section's title in a panel or a page.
154    Section,
155    /// Ordinary text.
156    Body,
157    /// Secondary text: hints, descriptions, an empty list's message.
158    Muted,
159    /// Small print about an item: a date, a size, a count.
160    Meta,
161}
162
163impl TextRole {
164    pub const ALL: [TextRole; 5] = [
165        TextRole::Title,
166        TextRole::Section,
167        TextRole::Body,
168        TextRole::Muted,
169        TextRole::Meta,
170    ];
171
172    /// Its name in the tokens (`title`: `text-role.title.*`).
173    pub fn name(self) -> &'static str {
174        match self {
175            TextRole::Title => "title",
176            TextRole::Section => "section",
177            TextRole::Body => "body",
178            TextRole::Muted => "muted",
179            TextRole::Meta => "meta",
180        }
181    }
182}
183
184/// How a text role is drawn.
185#[derive(Clone, Copy, Debug, PartialEq)]
186#[non_exhaustive]
187pub struct TextRoleStyle {
188    /// In points (a step of `font.size.*`).
189    pub size: f32,
190    pub color: Color32,
191    /// Regular unless the role says otherwise (`fonts::family` draws it).
192    pub weight: crate::fonts::Weight,
193}
194
195/// Every text role's style (`text-role.*`).
196#[derive(Clone, Debug, PartialEq)]
197#[non_exhaustive]
198pub struct TextRoles {
199    pub title: TextRoleStyle,
200    pub section: TextRoleStyle,
201    pub body: TextRoleStyle,
202    /// Inline emphasis at the body's size (`text-role.strong`): not a
203    /// [`TextRole`] variant, so drawn with [`crate::ui::strong_text`] and
204    /// `UiPop::strong_text`.
205    pub strong: TextRoleStyle,
206    pub muted: TextRoleStyle,
207    pub meta: TextRoleStyle,
208}
209
210impl TextRoles {
211    /// A role's style.
212    pub fn get(&self, role: TextRole) -> &TextRoleStyle {
213        match role {
214            TextRole::Title => &self.title,
215            TextRole::Section => &self.section,
216            TextRole::Body => &self.body,
217            TextRole::Muted => &self.muted,
218            TextRole::Meta => &self.meta,
219        }
220    }
221}
222
223/// Sizes in points.
224#[derive(Clone, Debug, PartialEq)]
225#[non_exhaustive]
226pub struct Size {
227    pub control_height: f32,
228    /// A row of a list, a tree or a property panel (`size.row.height`),
229    /// apart from the controls' height.
230    pub row_height: f32,
231    pub icon_inline: f32,
232    pub icon_toolbar: f32,
233    pub icon_panel: f32,
234    pub dialog_width: f32,
235    pub toast_width: f32,
236}
237
238/// Font sizes in points and families, the first preferred. `small`,
239/// `body`, `button`, `heading` and `mono` are egui's text styles
240/// (`font.text-style.*`), each a step of the `scale` (`font.size.*`).
241#[derive(Clone, Debug, PartialEq)]
242#[non_exhaustive]
243pub struct Font {
244    pub small: f32,
245    pub body: f32,
246    pub button: f32,
247    pub heading: f32,
248    pub mono: f32,
249    /// The size scale, `xs` to `xl` (`fonts::Step`).
250    pub scale: FontScale,
251    pub family_ui: Vec<String>,
252    pub family_mono: Vec<String>,
253    /// How values line their digits up (`font.numeric`).
254    pub numeric: crate::fonts::Numeric,
255    /// How far each role's glyphs are drawn below their place, a share
256    /// of the size (`font.baseline-offset.ui`, `font.baseline-offset.mono`).
257    pub baseline_offsets: crate::fonts::BaselineOffsets,
258}
259
260/// The size scale's five steps, in points (`font.size.xs` to `xl`).
261#[derive(Clone, Copy, Debug, PartialEq)]
262#[non_exhaustive]
263pub struct FontScale {
264    pub xs: f32,
265    pub s: f32,
266    pub m: f32,
267    pub l: f32,
268    pub xl: f32,
269}
270
271impl FontScale {
272    /// A step's size in points.
273    pub fn get(&self, step: crate::fonts::Step) -> f32 {
274        use crate::fonts::Step;
275        match step {
276            Step::Xs => self.xs,
277            Step::S => self.s,
278            Step::M => self.m,
279            Step::L => self.l,
280            Step::Xl => self.xl,
281        }
282    }
283}
284
285/// Times of motion, in seconds (see `motion`).
286#[derive(Clone, Debug, PartialEq)]
287#[non_exhaustive]
288pub struct MotionTokens {
289    /// Nothing shows before work ran this long (`motion.spinner.delay`).
290    pub spinner_delay: f32,
291    /// A busy indicator, once shown, stays this long
292    /// (`motion.spinner.min`).
293    pub spinner_min: f32,
294    /// One turn of a spinner (`motion.spinner.turn`).
295    pub spinner_turn: f32,
296    /// An indeterminate bar's segment crossing the track
297    /// (`motion.progress.travel`).
298    pub progress_travel: f32,
299    /// A skeleton's shimmer crossing it (`motion.skeleton.shimmer`).
300    pub skeleton_shimmer: f32,
301    /// One pulse of a busy LED or a mark calling attention
302    /// (`motion.pulse.period`).
303    pub pulse_period: f32,
304    /// How many times a mark calling attention pulses
305    /// (`motion.pulse.count`).
306    pub pulse_count: u32,
307    /// A toast sliding in from its corner's side, and out again
308    /// (`motion.toast.slide`; none under reduced motion).
309    pub toast_slide: f32,
310    /// The pointer rests this long on a submenu item before its submenu
311    /// opens (`motion.submenu.delay`).
312    pub submenu_delay: f32,
313}
314
315/// The data palettes (`palette.*`): colours for charts and data views.
316#[derive(Clone, Debug, PartialEq)]
317#[non_exhaustive]
318pub struct DataPalette {
319    /// The categorical palette, `palette.category.0` to `.9`: one colour
320    /// per series, in order (`egui_pop_tokens::CATEGORY`).
321    pub category: [Color32; egui_pop_tokens::CATEGORY.len()],
322    /// The log levels' colours, `palette.log.*`.
323    pub log: LogPalette,
324    /// The axes' colours, `palette.axis.*`.
325    pub axis: AxisPalette,
326}
327
328/// The axes' colours (`palette.axis.*`): X red, Y green and Z blue, as
329/// most 3D and image tools draw them. Each is seen at 3:1 on the
330/// viewport's background.
331#[derive(Clone, Copy, Debug, PartialEq)]
332#[non_exhaustive]
333pub struct AxisPalette {
334    /// `palette.axis.x`.
335    pub x: Color32,
336    /// `palette.axis.y`.
337    pub y: Color32,
338    /// `palette.axis.z`.
339    pub z: Color32,
340}
341
342/// The log levels' colours (`palette.log.*`), from the least to the most
343/// severe: what a log view colours a line's level with. Each reads as
344/// text on the canvas and the panel.
345#[derive(Clone, Copy, Debug, PartialEq)]
346#[non_exhaustive]
347pub struct LogPalette {
348    /// `palette.log.trace`.
349    pub trace: Color32,
350    /// `palette.log.debug`.
351    pub debug: Color32,
352    /// `palette.log.info`.
353    pub info: Color32,
354    /// `palette.log.warn`.
355    pub warn: Color32,
356    /// `palette.log.error`.
357    pub error: Color32,
358    /// `palette.log.critical`: past error.
359    pub critical: Color32,
360}
361
362impl LogPalette {
363    /// The colours in [`egui_pop_tokens::LOG_LEVELS`]' order, from trace
364    /// to critical.
365    pub fn levels(&self) -> [Color32; egui_pop_tokens::LOG_LEVELS.len()] {
366        [
367            self.trace,
368            self.debug,
369            self.info,
370            self.warn,
371            self.error,
372            self.critical,
373        ]
374    }
375}
376
377impl DataPalette {
378    /// Series `index`'s colour: its slot of the categorical palette,
379    /// round again from the first past the last. Give a series the same
380    /// index whatever else is shown, so its colour follows it; more
381    /// series than slots repeat colours, so name them (a legend) or group
382    /// the smallest.
383    pub fn series(&self, index: usize) -> Color32 {
384        self.category[index % self.category.len()]
385    }
386}
387
388/// Shadows under what lies over the interface (`shadow.*`), as egui's.
389#[derive(Clone, Debug, PartialEq)]
390#[non_exhaustive]
391pub struct ShadowTokens {
392    /// Menus, popovers, tooltips (egui's `popup_shadow`).
393    pub popup: Shadow,
394    /// Dialogs and palettes (egui's `window_shadow`).
395    pub window: Shadow,
396    /// A side area lying over the centre, its `offset` towards the
397    /// centre as for the start side.
398    pub side: Shadow,
399}
400
401/// A role's baseline offset (`font.baseline-offset.*`): a share of the
402/// size, kept between -1 and 1; 0 when missing or not a number.
403fn baseline_offset(r: &ResolvedTokens, path: &str) -> f32 {
404    r.dimension(path)
405        .filter(|v| v.is_finite())
406        .map_or(0.0, |v| v.clamp(-1.0, 1.0))
407}
408
409/// The shadow a group of tokens gives (`<prefix>offset-x`, `offset-y`,
410/// `blur`, `spread` and `color`; `shadow.window.` or a component's
411/// `side-area.shadow-`), as egui's [`Shadow`], rounded to its whole
412/// points; `None` when the colour is missing. egui's spread cannot be
413/// negative: below 0 it is 0.
414pub fn shadow(r: &ResolvedTokens, prefix: &str) -> Option<Shadow> {
415    let color = r.color(&format!("{prefix}color"))?;
416    let d = |t: &str| r.dimension(&format!("{prefix}{t}")).unwrap_or(0.0);
417    let offset = |v: f32| v.round().clamp(-128.0, 127.0) as i8;
418    let size = |v: f32| v.round().clamp(0.0, 255.0) as u8;
419    Some(Shadow {
420        offset: [offset(d("offset-x")), offset(d("offset-y"))],
421        blur: size(d("blur")),
422        spread: size(d("spread")),
423        color: color32(color),
424    })
425}
426
427/// The system tokens of a resolved theme, typed for egui. Custom widgets
428/// read it with [`Tokens::of`] instead of hard-coding a colour or a size;
429/// a component's look is in its kit (`Kit::of(ctx).<component>`), and any
430/// other token in [`Tokens::resolved`].
431#[derive(Clone, Debug, PartialEq)]
432#[non_exhaustive]
433pub struct Tokens {
434    pub surface: Surface,
435    pub text: Text,
436    /// Text by role (`text-role.*`).
437    pub text_role: TextRoles,
438    pub border: Border,
439    pub accent: Accent,
440    pub status: Status,
441    pub focus_ring: Color32,
442    pub selection: Color32,
443    pub radius: Radius,
444    pub space: Space,
445    pub size: Size,
446    pub font: Font,
447    pub shadow: ShadowTokens,
448    /// Colours for charts and data views (`palette.*`).
449    pub palette: DataPalette,
450    /// `motion.duration` in seconds; zero when motion is reduced.
451    pub motion_duration: f32,
452    /// The other times of motion.
453    pub motion: MotionTokens,
454    resolved: Arc<ResolvedTokens>,
455}
456
457impl Default for Tokens {
458    /// The built-in `pop-dark` theme.
459    fn default() -> Self {
460        Tokens::new(Themes::default().resolve(&ThemeSpec::default()))
461    }
462}
463
464impl Tokens {
465    /// Types a resolved theme. Resolution guarantees every contract token,
466    /// so nothing here can be missing.
467    pub fn new(resolved: ResolvedTokens) -> Tokens {
468        let r = &resolved;
469        let c = |path: &str| color32(r.color(path).unwrap_or(egui_pop_tokens::Color::MISSING));
470        let d = |path: &str| r.dimension(path).unwrap_or(0.0);
471        let f = |path: &str| {
472            r.font_family(path)
473                .map(<[String]>::to_vec)
474                .unwrap_or_default()
475        };
476        Tokens {
477            surface: Surface {
478                canvas: c("surface.canvas"),
479                panel: c("surface.panel"),
480                raised: c("surface.raised"),
481                hover: c("surface.hover"),
482                active: c("surface.active"),
483                overlay: c("surface.overlay"),
484                sunken: c("surface.sunken"),
485            },
486            text: Text {
487                default: c("text.default"),
488                muted: c("text.muted"),
489                strong: c("text.strong"),
490                on_accent: c("text.on-accent"),
491            },
492            text_role: {
493                let role = |name: &str| TextRoleStyle {
494                    size: d(&format!("text-role.{name}.size")),
495                    color: c(&format!("text-role.{name}.color")),
496                    weight: crate::fonts::Weight(
497                        r.dimension(&format!("text-role.{name}.weight"))
498                            .unwrap_or(400.0)
499                            .clamp(1.0, 1000.0) as u16,
500                    ),
501                };
502                TextRoles {
503                    title: role("title"),
504                    section: role("section"),
505                    body: role("body"),
506                    // A theme from before the role: the body, semibold.
507                    strong: if r.dimension("text-role.strong.size").is_some() {
508                        role("strong")
509                    } else {
510                        TextRoleStyle {
511                            weight: crate::fonts::Weight::SEMIBOLD,
512                            ..role("body")
513                        }
514                    },
515                    muted: role("muted"),
516                    meta: role("meta"),
517                }
518            },
519            border: Border {
520                default: c("border.default"),
521                strong: c("border.strong"),
522            },
523            accent: Accent {
524                default: c("accent.default"),
525                hover: c("accent.hover"),
526                active: c("accent.active"),
527                subtle: c("accent.subtle"),
528            },
529            status: Status {
530                danger: c("danger"),
531                warning: c("warning"),
532                success: c("success"),
533                info: c("info"),
534            },
535            focus_ring: c("focus.ring"),
536            selection: c("selection"),
537            radius: Radius {
538                widget: d("radius.widget"),
539                window: d("radius.window"),
540            },
541            space: Space {
542                xs: d("space.xs"),
543                s: d("space.s"),
544                m: d("space.m"),
545                l: d("space.l"),
546                xl: d("space.xl"),
547                inline: d("space.inline"),
548                group: d("space.group"),
549                section: d("space.section"),
550                page: d("space.page"),
551            },
552            size: Size {
553                control_height: d("size.control.height"),
554                row_height: d("size.row.height"),
555                icon_inline: d("size.icon.inline"),
556                icon_toolbar: d("size.icon.toolbar"),
557                icon_panel: d("size.icon.panel"),
558                dialog_width: d("size.dialog.width"),
559                toast_width: d("size.toast.width"),
560            },
561            font: Font {
562                small: d("font.text-style.small"),
563                body: d("font.text-style.body"),
564                button: d("font.text-style.button"),
565                heading: d("font.text-style.heading"),
566                mono: d("font.text-style.monospace"),
567                scale: FontScale {
568                    xs: d("font.size.xs"),
569                    s: d("font.size.s"),
570                    m: d("font.size.m"),
571                    l: d("font.size.l"),
572                    xl: d("font.size.xl"),
573                },
574                family_ui: f("font.family.ui"),
575                family_mono: f("font.family.mono"),
576                numeric: match r.value("font.numeric") {
577                    Some(egui_pop_tokens::Value::Other(serde_json::Value::String(s))) => {
578                        crate::fonts::Numeric::parse(s).unwrap_or_default()
579                    }
580                    _ => crate::fonts::Numeric::default(),
581                },
582                baseline_offsets: crate::fonts::BaselineOffsets {
583                    ui: baseline_offset(r, "font.baseline-offset.ui"),
584                    mono: baseline_offset(r, "font.baseline-offset.mono"),
585                },
586            },
587            shadow: {
588                let sh = |g: &str| shadow(r, &format!("shadow.{g}.")).unwrap_or(Shadow::NONE);
589                ShadowTokens {
590                    popup: sh("popup"),
591                    window: sh("window"),
592                    side: sh("side"),
593                }
594            },
595            palette: DataPalette {
596                category: egui_pop_tokens::CATEGORY.map(c),
597                log: LogPalette {
598                    trace: c("palette.log.trace"),
599                    debug: c("palette.log.debug"),
600                    info: c("palette.log.info"),
601                    warn: c("palette.log.warn"),
602                    error: c("palette.log.error"),
603                    critical: c("palette.log.critical"),
604                },
605                axis: AxisPalette {
606                    x: c("palette.axis.x"),
607                    y: c("palette.axis.y"),
608                    z: c("palette.axis.z"),
609                },
610            },
611            motion_duration: r.duration_ms("motion.duration").unwrap_or(0.0).max(0.0) / 1000.0,
612            motion: {
613                let s = |path: &str| r.duration_ms(path).unwrap_or(0.0).max(0.0) / 1000.0;
614                MotionTokens {
615                    spinner_delay: s("motion.spinner.delay"),
616                    spinner_min: s("motion.spinner.min"),
617                    spinner_turn: s("motion.spinner.turn"),
618                    progress_travel: s("motion.progress.travel"),
619                    skeleton_shimmer: s("motion.skeleton.shimmer"),
620                    pulse_period: s("motion.pulse.period"),
621                    pulse_count: r
622                        .dimension("motion.pulse.count")
623                        .unwrap_or(3.0)
624                        .clamp(0.0, 100.0) as u32,
625                    toast_slide: s("motion.toast.slide"),
626                    submenu_delay: s("motion.submenu.delay"),
627                }
628            },
629            resolved: Arc::new(resolved),
630        }
631    }
632
633    /// The full resolved set: every tier, descriptions, aliases, problems.
634    pub fn resolved(&self) -> &ResolvedTokens {
635        &self.resolved
636    }
637
638    /// Any colour token by path, the reference tier included.
639    pub fn color(&self, path: &str) -> Option<Color32> {
640        self.resolved.color(path).map(color32)
641    }
642
643    /// Whether the theme is a dark one (its panels are dark).
644    pub fn dark_mode(&self) -> bool {
645        self.resolved
646            .color("surface.panel")
647            .is_some_and(egui_pop_tokens::Color::is_dark)
648    }
649
650    /// The tokens of the theme drawn now: of egui's theme of the moment
651    /// (`ctx.theme()`, the user's or the system's light or dark mode)
652    /// when a pair is installed, else of the theme installed; the
653    /// built-in `pop-dark` ones (installed on first use) when no theme
654    /// was. Read it while drawing, never keep it across frames: a switch
655    /// between light and dark changes it without any install.
656    ///
657    /// Inside a [`ScopedTheme`]'s `show`, they are the scoped theme's.
658    pub fn of(ctx: &Context) -> Arc<Tokens> {
659        if let Some(scoped) = ScopedTheme::current(ctx) {
660            return scoped.tokens;
661        }
662        Tokens::of_theme(ctx, ctx.theme())
663    }
664
665    /// The tokens installed for one of egui's themes (the same for both
666    /// when the theme installed is alone).
667    pub fn of_theme(ctx: &Context, theme: Theme) -> Arc<Tokens> {
668        variants(ctx).get(theme).clone()
669    }
670
671    /// The egui theme this set is drawn under.
672    pub fn egui_theme(&self) -> Theme {
673        if self.dark_mode() {
674            Theme::Dark
675        } else {
676            Theme::Light
677        }
678    }
679}
680
681/// The tokens installed, one set per egui theme: a theme and its
682/// counterpart, or the same theme twice when it is alone.
683#[derive(Clone, Debug)]
684pub struct Variants {
685    pub dark: Arc<Tokens>,
686    pub light: Arc<Tokens>,
687}
688
689impl Variants {
690    /// One theme for both of egui's themes.
691    pub fn alone(tokens: Arc<Tokens>) -> Variants {
692        Variants {
693            dark: tokens.clone(),
694            light: tokens,
695        }
696    }
697
698    /// The set for one of egui's themes.
699    pub fn get(&self, theme: Theme) -> &Arc<Tokens> {
700        match theme {
701            Theme::Dark => &self.dark,
702            Theme::Light => &self.light,
703        }
704    }
705
706    /// Whether a light and a dark theme are installed together: egui's
707    /// light or dark mode then chooses between them.
708    pub fn paired(&self) -> bool {
709        !Arc::ptr_eq(&self.dark, &self.light)
710    }
711}
712
713/// The tokens installed in a context, per egui theme; the built-in
714/// `pop-dark` ones, alone (installed on first use), when no theme was.
715pub fn variants(ctx: &Context) -> Variants {
716    TOKENS.get_or_insert_with(ctx, || Variants::alone(Arc::new(Tokens::default())))
717}
718
719/// Whether the theme installed has a counterpart: a light and a dark
720/// variant installed together ([`install_with`]).
721pub fn is_paired(ctx: &Context) -> bool {
722    variants(ctx).paired()
723}
724
725/// Asks for egui's light or dark mode, or the system's
726/// (`ThemePreference::System`): with a pair installed, it switches
727/// between the two at once, nothing installed again. A theme alone keeps
728/// its own mode whatever is asked.
729pub fn set_preference(ctx: &Context, preference: ThemePreference) {
730    let v = variants(ctx);
731    if v.paired() {
732        ctx.set_theme(preference);
733    } else {
734        ctx.set_theme(v.dark.egui_theme());
735    }
736}
737
738/// The tokens installed.
739const TOKENS: Slot<Variants> = Slot::opaque("core.theme.tokens");
740
741/// The scoped theme being drawn, if any.
742const SCOPED: Slot<ScopedTheme> = Slot::opaque("core.theme.scoped");
743
744/// A theme drawn in one part of a window without being installed: a
745/// theme's tokens, their kit and egui's style for them, applied to a
746/// child `Ui` ([`ScopedTheme::show`]). While it draws, [`Tokens::of`]
747/// and `Kit::of` give its tokens and kit, so egui-pop's widgets and
748/// custom painting follow it as egui's do; the rest of the window keeps
749/// the installed theme. A theme editor's preview, a themed island, a
750/// theme picker's thumbnails.
751///
752/// Popups follow it too. egui builds the `Ui` of a popup, a tooltip or
753/// a window from the context's style, not from the `Ui` that opened it,
754/// so while the scope draws, egui's context style is the scoped theme's
755/// as well (put back when it ends, even after a panic): a combo box's
756/// list, a tooltip, a context menu or a menu opened inside it, egui's
757/// or egui-pop's, is drawn in the scoped theme. A popup drawn later, out
758/// of the scope (egui-pop's `menus::popup_at`), records the scope it was
759/// opened in and draws within it ([`ScopedTheme::within`]).
760///
761/// What stays the installed theme's: fonts (egui's font definitions are
762/// global, rebuilt with the atlas), egui's light or dark mode
763/// (`ctx.theme()`), and what is drawn outside the scope. A change to the
764/// context's style made while the scope draws is undone when it ends:
765/// install themes between frames, as [`install_tokens`] says. Build it
766/// once per theme and keep it (compiling the kit has a cost), never per
767/// frame.
768///
769/// ```
770/// use egui_pop_core::theme::{self, ScopedTheme, ThemeSpec, Themes, Tokens};
771///
772/// let ctx = egui::Context::default();
773/// theme::install(&ctx, &ThemeSpec::new("pop-dark"));
774/// let light = ScopedTheme::new(&ctx, Tokens::new(Themes::default().resolve(&ThemeSpec::new("pop-light"))));
775/// ctx.run_ui(Default::default(), |ui| {
776///     light.show(ui, |ui| {
777///         assert!(!Tokens::of(ui.ctx()).dark_mode());
778///         assert!(!ui.visuals().dark_mode);
779///         // What a popup opened here is built from.
780///         assert!(!ui.ctx().global_style().visuals.dark_mode);
781///     });
782///     assert!(Tokens::of(ui.ctx()).dark_mode());
783///     assert!(ui.ctx().global_style().visuals.dark_mode);
784/// })
785/// .textures_delta
786/// .clear();
787/// ```
788#[derive(Clone)]
789pub struct ScopedTheme {
790    tokens: Arc<Tokens>,
791    kit: Arc<Kit>,
792    /// The context style made last: the style it was made from, the
793    /// scale, and the style. Shared by the clones.
794    context_style: Arc<Mutex<Option<ContextStyle>>>,
795}
796
797/// A scoped theme's style for the context, and what it was made from.
798struct ContextStyle {
799    base: Arc<Style>,
800    ppp: f32,
801    style: Arc<Style>,
802}
803
804impl std::fmt::Debug for ScopedTheme {
805    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
806        f.debug_struct("ScopedTheme")
807            .field("theme", &self.tokens.resolved().spec().label())
808            .finish_non_exhaustive()
809    }
810}
811
812impl ScopedTheme {
813    /// A theme to draw scoped, its kit compiled with the shapes
814    /// registered in `ctx` (kits' handlers).
815    pub fn new(ctx: &Context, tokens: Tokens) -> ScopedTheme {
816        let tokens = Arc::new(tokens);
817        let kit = crate::kit::compile_in(ctx, &tokens);
818        ScopedTheme {
819            tokens,
820            kit,
821            context_style: Arc::default(),
822        }
823    }
824
825    pub fn tokens(&self) -> &Arc<Tokens> {
826        &self.tokens
827    }
828
829    pub fn kit(&self) -> &Arc<Kit> {
830        &self.kit
831    }
832
833    /// The scoped theme drawing now, if any.
834    pub fn current(ctx: &Context) -> Option<ScopedTheme> {
835        SCOPED.get(ctx)
836    }
837
838    /// Draws `add` in a child `Ui` with this theme: egui's style for it,
839    /// and [`Tokens::of`] and `Kit::of` giving its tokens and kit until
840    /// `add` returns, as [`ScopedTheme::within`] does for the popups
841    /// opened in it (scopes nest; the previous one comes back, even when
842    /// `add` panics).
843    pub fn show<R>(&self, ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
844        let ctx = ui.ctx().clone();
845        let ppp = ctx.pixels_per_point();
846        self.within(&ctx, || {
847            ui.scope(|ui| {
848                let mut style = style_with(&self.tokens, &self.kit, ui.style());
849                snap_strokes(&mut style, ppp);
850                ui.set_style(style);
851                add(ui)
852            })
853            .inner
854        })
855    }
856
857    /// Runs `f` with this theme as the context's, without a `Ui` of its
858    /// own: [`Tokens::of`] and `Kit::of` give its tokens and kit, and
859    /// egui's context style (what egui builds popups, tooltips, menus
860    /// and windows from) is its style. Everything comes back when `f`
861    /// returns, even when it panics. For a popup drawn after the scope
862    /// that opened it has ended: record [`ScopedTheme::current`] when it
863    /// opens, and draw it within.
864    pub fn within<R>(&self, ctx: &Context, f: impl FnOnce() -> R) -> R {
865        // upstream: egui styles a popup's `Ui` from the context, not from
866        // the `Ui` that opened it (docs/upstream.md, "popups inside a
867        // scoped style").
868        struct Restore {
869            ctx: Context,
870            previous: Option<ScopedTheme>,
871            styles: (Arc<Style>, Arc<Style>),
872        }
873        impl Drop for Restore {
874            fn drop(&mut self) {
875                let (dark, light) = self.styles.clone();
876                self.ctx.options_mut(|o| {
877                    o.dark_style = dark;
878                    o.light_style = light;
879                });
880                match self.previous.take() {
881                    Some(p) => SCOPED.set(&self.ctx, p),
882                    None => {
883                        SCOPED.remove(&self.ctx);
884                    }
885                }
886            }
887        }
888        let style = self.context_style(&ctx.global_style(), ctx.pixels_per_point());
889        let previous = SCOPED.get(ctx);
890        let styles = ctx.options(|o| (o.dark_style.clone(), o.light_style.clone()));
891        SCOPED.set(ctx, self.clone());
892        let _restore = Restore {
893            ctx: ctx.clone(),
894            previous,
895            styles,
896        };
897        // Both of egui's styles: whatever its mode, the scope's is drawn.
898        ctx.options_mut(|o| {
899            o.dark_style = style.clone();
900            o.light_style = style;
901        });
902        f()
903    }
904
905    /// The context's style in this theme, made from `base` (the
906    /// context's style outside the scope) at a scale; made again only
907    /// when either changes.
908    fn context_style(&self, base: &Arc<Style>, ppp: f32) -> Arc<Style> {
909        let mut made = crate::state::lock(&self.context_style);
910        if let Some(m) = made.as_ref()
911            && Arc::ptr_eq(&m.base, base)
912            && m.ppp == ppp
913        {
914            return m.style.clone();
915        }
916        let mut style = style_with(&self.tokens, &self.kit, base);
917        snap_strokes(&mut style, ppp);
918        let style = Arc::new(style);
919        *made = Some(ContextStyle {
920            base: base.clone(),
921            ppp,
922            style: style.clone(),
923        });
924        style
925    }
926}
927
928fn radius(points: f32) -> CornerRadius {
929    CornerRadius::same(points.round().clamp(0.0, 255.0) as u8)
930}
931
932fn margin(points: f32) -> Margin {
933    Margin::same(points.round().clamp(0.0, 127.0) as i8)
934}
935
936/// egui's visuals for a theme.
937pub fn visuals(t: &Tokens) -> Visuals {
938    visuals_with(t, &Kit::compile(t, &Shapes::default()))
939}
940
941/// egui's visuals for a theme and its compiled kit: egui's widget states
942/// come from the kit's `button` (rest, hover, active, and selected for
943/// an open menu), text fields' background from its `field`. What egui
944/// cannot draw is in the kit's problems (`Kit::compile`).
945pub fn visuals_with(t: &Tokens, kit: &Kit) -> Visuals {
946    let mut v = if t.dark_mode() {
947        Visuals::dark()
948    } else {
949        Visuals::light()
950    };
951    v.panel_fill = t.surface.panel;
952    v.window_fill = t.surface.overlay;
953    v.extreme_bg_color = t.surface.sunken;
954    v.text_edit_bg_color = Some(kit.field.style(State::REST).fill);
955    v.faint_bg_color = t.surface.raised;
956    v.code_bg_color = t.surface.raised;
957    v.window_stroke = Stroke::new(1.0, t.border.default);
958    v.window_shadow = t.shadow.window;
959    v.popup_shadow = t.shadow.popup;
960    v.window_corner_radius = radius(t.radius.window);
961    v.menu_corner_radius = radius(t.radius.window);
962    v.hyperlink_color = t.accent.default;
963    v.warn_fg_color = t.status.warning;
964    v.error_fg_color = t.status.danger;
965    v.weak_text_color = Some(t.text.muted);
966    v.selection.bg_fill = t.selection;
967    v.selection.stroke = Stroke::new(1.0, t.text.strong);
968    v.text_cursor.stroke = Stroke::new(2.0, t.text.strong);
969    v.text_cursor.blink = t.motion_duration > 0.0;
970
971    let w = &mut v.widgets;
972    let rest = kit.button.style(State::REST);
973    w.noninteractive.bg_fill = t.surface.panel;
974    w.noninteractive.weak_bg_fill = t.surface.panel;
975    w.noninteractive.bg_stroke = Stroke::new(rest.border_width, t.border.default);
976    w.noninteractive.fg_stroke = Stroke::new(1.0, t.text.default);
977    w.noninteractive.corner_radius = radius(rest.radius);
978    // The same mapping as a `Stock::Button` scope (`Kit::scope`), for
979    // every egui widget.
980    kit.scoped
981        .get(crate::kit::Stock::Button, crate::kit::Tone::Neutral)
982        .apply_widgets(&mut v);
983    v
984}
985
986/// egui's style for a theme, built over `base` (whose settings the theme
987/// does not decide are kept).
988pub fn style(t: &Tokens, base: &Style) -> Style {
989    style_with(t, &Kit::compile(t, &Shapes::default()), base)
990}
991
992/// [`style`] with a compiled kit (the one installed with the theme).
993pub fn style_with(t: &Tokens, kit: &Kit, base: &Style) -> Style {
994    let mut style = base.clone();
995    style.visuals = visuals_with(t, kit);
996    for (text_style, size) in [
997        (TextStyle::Small, t.font.small),
998        (TextStyle::Body, t.font.body),
999        (TextStyle::Button, t.font.button),
1000        (TextStyle::Heading, t.font.heading),
1001        (TextStyle::Monospace, t.font.mono),
1002    ] {
1003        if let Some(font) = style.text_styles.get_mut(&text_style) {
1004            font.size = size.max(4.0);
1005        }
1006    }
1007    let s = &t.space;
1008    let sp = &mut style.spacing;
1009    sp.item_spacing = egui::vec2(s.m, s.s);
1010    sp.button_padding = egui::vec2(s.s + s.xs, s.xs);
1011    sp.window_margin = margin(s.l);
1012    sp.menu_margin = margin(s.m);
1013    sp.interact_size.y = t.size.control_height;
1014    sp.icon_width = t.size.icon_inline;
1015    sp.icon_width_inner = (t.size.icon_inline * 0.6).round();
1016    // Below 4px a checkbox or radio reads as glued to its label, which the
1017    // compact density's 2px small space would do.
1018    sp.icon_spacing = s.s.max(4.0);
1019    sp.indent = t.size.icon_toolbar;
1020    // Every scroll area's bars, from the kit's `scroll-bar`.
1021    sp.scroll = kit.scroll.style(&sp.scroll);
1022    // Under reduced motion, a scroll area stops where the finger leaves it: no
1023    // coasting after a touch drag, and no stretching past an end on a trackpad
1024    // or a touch screen (egui's rubber band). A mouse wheel has neither.
1025    // A theme with motion installed over one without gets egui's back.
1026    let kinetic = base.spacing.scroll.kinetic;
1027    let still = KineticScrollStyle {
1028        decay_time: 0.0,
1029        rubber_band: false,
1030        ..kinetic
1031    };
1032    sp.scroll.kinetic = if t.motion_duration == 0.0 {
1033        still
1034    } else if kinetic == still {
1035        KineticScrollStyle::default()
1036    } else {
1037        kinetic
1038    };
1039    // A strip that scrolls only one way takes the plain wheel: egui's default
1040    // wants Shift for a horizontal strip, which nobody finds on a strip with no
1041    // bar.
1042    style.always_scroll_the_only_direction = true;
1043    style.animation_time = t.motion_duration;
1044    if t.motion_duration == 0.0 {
1045        style.scroll_animation = ScrollAnimation::none();
1046    }
1047    style
1048}
1049
1050/// Snaps a style's stroke widths to whole physical pixels at `ppp`
1051/// (`scale::snap`), so 1 point borders stay one sharp pixel at 1.25 or
1052/// 1.5. `install_tokens` does it for the scale of the window it runs in;
1053/// egui-pop's application installs the theme again when that scale
1054/// changes.
1055pub fn snap_strokes(style: &mut Style, ppp: f32) {
1056    let snap = |w: f32| crate::scale::snap(w, ppp);
1057    let v = &mut style.visuals;
1058    v.window_stroke.width = snap(v.window_stroke.width);
1059    v.selection.stroke.width = snap(v.selection.stroke.width);
1060    v.text_cursor.stroke.width = snap(v.text_cursor.stroke.width);
1061    for w in [
1062        &mut v.widgets.noninteractive,
1063        &mut v.widgets.inactive,
1064        &mut v.widgets.hovered,
1065        &mut v.widgets.active,
1066        &mut v.widgets.open,
1067    ] {
1068        w.bg_stroke.width = snap(w.bg_stroke.width);
1069        w.fg_stroke.width = snap(w.fg_stroke.width);
1070    }
1071}
1072
1073/// Installs typed tokens into a context, alone: egui's dark and light
1074/// styles both become the theme's and egui's mode is forced to the
1075/// theme's (so the system's light or dark preference does not swap it
1076/// out), and [`Tokens::of`] returns them. Call it between frames (at
1077/// start-up, or when the user picks another theme), not while drawing.
1078pub fn install_tokens(ctx: &Context, tokens: Tokens) -> Arc<Tokens> {
1079    install_variants(ctx, tokens, None)
1080}
1081
1082/// Installs a theme and, when given one of the other mode, its
1083/// counterpart: each is written into its own egui style (dark or light)
1084/// with its own kit, and [`Tokens::of`] and `Kit::of` give the one of
1085/// egui's theme of the moment. egui's mode is set to the theme's (the
1086/// first one), as when it is alone, and it is egui's fallback when the
1087/// system says nothing; [`set_preference`] (or `ctx.set_theme`) then
1088/// switches between the two, or follows the system, without installing
1089/// anything again. A counterpart of the same mode is ignored (with a
1090/// warning): the theme is installed alone. Fonts and icon sizes come
1091/// from the first theme. Returns the first theme's tokens.
1092pub fn install_variants(ctx: &Context, tokens: Tokens, counterpart: Option<Tokens>) -> Arc<Tokens> {
1093    let tokens = Arc::new(tokens);
1094    let counterpart = counterpart.filter(|c| {
1095        let other = c.dark_mode() != tokens.dark_mode();
1096        if !other {
1097            log::warn!(
1098                target: "egui_pop",
1099                "theme: `{}` and `{}` are both {}: installed alone",
1100                tokens.resolved().spec().base,
1101                c.resolved().spec().base,
1102                if tokens.dark_mode() { "dark" } else { "light" }
1103            );
1104        }
1105        other
1106    });
1107    let variants = match counterpart {
1108        None => Variants::alone(tokens.clone()),
1109        Some(c) if tokens.dark_mode() => Variants {
1110            dark: tokens.clone(),
1111            light: Arc::new(c),
1112        },
1113        Some(c) => Variants {
1114            dark: Arc::new(c),
1115            light: tokens.clone(),
1116        },
1117    };
1118    let mode = tokens.egui_theme();
1119    ctx.set_theme(mode);
1120    ctx.options_mut(|o| o.fallback_theme = mode);
1121    // The kits first: egui's styles are drawn from them.
1122    let kits = crate::kit::install_variants(ctx, &variants.dark, &variants.light);
1123    let ppp = ctx.pixels_per_point();
1124    for theme in [Theme::Dark, Theme::Light] {
1125        let t = variants.get(theme);
1126        let kit = kits.get(theme);
1127        ctx.style_mut_of(theme, |s| {
1128            *s = style_with(t, kit, s);
1129            snap_strokes(s, ppp);
1130        });
1131    }
1132    TOKENS.set(ctx, variants);
1133    crate::fonts::install_with_offsets(
1134        ctx,
1135        &tokens.font.family_ui,
1136        &tokens.font.family_mono,
1137        tokens.font.baseline_offsets,
1138    );
1139    crate::icon_set::install(ctx, &tokens);
1140    tokens
1141}
1142
1143/// Resolves a spec against the given themes and installs it. Problems
1144/// (a broken user theme, a typo in an override) are in
1145/// `tokens.resolved().problems()`; the theme is installed anyway, with
1146/// fallbacks.
1147/// The spec's counterpart, when it has one ([`ThemeSpec::counterpart`],
1148/// the token files' `org.egui-pop.variant-of`), is installed with it
1149/// ([`install_variants`]).
1150pub fn install_with(ctx: &Context, themes: &Themes, spec: &ThemeSpec) -> Arc<Tokens> {
1151    install_variants(
1152        ctx,
1153        Tokens::new(themes.resolve(spec)),
1154        themes.resolve_counterpart(spec).map(Tokens::new),
1155    )
1156}
1157
1158/// Resolves a spec against the built-in themes and installs it.
1159pub fn install(ctx: &Context, spec: &ThemeSpec) -> Arc<Tokens> {
1160    install_with(ctx, &Themes::default(), spec)
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165    use super::*;
1166
1167    fn tokens(name: &str) -> Tokens {
1168        Tokens::new(Themes::default().resolve(&ThemeSpec::new(name)))
1169    }
1170
1171    #[test]
1172    fn scoped_themes_nest_and_come_back_even_after_a_panic() {
1173        let ctx = Context::default();
1174        install(&ctx, &ThemeSpec::new("pop-dark"));
1175        let light = ScopedTheme::new(&ctx, tokens("pop-light"));
1176        let hc = ScopedTheme::new(&ctx, tokens("pop-high-contrast"));
1177        let base = |ctx: &Context| Tokens::of(ctx).resolved().spec().base.clone();
1178        let installed = ctx.style_of(Theme::Dark);
1179        let mut out = ctx.run_ui(Default::default(), |ui| {
1180            light.show(ui, |ui| {
1181                assert_eq!(base(ui.ctx()), "pop-light");
1182                assert!(Arc::ptr_eq(&Kit::of(ui.ctx()), light.kit()));
1183                hc.show(ui, |ui| assert_eq!(base(ui.ctx()), "pop-high-contrast"));
1184                assert_eq!(base(ui.ctx()), "pop-light");
1185                let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1186                    hc.show(ui, |_| panic!("a widget fails"));
1187                }));
1188                assert!(caught.is_err());
1189                assert_eq!(base(ui.ctx()), "pop-light");
1190                // The context's style (popups) is the scope's, back
1191                // after the panic.
1192                assert!(!ui.ctx().global_style().visuals.dark_mode);
1193                assert!(!ui.ctx().style_of(Theme::Dark).visuals.dark_mode);
1194            });
1195            assert_eq!(base(ui.ctx()), "pop-dark");
1196            assert!(ScopedTheme::current(ui.ctx()).is_none());
1197            assert_eq!(*ui.ctx().style_of(Theme::Dark), *installed);
1198        });
1199        out.textures_delta.clear();
1200    }
1201}