Skip to main content

native_gui_core/
theme.rs

1//! Theme tokens and light/dark modes.
2//!
3//! A resolved, backend-agnostic token set (colors, spacing, typography) plus
4//! the per-widget override vocabulary. Native application lands
5//! (GTK CSS, Win32 brushes/colors, Cocoa appearance); the `Backend` defaults
6//! return the typed capability error until then, so a request is never
7//! silently ignored. See `docs/widget-expansion-roadmap.md` ("Theming and art
8//! provider") for the design and evidence rules.
9
10use crate::widgets::Color;
11
12/// Light/dark mode selector.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum ThemeMode {
15    Light,
16    Dark,
17}
18
19impl ThemeMode {
20    /// Stable lowercase identifier used by tests and diagnostics.
21    pub fn as_str(self) -> &'static str {
22        match self {
23            Self::Light => "light",
24            Self::Dark => "dark",
25        }
26    }
27}
28
29/// Backend capability flags for system light/dark detection.
30///
31/// A backend that cannot observe the OS preference reports
32/// [`ThemeCapabilities::none`] and returns `None` from
33/// `Backend::system_theme_mode`, so apps can gate their follow-the-system
34/// logic on real support instead of guessing.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
36pub struct ThemeCapabilities {
37    /// The backend can report the OS light/dark preference through
38    /// `Backend::system_theme_mode`.
39    pub system_detection: bool,
40    /// The backend reports light/dark transitions through
41    /// [`crate::UiEvent::ThemeChanged`] as the OS preference changes.
42    pub change_events: bool,
43    /// The backend can detect the OS high-contrast accessibility mode.
44    pub high_contrast_detection: bool,
45}
46
47impl ThemeCapabilities {
48    /// No detection and no change events.
49    pub const fn none() -> Self {
50        Self {
51            system_detection: false,
52            change_events: false,
53            high_contrast_detection: false,
54        }
55    }
56
57    /// Full detection with change events (native backends, injectable Mock).
58    pub const fn all() -> Self {
59        Self {
60            system_detection: true,
61            change_events: true,
62            high_contrast_detection: true,
63        }
64    }
65}
66
67/// Named colors resolved by a theme.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub struct ThemeColors {
70    /// Window/workspace background.
71    pub background: Color,
72    /// Card/panel surface.
73    pub surface: Color,
74    /// Primary text color.
75    pub text: Color,
76    /// Secondary/label text color.
77    pub text_muted: Color,
78    /// Accent color (selection, links, focused outlines).
79    pub accent: Color,
80    /// Separator/border color.
81    pub border: Color,
82    /// Warning severity color.
83    pub warning: Color,
84    /// Error severity color.
85    pub error: Color,
86}
87
88/// Spacing scale in logical pixels.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct ThemeSpacing {
91    pub xs: i32,
92    pub sm: i32,
93    pub md: i32,
94    pub lg: i32,
95    pub xl: i32,
96}
97
98/// Typography scale in points.
99#[derive(Debug, Clone, Copy, PartialEq)]
100pub struct ThemeTypography {
101    pub body_size: f32,
102    pub label_size: f32,
103    pub title_size: f32,
104    pub heading_size: f32,
105}
106
107/// A fully resolved theme.
108#[derive(Debug, Clone, PartialEq)]
109pub struct Theme {
110    pub mode: ThemeMode,
111    pub colors: ThemeColors,
112    pub spacing: ThemeSpacing,
113    pub typography: ThemeTypography,
114}
115
116impl Theme {
117    /// Built-in light theme.
118    pub fn light() -> Self {
119        Self {
120            mode: ThemeMode::Light,
121            colors: ThemeColors {
122                background: Color::rgb(0xF6, 0xF6, 0xF6),
123                surface: Color::rgb(0xFF, 0xFF, 0xFF),
124                text: Color::rgb(0x1F, 0x1F, 0x1F),
125                text_muted: Color::rgb(0x6B, 0x6B, 0x6B),
126                accent: Color::rgb(0x0B, 0x5C, 0xAB),
127                border: Color::rgb(0xD0, 0xD0, 0xD0),
128                warning: Color::rgb(0xB4, 0x6A, 0x00),
129                error: Color::rgb(0xB0, 0x2A, 0x2A),
130            },
131            spacing: ThemeSpacing::default_scale(),
132            typography: ThemeTypography::default_scale(),
133        }
134    }
135
136    /// Built-in dark theme.
137    pub fn dark() -> Self {
138        Self {
139            mode: ThemeMode::Dark,
140            colors: ThemeColors {
141                background: Color::rgb(0x1E, 0x1E, 0x1E),
142                surface: Color::rgb(0x25, 0x25, 0x25),
143                text: Color::rgb(0xF0, 0xF0, 0xF0),
144                text_muted: Color::rgb(0xA8, 0xA8, 0xA8),
145                accent: Color::rgb(0x4D, 0x9B, 0xE6),
146                border: Color::rgb(0x3A, 0x3A, 0x3A),
147                warning: Color::rgb(0xE0, 0xA0, 0x30),
148                error: Color::rgb(0xE0, 0x6A, 0x6A),
149            },
150            spacing: ThemeSpacing::default_scale(),
151            typography: ThemeTypography::default_scale(),
152        }
153    }
154
155    /// Resolves the built-in theme for a mode.
156    pub fn for_mode(mode: ThemeMode) -> Self {
157        match mode {
158            ThemeMode::Light => Self::light(),
159            ThemeMode::Dark => Self::dark(),
160        }
161    }
162
163    /// Built-in high-contrast theme for a preset.
164    ///
165    /// Every preset keeps `text`, `text_muted`, `accent`, `border`, `warning`,
166    /// and `error` at WCAG 2.1 AAA contrast (>= 7:1) against `background`.
167    pub fn high_contrast(preset: HighContrastPreset) -> Self {
168        let rgb = Color::rgb;
169        let colors = match preset {
170            HighContrastPreset::BlackOnWhite => ThemeColors {
171                background: rgb(0xFF, 0xFF, 0xFF),
172                surface: rgb(0xFF, 0xFF, 0xFF),
173                text: rgb(0x00, 0x00, 0x00),
174                text_muted: rgb(0x00, 0x00, 0x64),
175                accent: rgb(0x00, 0x00, 0x8C),
176                border: rgb(0x00, 0x00, 0x00),
177                warning: rgb(0x6E, 0x30, 0x00),
178                error: rgb(0x90, 0x00, 0x00),
179            },
180            HighContrastPreset::WhiteOnBlack => ThemeColors {
181                background: rgb(0x00, 0x00, 0x00),
182                surface: rgb(0x00, 0x00, 0x00),
183                text: rgb(0xFF, 0xFF, 0xFF),
184                text_muted: rgb(0x00, 0xFF, 0xFF),
185                accent: rgb(0x1A, 0xEB, 0xFF),
186                border: rgb(0xFF, 0xFF, 0xFF),
187                warning: rgb(0xFF, 0xFF, 0x00),
188                error: rgb(0xFF, 0x66, 0x66),
189            },
190            HighContrastPreset::Desert => ThemeColors {
191                background: rgb(0xFF, 0xFA, 0xF0),
192                surface: rgb(0xFF, 0xFA, 0xF0),
193                text: rgb(0x20, 0x12, 0x05),
194                text_muted: rgb(0x4A, 0x1E, 0x00),
195                accent: rgb(0x00, 0x48, 0x55),
196                border: rgb(0x40, 0x20, 0x08),
197                warning: rgb(0x75, 0x33, 0x00),
198                error: rgb(0x8B, 0x00, 0x00),
199            },
200            HighContrastPreset::NightSky => ThemeColors {
201                background: rgb(0x00, 0x00, 0x00),
202                surface: rgb(0x00, 0x00, 0x00),
203                text: rgb(0xFF, 0xFF, 0xFF),
204                text_muted: rgb(0x99, 0xCC, 0xFF),
205                accent: rgb(0x80, 0xDF, 0xFF),
206                border: rgb(0xB0, 0xC4, 0xDE),
207                warning: rgb(0xFF, 0xE0, 0x66),
208                error: rgb(0xFF, 0x6B, 0x6B),
209            },
210        };
211        Self {
212            mode: preset.mode(),
213            colors,
214            spacing: ThemeSpacing::default_scale(),
215            typography: ThemeTypography::default_scale(),
216        }
217    }
218}
219
220/// System high-contrast color schemes, modeled on the Windows
221/// contrast themes and GTK `HighContrast`/`HighContrastInverse`.
222#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
223pub enum HighContrastPreset {
224    /// Black text on white (Windows "High Contrast White", GTK `HighContrast`).
225    BlackOnWhite,
226    /// White text on black (Windows "High Contrast Black", GTK `HighContrastInverse`).
227    WhiteOnBlack,
228    /// Dark umber on warm parchment (Windows 11 "Desert").
229    Desert,
230    /// White and azure on black (Windows 11 "Night Sky").
231    NightSky,
232}
233
234impl HighContrastPreset {
235    /// Every preset, in declaration order.
236    pub const ALL: [Self; 4] = [
237        Self::BlackOnWhite,
238        Self::WhiteOnBlack,
239        Self::Desert,
240        Self::NightSky,
241    ];
242
243    /// Stable lowercase identifier used by tests and diagnostics.
244    pub fn as_str(self) -> &'static str {
245        match self {
246            Self::BlackOnWhite => "black-on-white",
247            Self::WhiteOnBlack => "white-on-black",
248            Self::Desert => "desert",
249            Self::NightSky => "night-sky",
250        }
251    }
252
253    /// Light/dark mode of the preset's background.
254    pub fn mode(self) -> ThemeMode {
255        match self {
256            Self::BlackOnWhite | Self::Desert => ThemeMode::Light,
257            Self::WhiteOnBlack | Self::NightSky => ThemeMode::Dark,
258        }
259    }
260
261    /// Returns the default high-contrast preset for a given light/dark mode.
262    pub fn for_mode(mode: ThemeMode) -> Self {
263        match mode {
264            ThemeMode::Light => Self::BlackOnWhite,
265            ThemeMode::Dark => Self::WhiteOnBlack,
266        }
267    }
268}
269
270impl ThemeSpacing {
271    fn default_scale() -> Self {
272        Self {
273            xs: 2,
274            sm: 4,
275            md: 8,
276            lg: 16,
277            xl: 24,
278        }
279    }
280}
281
282impl ThemeTypography {
283    fn default_scale() -> Self {
284        Self {
285            body_size: 13.0,
286            label_size: 12.0,
287            title_size: 16.0,
288            heading_size: 20.0,
289        }
290    }
291}
292
293/// A per-widget theme override. Only tokens that map to real
294/// native knobs are portable today.
295#[derive(Debug, Clone, Copy, PartialEq)]
296pub enum ThemeOverride {
297    /// Overrides the widget background.
298    Background(Color),
299    /// Overrides the widget foreground/text color.
300    Foreground(Color),
301    /// Overrides the widget padding in logical pixels.
302    Padding(i32),
303    /// Overrides the widget font size in points.
304    FontSize(f32),
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    #[test]
312    fn light_and_dark_resolve_distinct_tokens() {
313        let light = Theme::light();
314        let dark = Theme::dark();
315        assert_eq!(light.mode, ThemeMode::Light);
316        assert_eq!(dark.mode, ThemeMode::Dark);
317        assert_ne!(light.colors.background, dark.colors.background);
318        assert_ne!(light.colors.surface, dark.colors.surface);
319        assert_ne!(light.colors.text, dark.colors.text);
320        // Spacing and typography scales are shared by both modes.
321        assert_eq!(light.spacing, dark.spacing);
322        assert_eq!(light.typography, dark.typography);
323    }
324
325    #[test]
326    fn for_mode_matches_the_builtins() {
327        assert_eq!(Theme::for_mode(ThemeMode::Light), Theme::light());
328        assert_eq!(Theme::for_mode(ThemeMode::Dark), Theme::dark());
329        assert_eq!(ThemeMode::Light.as_str(), "light");
330        assert_eq!(ThemeMode::Dark.as_str(), "dark");
331    }
332
333    #[test]
334    fn high_contrast_presets_meet_wcag_aaa() {
335        use crate::focus::FocusRingMetrics;
336        for preset in HighContrastPreset::ALL {
337            let theme = Theme::high_contrast(preset);
338            assert_eq!(theme.mode, preset.mode(), "{}", preset.as_str());
339            let c = theme.colors;
340            for (name, fg) in [
341                ("text", c.text),
342                ("text_muted", c.text_muted),
343                ("accent", c.accent),
344                ("border", c.border),
345                ("warning", c.warning),
346                ("error", c.error),
347            ] {
348                for bg in [c.background, c.surface] {
349                    let ratio = FocusRingMetrics::contrast_ratio(fg, bg);
350                    assert!(
351                        ratio >= 7.0,
352                        "{} {name} contrast {ratio:.2} < 7.0",
353                        preset.as_str()
354                    );
355                }
356            }
357        }
358    }
359
360    #[test]
361    fn high_contrast_presets_are_distinct() {
362        let all = HighContrastPreset::ALL.map(Theme::high_contrast);
363        for (i, a) in all.iter().enumerate() {
364            for b in &all[i + 1..] {
365                assert_ne!(a.colors, b.colors);
366            }
367        }
368    }
369
370    #[test]
371    fn scales_are_monotonic() {
372        let theme = Theme::light();
373        let spacing = theme.spacing;
374        assert!(spacing.xs < spacing.sm);
375        assert!(spacing.sm < spacing.md);
376        assert!(spacing.md < spacing.lg);
377        assert!(spacing.lg < spacing.xl);
378
379        let typography = theme.typography;
380        assert!(typography.label_size <= typography.body_size);
381        assert!(typography.body_size < typography.title_size);
382        assert!(typography.title_size < typography.heading_size);
383    }
384}