Skip to main content

herogpui_theme/
provider.rs

1//! Global theme provider — the HeroGPUI equivalent of `HeroUIProvider`.
2
3use std::collections::HashMap;
4
5use gpui::{AnyWindowHandle, App, Global, SharedString, Subscription, Window, WindowAppearance};
6
7use crate::layout::LayoutTheme;
8use crate::semantic::{RoleColor, ThemeColors};
9use crate::theme::{Appearance, Theme};
10use herogpui_core::Color;
11
12/// Holds the active theme, any registered custom themes, and the opt-in
13/// "follow the OS appearance" mode.
14///
15/// The reduced-motion preference is deliberately *not* a field here. GPUI owns
16/// that flag (`App::reduce_motion`) and its own `Animation`/spring elements read
17/// it directly, so a copy on this global would be a second source of truth: a
18/// consumer app writing a plain `gpui::Animation`, or any GPUI internal such as
19/// animated-image playback, would keep animating after HeroGPUI was told to
20/// stop. `ActiveTheme::reduce_motion` therefore reads GPUI's flag and
21/// [`set_reduce_motion`] writes it, so the two cannot disagree.
22pub struct ThemeProvider {
23    active: SharedString,
24    themes: HashMap<SharedString, Theme>,
25    /// Set only by [`follow_system_appearance`]; nothing else may turn it on.
26    /// Following the OS is opt-in because an app that pins `Appearance::Light`
27    /// through `init_with`/`use_theme` means it, and must keep it.
28    follow_system_appearance: bool,
29    /// One retained appearance observer per followed window, keyed so a root
30    /// view that re-registers on rebuild replaces its observer instead of
31    /// stacking a second one. Retention is the point: `Subscription` is
32    /// unsubscribe-on-drop, so a discarded handle syncs once and then goes
33    /// quiet forever — the classic failure here.
34    appearance_observers: HashMap<AnyWindowHandle, Subscription>,
35}
36
37impl Global for ThemeProvider {}
38
39impl ThemeProvider {
40    /// Registers the provider with the default light theme.
41    ///
42    /// Call this once before opening the first window. Rendering a themed
43    /// component before initialization panics.
44    pub fn init(cx: &mut App) {
45        Self::init_with(Theme::light(), cx);
46    }
47
48    /// Registers the provider starting from an explicit theme.
49    ///
50    /// Call this once before opening the first window. Rendering a themed
51    /// component before initialization panics.
52    pub fn init_with(theme: Theme, cx: &mut App) {
53        let mut themes = HashMap::new();
54        themes.insert("light".into(), Theme::light());
55        themes.insert("dark".into(), Theme::dark());
56        let id = theme.id.clone();
57        themes.insert(id.clone(), theme);
58        // gpui does not surface the OS `prefers-reduced-motion` setting, so the
59        // env var stands in for it; `set_reduce_motion` is the app-level
60        // override, matching v3's `data-reduce-motion` precedence.
61        let reduce_motion = std::env::var("HEROGPUI_REDUCE_MOTION")
62            .is_ok_and(|v| v != "0" && !v.eq_ignore_ascii_case("false"));
63        cx.set_global(Self {
64            active: id,
65            themes,
66            follow_system_appearance: false,
67            appearance_observers: HashMap::new(),
68        });
69        // The global has to exist first: GPUI's setter refreshes every window
70        // when the value changes, and a themed window repainting before
71        // `set_global` would panic looking for the provider. GPUI's own default
72        // is a plain `false` seeded at app construction (it reads no OS
73        // setting), so writing the env-var seed here clobbers nothing.
74        cx.set_reduce_motion(reduce_motion);
75    }
76
77    pub fn get(cx: &App) -> &Self {
78        cx.global::<ThemeProvider>()
79    }
80
81    pub fn theme(&self) -> &Theme {
82        // `set_active` refuses ids that are not registered and `register`
83        // inserts before it activates, so the active id always resolves.
84        // Should that invariant ever break, fall back to the built-in light
85        // theme rather than panicking on every frame.
86        self.themes
87            .get(&self.active)
88            .or_else(|| self.themes.get("light"))
89            .expect("the built-in light theme is registered by `init_with` and never removed")
90    }
91
92    /// Whether a theme with this id has been registered.
93    pub fn contains(&self, id: &str) -> bool {
94        self.themes.contains_key(id)
95    }
96
97    pub fn active_id(&self) -> &SharedString {
98        &self.active
99    }
100
101    /// Registers and activates a custom theme.
102    pub fn register(&mut self, theme: Theme) {
103        self.active = theme.id.clone();
104        self.themes.insert(theme.id.clone(), theme);
105    }
106
107    /// Registers a theme without activating it, replacing any theme with
108    /// the same id. The active theme is unchanged (re-inserting the active
109    /// id swaps its tokens in place).
110    pub fn insert(&mut self, theme: Theme) {
111        self.themes.insert(theme.id.clone(), theme);
112    }
113
114    /// The ids of every registered theme, sorted.
115    pub fn theme_ids(&self) -> Vec<SharedString> {
116        let mut ids: Vec<_> = self.themes.keys().cloned().collect();
117        ids.sort();
118        ids
119    }
120
121    /// Activates a previously registered theme by id.
122    ///
123    /// An id that was never registered is refused: the active theme stays as
124    /// it was and the error carries the rejected id.
125    pub fn set_active(&mut self, id: impl Into<SharedString>) -> Result<(), UnknownThemeError> {
126        let id = id.into();
127        if !self.themes.contains_key(&id) {
128            return Err(UnknownThemeError { id });
129        }
130        self.active = id;
131        Ok(())
132    }
133
134    /// Whether the OS light/dark appearance is being followed — the state a
135    /// three-way "Light / Dark / System" setting needs to render itself.
136    pub fn follows_system_appearance(&self) -> bool {
137        self.follow_system_appearance
138    }
139}
140
141/// Convenience extension trait giving every GPUI context access to the theme.
142///
143/// Works with `&App`, `&mut App`, `Context<T>` (they deref to `App`).
144pub trait ActiveTheme {
145    fn theme(&self) -> &Theme;
146    fn colors(&self) -> &ThemeColors;
147    fn layout(&self) -> &LayoutTheme;
148    fn components(&self) -> &crate::ComponentThemes;
149    fn role(&self, color: Color) -> &RoleColor;
150    fn is_dark_theme(&self) -> bool;
151    /// Whether animations should be suppressed. Components must check this
152    /// before animating; v3 requires no opt-in from the caller.
153    fn reduce_motion(&self) -> bool;
154}
155
156impl ActiveTheme for App {
157    fn theme(&self) -> &Theme {
158        ThemeProvider::get(self).theme()
159    }
160
161    fn colors(&self) -> &ThemeColors {
162        &self.theme().colors
163    }
164
165    fn layout(&self) -> &LayoutTheme {
166        &self.theme().layout
167    }
168
169    fn components(&self) -> &crate::ComponentThemes {
170        &self.theme().components
171    }
172
173    fn role(&self, color: Color) -> &RoleColor {
174        match color {
175            Color::Default => &self.colors().default,
176            Color::Accent => &self.colors().accent,
177            Color::Success => &self.colors().success,
178            Color::Warning => &self.colors().warning,
179            Color::Danger => &self.colors().danger,
180        }
181    }
182
183    fn is_dark_theme(&self) -> bool {
184        self.theme().is_dark()
185    }
186
187    fn reduce_motion(&self) -> bool {
188        // GPUI's flag is the single source of truth (see `ThemeProvider`), and
189        // `App::reduce_motion` is spelled out rather than called as
190        // `self.reduce_motion()` because that would resolve to this very trait
191        // method through the inherent-first rule only by luck — inherent wins,
192        // so the shorthand happens to work and reads like infinite recursion.
193        App::reduce_motion(self)
194    }
195}
196
197/// Sets the global theme and schedules every open window to repaint.
198pub fn set_theme(theme: Theme, cx: &mut App) {
199    let provider = cx.global_mut::<ThemeProvider>();
200    provider.register(theme);
201    cx.refresh_windows();
202}
203
204/// The error [`use_theme`] and [`ThemeProvider::set_active`] return for an id
205/// that no registered theme carries (ids are case-sensitive: `"Dark"` is not
206/// `"dark"`).
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct UnknownThemeError {
209    /// The id that was asked for.
210    pub id: SharedString,
211}
212
213impl std::fmt::Display for UnknownThemeError {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        write!(
216            f,
217            "no theme is registered under the id {:?}",
218            self.id.as_ref()
219        )
220    }
221}
222
223impl std::error::Error for UnknownThemeError {}
224
225/// Activates one of the registered themes by id (`"light"`, `"dark"`, custom)
226/// and schedules every open window to repaint.
227///
228/// An unknown id is an error, not a panic: the active theme is left unchanged,
229/// no window repaints, and the rejected id comes back in
230/// [`UnknownThemeError`].
231pub fn use_theme(id: impl Into<SharedString>, cx: &mut App) -> Result<(), UnknownThemeError> {
232    let provider = cx.global_mut::<ThemeProvider>();
233    provider.set_active(id)?;
234    cx.refresh_windows();
235    Ok(())
236}
237
238/// Sets the app-level reduced-motion preference — the equivalent of putting
239/// `data-reduce-motion="true"` on the document element — and schedules every
240/// open window to repaint. Every animated component honours it without opt-in,
241/// and so does every plain `gpui::Animation`: the value is stored in GPUI's own
242/// global, which its animation elements consult themselves.
243pub fn set_reduce_motion(v: bool, cx: &mut App) {
244    cx.set_reduce_motion(v);
245    // GPUI's setter already refreshes on a *change*; this repaints on a
246    // no-change write too, which is the contract `theme_repaint.rs` pins for
247    // every provider mutation.
248    cx.refresh_windows();
249}
250
251/// Flips the reduced-motion preference.
252pub fn toggle_reduce_motion(cx: &mut App) {
253    let next = !App::reduce_motion(cx);
254    set_reduce_motion(next, cx);
255}
256
257/// Follows the OS light/dark appearance for as long as `window` stays open,
258/// activating the registered `"light"` or `"dark"` theme to match.
259///
260/// Opt-in on purpose: without this call the app keeps whatever theme it
261/// activated, so pinning a single appearance stays possible. Call it once per
262/// window, from the window's root-view constructor. A custom theme pair can
263/// join in by registering under the ids `"light"` and `"dark"`, which is what
264/// the switch reads.
265///
266/// The current appearance is applied immediately, so a window opened on a dark
267/// desktop does not paint one light frame first.
268///
269/// `App::should_auto_hide_scrollbars` is read by the painted `Scrollbar`
270/// overlay: thumbs hide after idle when the OS preference is on, and stay
271/// painted when it is off.
272pub fn follow_system_appearance(window: &mut Window, cx: &mut App) {
273    // The per-window `appearance()` over `App::window_appearance()`: it is the
274    // value the observer below reports, so the immediate sync and every later
275    // sync agree, and the app-level platform query is the one that misbehaves
276    // on Linux (longbridge/gpui-kit#104).
277    let subscription = window.observe_window_appearance(|window, cx| {
278        apply_system_appearance(window.appearance(), cx);
279    });
280    let handle = window.window_handle();
281    let appearance = window.appearance();
282
283    let provider = cx.global_mut::<ThemeProvider>();
284    provider.follow_system_appearance = true;
285    // Moving the `Subscription` into the global is what keeps the observer
286    // alive; binding it to a local here would unsubscribe at the end of this
287    // function and the OS switch would silently stop arriving.
288    provider.appearance_observers.insert(handle, subscription);
289
290    apply_system_appearance(appearance, cx);
291}
292
293/// Stops following the OS appearance, leaving the active theme as it is.
294pub fn stop_following_system_appearance(cx: &mut App) {
295    let provider = cx.global_mut::<ThemeProvider>();
296    provider.follow_system_appearance = false;
297    // Dropping the subscriptions is the unsubscribe. Clearing only the flag
298    // would leave live observers calling back into a mode that is off.
299    provider.appearance_observers.clear();
300}
301
302/// Activates the theme matching one OS appearance, if the mode is still on.
303fn apply_system_appearance(appearance: WindowAppearance, cx: &mut App) {
304    let provider = ThemeProvider::get(cx);
305    if !provider.follows_system_appearance() {
306        return;
307    }
308    let id = match Appearance::from(appearance) {
309        Appearance::Light => "light",
310        Appearance::Dark => "dark",
311    };
312    // A window reports its appearance on unrelated occasions too (and every
313    // followed window reports the same OS switch), so skip the no-op rather
314    // than repainting every window once per redundant notification.
315    if provider.active_id().as_ref() == id {
316        return;
317    }
318    // Both ids are registered by `init_with`; a custom pair replaces them
319    // under the same ids, so this cannot miss.
320    let _ = use_theme(id, cx);
321}
322
323/// Switches between the light and dark defaults.
324pub fn toggle_light_dark(cx: &mut App) {
325    let dark = cx.theme().is_dark();
326    let next = if dark { "light" } else { "dark" };
327    // Registered by `init_with`, so this cannot miss.
328    let _ = use_theme(next, cx);
329}