Skip to main content

crisol_ui_kit/foundation/theme/
apply.rs

1//! Applying theme tokens to an egui context.
2
3use egui::style::{WidgetVisuals, Widgets};
4use egui::{Color32, Stroke};
5
6use super::{ANIMATION_TIME, Theme, ThemeId, ThemeMode, effective_id};
7
8/// Whether the desktop currently prefers a dark theme.
9pub fn system_is_dark(ctx: &egui::Context) -> bool {
10    ctx.input(|input| input.raw.system_theme)
11        .is_some_and(|theme| theme == egui::Theme::Dark)
12}
13
14/// Apply the GitHub light or dark theme.
15pub fn apply(ctx: &egui::Context, mode: ThemeMode) {
16    apply_id(
17        ctx,
18        match mode {
19            ThemeMode::Light => ThemeId::GithubLight,
20            ThemeMode::Dark => ThemeId::GithubDark,
21            _ => ThemeId::GithubLight,
22        },
23    );
24}
25
26/// Apply a theme, following the system light/dark preference when requested.
27pub fn apply_theme(ctx: &egui::Context, id: ThemeId, follow_system: bool) -> ThemeId {
28    let effective = effective_id(id, follow_system, system_is_dark(ctx));
29    apply_id(ctx, effective);
30    effective
31}
32
33/// Apply a theme identifier: visuals, widget states, spacing, scrollbars, and type scale.
34pub fn apply_id(ctx: &egui::Context, id: ThemeId) {
35    apply_tokens(ctx, &Theme::for_id(id));
36}
37
38/// Apply any set of tokens, built-in or your own (see [`Theme::with_accent`] and
39/// [`Theme::accessibility_issues`]). The light or dark egui base follows
40/// [`Theme::is_dark`]; the installed [`crate::style::WorkbenchStyle`] is kept.
41pub fn apply_tokens(ctx: &egui::Context, theme: &Theme) {
42    let theme = *theme;
43    ctx.data_mut(|data| data.insert_temp(current_key(), theme));
44    let mut visuals = if theme.is_dark() {
45        egui::Visuals::dark()
46    } else {
47        egui::Visuals::light()
48    };
49    visuals.panel_fill = theme.background;
50    visuals.window_fill = theme.surface;
51    visuals.faint_bg_color = theme.hover;
52    visuals.extreme_bg_color = theme.sunken;
53    visuals.hyperlink_color = theme.link;
54    visuals.selection.bg_fill = theme.selection;
55    visuals.selection.stroke = Stroke::new(1.0, theme.text);
56    visuals.window_stroke = Stroke::new(1.0, theme.border);
57    // Semantic colors come from the theme, not egui's saturated #FF0000 / #FF6400, so
58    // danger and warning text meets AA on every surface.
59    visuals.error_fg_color = theme.danger;
60    visuals.warn_fg_color = theme.warning;
61
62    paint_widgets(&mut visuals.widgets, &theme);
63    visuals.override_text_color = Some(theme.text);
64    // Glyphs on whole device pixels. Sub-pixel binning renders each glyph at a
65    // quarter-pixel offset, which at fractional scales (zoom 110%, a 1.25 desktop
66    // factor) smears every stem over two pixels. Hinting snaps outlines to the grid.
67    visuals.text_options.subpixel_binning = false;
68    visuals.text_options.font_hinting = true;
69
70    ctx.all_styles_mut(|style| {
71        style.visuals = visuals.clone();
72        style.spacing.item_spacing = egui::vec2(8.0, 4.0);
73        style.spacing.button_padding = egui::vec2(8.0, 3.0);
74        style.spacing.interact_size = egui::vec2(26.0, 24.0);
75        style.spacing.menu_margin = egui::Margin::same(4);
76        style.spacing.scroll.bar_width = 6.0;
77        style.spacing.scroll.floating_width = 3.0;
78        style.spacing.scroll.floating_allocated_width = 4.0;
79        style.spacing.scroll.bar_inner_margin = 2.0;
80        style.animation_time = ANIMATION_TIME;
81    });
82    // Radii, border widths, and the type scale come from the installed style.
83    crate::foundation::style::apply_to_egui(ctx, &crate::foundation::style::get(ctx));
84}
85
86/// The five widget states. Fills come from the tokens; every state shares a 1 px
87/// focus-colored foreground stroke before the per-state overrides. Radii and border
88/// widths are set afterwards from the [`crate::style::WorkbenchStyle`].
89fn paint_widgets(widgets: &mut Widgets, theme: &Theme) {
90    let foreground = Stroke::new(1.0, theme.focus);
91    let states: [(&mut WidgetVisuals, Color32); 5] = [
92        (&mut widgets.noninteractive, theme.background),
93        (&mut widgets.inactive, theme.surface),
94        (&mut widgets.hovered, theme.hover),
95        (&mut widgets.active, theme.accent),
96        (&mut widgets.open, theme.surface),
97    ];
98    for (state, fill) in states {
99        state.bg_fill = fill;
100        state.weak_bg_fill = fill;
101        state.fg_stroke = foreground;
102    }
103    widgets.inactive.weak_bg_fill = theme.surface;
104    widgets.inactive.bg_stroke = theme.border_stroke();
105    widgets.hovered.bg_stroke = Stroke::new(1.0, theme.focus);
106    widgets.active.fg_stroke = Stroke::new(1.0, theme.text);
107    widgets.active.bg_stroke = Stroke::new(2.0, theme.focus);
108    widgets.noninteractive.bg_stroke = Stroke::new(1.0, theme.border);
109}
110
111fn current_key() -> egui::Id {
112    egui::Id::unique("crisol::theme::current")
113}
114
115/// The tokens of the theme last applied with [`apply_id`] (or [`apply_theme`]).
116///
117/// Components use it for the roles egui's visuals do not carry, such as
118/// `success`. Falls back to GitHub Light or Dark, following the current visuals,
119/// when no theme was applied.
120pub fn current(ctx: &egui::Context) -> Theme {
121    ctx.data(|data| data.get_temp::<Theme>(current_key()))
122        .unwrap_or_else(|| {
123            if ctx.style_of(ctx.theme()).visuals.dark_mode {
124                Theme::dark()
125            } else {
126                Theme::light()
127            }
128        })
129}
130
131/// Whether animations are on (reduced motion sets the animation time to zero).
132pub fn motion_enabled(ctx: &egui::Context) -> bool {
133    ctx.style_of(ctx.theme()).animation_time > 0.0
134}
135
136/// Turn animations off for reduced-motion preferences, or back on.
137pub fn set_reduced_motion(ctx: &egui::Context, reduced: bool) {
138    ctx.all_styles_mut(|style| {
139        style.animation_time = if reduced { 0.0 } else { ANIMATION_TIME };
140    });
141}