native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
//! Theme tokens and light/dark modes.
//!
//! A resolved, backend-agnostic token set (colors, spacing, typography) plus
//! the per-widget override vocabulary. Native application lands
//! (GTK CSS, Win32 brushes/colors, Cocoa appearance); the `Backend` defaults
//! return the typed capability error until then, so a request is never
//! silently ignored. See `docs/widget-expansion-roadmap.md` ("Theming and art
//! provider") for the design and evidence rules.

use crate::widgets::Color;

/// Light/dark mode selector.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ThemeMode {
    Light,
    Dark,
}

impl ThemeMode {
    /// Stable lowercase identifier used by tests and diagnostics.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Light => "light",
            Self::Dark => "dark",
        }
    }
}

/// Backend capability flags for system light/dark detection.
///
/// A backend that cannot observe the OS preference reports
/// [`ThemeCapabilities::none`] and returns `None` from
/// `Backend::system_theme_mode`, so apps can gate their follow-the-system
/// logic on real support instead of guessing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ThemeCapabilities {
    /// The backend can report the OS light/dark preference through
    /// `Backend::system_theme_mode`.
    pub system_detection: bool,
    /// The backend reports light/dark transitions through
    /// [`crate::UiEvent::ThemeChanged`] as the OS preference changes.
    pub change_events: bool,
    /// The backend can detect the OS high-contrast accessibility mode.
    pub high_contrast_detection: bool,
}

impl ThemeCapabilities {
    /// No detection and no change events.
    pub const fn none() -> Self {
        Self {
            system_detection: false,
            change_events: false,
            high_contrast_detection: false,
        }
    }

    /// Full detection with change events (native backends, injectable Mock).
    pub const fn all() -> Self {
        Self {
            system_detection: true,
            change_events: true,
            high_contrast_detection: true,
        }
    }
}

/// Named colors resolved by a theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ThemeColors {
    /// Window/workspace background.
    pub background: Color,
    /// Card/panel surface.
    pub surface: Color,
    /// Primary text color.
    pub text: Color,
    /// Secondary/label text color.
    pub text_muted: Color,
    /// Accent color (selection, links, focused outlines).
    pub accent: Color,
    /// Separator/border color.
    pub border: Color,
    /// Warning severity color.
    pub warning: Color,
    /// Error severity color.
    pub error: Color,
}

/// Spacing scale in logical pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ThemeSpacing {
    pub xs: i32,
    pub sm: i32,
    pub md: i32,
    pub lg: i32,
    pub xl: i32,
}

/// Typography scale in points.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ThemeTypography {
    pub body_size: f32,
    pub label_size: f32,
    pub title_size: f32,
    pub heading_size: f32,
}

/// A fully resolved theme.
#[derive(Debug, Clone, PartialEq)]
pub struct Theme {
    pub mode: ThemeMode,
    pub colors: ThemeColors,
    pub spacing: ThemeSpacing,
    pub typography: ThemeTypography,
}

impl Theme {
    /// Built-in light theme.
    pub fn light() -> Self {
        Self {
            mode: ThemeMode::Light,
            colors: ThemeColors {
                background: Color::rgb(0xF6, 0xF6, 0xF6),
                surface: Color::rgb(0xFF, 0xFF, 0xFF),
                text: Color::rgb(0x1F, 0x1F, 0x1F),
                text_muted: Color::rgb(0x6B, 0x6B, 0x6B),
                accent: Color::rgb(0x0B, 0x5C, 0xAB),
                border: Color::rgb(0xD0, 0xD0, 0xD0),
                warning: Color::rgb(0xB4, 0x6A, 0x00),
                error: Color::rgb(0xB0, 0x2A, 0x2A),
            },
            spacing: ThemeSpacing::default_scale(),
            typography: ThemeTypography::default_scale(),
        }
    }

    /// Built-in dark theme.
    pub fn dark() -> Self {
        Self {
            mode: ThemeMode::Dark,
            colors: ThemeColors {
                background: Color::rgb(0x1E, 0x1E, 0x1E),
                surface: Color::rgb(0x25, 0x25, 0x25),
                text: Color::rgb(0xF0, 0xF0, 0xF0),
                text_muted: Color::rgb(0xA8, 0xA8, 0xA8),
                accent: Color::rgb(0x4D, 0x9B, 0xE6),
                border: Color::rgb(0x3A, 0x3A, 0x3A),
                warning: Color::rgb(0xE0, 0xA0, 0x30),
                error: Color::rgb(0xE0, 0x6A, 0x6A),
            },
            spacing: ThemeSpacing::default_scale(),
            typography: ThemeTypography::default_scale(),
        }
    }

    /// Resolves the built-in theme for a mode.
    pub fn for_mode(mode: ThemeMode) -> Self {
        match mode {
            ThemeMode::Light => Self::light(),
            ThemeMode::Dark => Self::dark(),
        }
    }

    /// Built-in high-contrast theme for a preset.
    ///
    /// Every preset keeps `text`, `text_muted`, `accent`, `border`, `warning`,
    /// and `error` at WCAG 2.1 AAA contrast (>= 7:1) against `background`.
    pub fn high_contrast(preset: HighContrastPreset) -> Self {
        let rgb = Color::rgb;
        let colors = match preset {
            HighContrastPreset::BlackOnWhite => ThemeColors {
                background: rgb(0xFF, 0xFF, 0xFF),
                surface: rgb(0xFF, 0xFF, 0xFF),
                text: rgb(0x00, 0x00, 0x00),
                text_muted: rgb(0x00, 0x00, 0x64),
                accent: rgb(0x00, 0x00, 0x8C),
                border: rgb(0x00, 0x00, 0x00),
                warning: rgb(0x6E, 0x30, 0x00),
                error: rgb(0x90, 0x00, 0x00),
            },
            HighContrastPreset::WhiteOnBlack => ThemeColors {
                background: rgb(0x00, 0x00, 0x00),
                surface: rgb(0x00, 0x00, 0x00),
                text: rgb(0xFF, 0xFF, 0xFF),
                text_muted: rgb(0x00, 0xFF, 0xFF),
                accent: rgb(0x1A, 0xEB, 0xFF),
                border: rgb(0xFF, 0xFF, 0xFF),
                warning: rgb(0xFF, 0xFF, 0x00),
                error: rgb(0xFF, 0x66, 0x66),
            },
            HighContrastPreset::Desert => ThemeColors {
                background: rgb(0xFF, 0xFA, 0xF0),
                surface: rgb(0xFF, 0xFA, 0xF0),
                text: rgb(0x20, 0x12, 0x05),
                text_muted: rgb(0x4A, 0x1E, 0x00),
                accent: rgb(0x00, 0x48, 0x55),
                border: rgb(0x40, 0x20, 0x08),
                warning: rgb(0x75, 0x33, 0x00),
                error: rgb(0x8B, 0x00, 0x00),
            },
            HighContrastPreset::NightSky => ThemeColors {
                background: rgb(0x00, 0x00, 0x00),
                surface: rgb(0x00, 0x00, 0x00),
                text: rgb(0xFF, 0xFF, 0xFF),
                text_muted: rgb(0x99, 0xCC, 0xFF),
                accent: rgb(0x80, 0xDF, 0xFF),
                border: rgb(0xB0, 0xC4, 0xDE),
                warning: rgb(0xFF, 0xE0, 0x66),
                error: rgb(0xFF, 0x6B, 0x6B),
            },
        };
        Self {
            mode: preset.mode(),
            colors,
            spacing: ThemeSpacing::default_scale(),
            typography: ThemeTypography::default_scale(),
        }
    }
}

/// System high-contrast color schemes, modeled on the Windows
/// contrast themes and GTK `HighContrast`/`HighContrastInverse`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HighContrastPreset {
    /// Black text on white (Windows "High Contrast White", GTK `HighContrast`).
    BlackOnWhite,
    /// White text on black (Windows "High Contrast Black", GTK `HighContrastInverse`).
    WhiteOnBlack,
    /// Dark umber on warm parchment (Windows 11 "Desert").
    Desert,
    /// White and azure on black (Windows 11 "Night Sky").
    NightSky,
}

impl HighContrastPreset {
    /// Every preset, in declaration order.
    pub const ALL: [Self; 4] = [
        Self::BlackOnWhite,
        Self::WhiteOnBlack,
        Self::Desert,
        Self::NightSky,
    ];

    /// Stable lowercase identifier used by tests and diagnostics.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::BlackOnWhite => "black-on-white",
            Self::WhiteOnBlack => "white-on-black",
            Self::Desert => "desert",
            Self::NightSky => "night-sky",
        }
    }

    /// Light/dark mode of the preset's background.
    pub fn mode(self) -> ThemeMode {
        match self {
            Self::BlackOnWhite | Self::Desert => ThemeMode::Light,
            Self::WhiteOnBlack | Self::NightSky => ThemeMode::Dark,
        }
    }

    /// Returns the default high-contrast preset for a given light/dark mode.
    pub fn for_mode(mode: ThemeMode) -> Self {
        match mode {
            ThemeMode::Light => Self::BlackOnWhite,
            ThemeMode::Dark => Self::WhiteOnBlack,
        }
    }
}

impl ThemeSpacing {
    fn default_scale() -> Self {
        Self {
            xs: 2,
            sm: 4,
            md: 8,
            lg: 16,
            xl: 24,
        }
    }
}

impl ThemeTypography {
    fn default_scale() -> Self {
        Self {
            body_size: 13.0,
            label_size: 12.0,
            title_size: 16.0,
            heading_size: 20.0,
        }
    }
}

/// A per-widget theme override. Only tokens that map to real
/// native knobs are portable today.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ThemeOverride {
    /// Overrides the widget background.
    Background(Color),
    /// Overrides the widget foreground/text color.
    Foreground(Color),
    /// Overrides the widget padding in logical pixels.
    Padding(i32),
    /// Overrides the widget font size in points.
    FontSize(f32),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn light_and_dark_resolve_distinct_tokens() {
        let light = Theme::light();
        let dark = Theme::dark();
        assert_eq!(light.mode, ThemeMode::Light);
        assert_eq!(dark.mode, ThemeMode::Dark);
        assert_ne!(light.colors.background, dark.colors.background);
        assert_ne!(light.colors.surface, dark.colors.surface);
        assert_ne!(light.colors.text, dark.colors.text);
        // Spacing and typography scales are shared by both modes.
        assert_eq!(light.spacing, dark.spacing);
        assert_eq!(light.typography, dark.typography);
    }

    #[test]
    fn for_mode_matches_the_builtins() {
        assert_eq!(Theme::for_mode(ThemeMode::Light), Theme::light());
        assert_eq!(Theme::for_mode(ThemeMode::Dark), Theme::dark());
        assert_eq!(ThemeMode::Light.as_str(), "light");
        assert_eq!(ThemeMode::Dark.as_str(), "dark");
    }

    #[test]
    fn high_contrast_presets_meet_wcag_aaa() {
        use crate::focus::FocusRingMetrics;
        for preset in HighContrastPreset::ALL {
            let theme = Theme::high_contrast(preset);
            assert_eq!(theme.mode, preset.mode(), "{}", preset.as_str());
            let c = theme.colors;
            for (name, fg) in [
                ("text", c.text),
                ("text_muted", c.text_muted),
                ("accent", c.accent),
                ("border", c.border),
                ("warning", c.warning),
                ("error", c.error),
            ] {
                for bg in [c.background, c.surface] {
                    let ratio = FocusRingMetrics::contrast_ratio(fg, bg);
                    assert!(
                        ratio >= 7.0,
                        "{} {name} contrast {ratio:.2} < 7.0",
                        preset.as_str()
                    );
                }
            }
        }
    }

    #[test]
    fn high_contrast_presets_are_distinct() {
        let all = HighContrastPreset::ALL.map(Theme::high_contrast);
        for (i, a) in all.iter().enumerate() {
            for b in &all[i + 1..] {
                assert_ne!(a.colors, b.colors);
            }
        }
    }

    #[test]
    fn scales_are_monotonic() {
        let theme = Theme::light();
        let spacing = theme.spacing;
        assert!(spacing.xs < spacing.sm);
        assert!(spacing.sm < spacing.md);
        assert!(spacing.md < spacing.lg);
        assert!(spacing.lg < spacing.xl);

        let typography = theme.typography;
        assert!(typography.label_size <= typography.body_size);
        assert!(typography.body_size < typography.title_size);
        assert!(typography.title_size < typography.heading_size);
    }
}