Skip to main content

glassy_ui/theme/
active.rs

1use gpui::{App, Context, Global};
2
3use super::{Theme, ThemeKind};
4
5#[derive(Clone, Copy)]
6struct ActiveThemeState(Theme);
7
8impl Global for ActiveThemeState {}
9
10/// Install the default light theme. Call once at app startup.
11pub fn init(cx: &mut App) {
12    if !cx.has_global::<ActiveThemeState>() {
13        cx.set_global(ActiveThemeState(Theme::light()));
14    }
15}
16
17/// Read and switch the process-wide theme.
18///
19/// ```ignore
20/// init(cx);
21/// let theme = cx.theme();
22/// div().bg(theme.canvas);
23///
24/// cx.toggle_theme();
25/// cx.set_theme(Theme::dark());
26/// cx.set_theme_name("light");
27/// ```
28pub trait ActiveTheme {
29    fn theme(&self) -> Theme;
30    fn set_theme(&mut self, theme: Theme);
31    fn set_theme_kind(&mut self, kind: ThemeKind);
32    fn set_theme_name(&mut self, name: &str) -> bool;
33    fn toggle_theme(&mut self);
34}
35
36impl ActiveTheme for App {
37    fn theme(&self) -> Theme {
38        if self.has_global::<ActiveThemeState>() {
39            self.global::<ActiveThemeState>().0
40        } else {
41            Theme::light()
42        }
43    }
44
45    fn set_theme(&mut self, theme: Theme) {
46        self.set_global(ActiveThemeState(theme));
47        self.refresh_windows();
48    }
49
50    fn set_theme_kind(&mut self, kind: ThemeKind) {
51        self.set_theme(Theme::for_kind(kind));
52    }
53
54    fn set_theme_name(&mut self, name: &str) -> bool {
55        if let Some(theme) = Theme::named(name) {
56            self.set_theme(theme);
57            true
58        } else {
59            false
60        }
61    }
62
63    fn toggle_theme(&mut self) {
64        let next = self.theme().toggle();
65        self.set_theme(next);
66    }
67}
68
69impl<T> ActiveTheme for Context<'_, T> {
70    fn theme(&self) -> Theme {
71        App::theme(self)
72    }
73
74    fn set_theme(&mut self, theme: Theme) {
75        App::set_theme(self, theme);
76    }
77
78    fn set_theme_kind(&mut self, kind: ThemeKind) {
79        App::set_theme_kind(self, kind);
80    }
81
82    fn set_theme_name(&mut self, name: &str) -> bool {
83        App::set_theme_name(self, name)
84    }
85
86    fn toggle_theme(&mut self) {
87        App::toggle_theme(self);
88    }
89}