Skip to main content

gpui_material_theme/
color.rs

1use crate::{ColorRole, generated::*};
2
3/// A packed 8-bit sRGB color in alpha, red, green, blue order.
4#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
6#[cfg_attr(feature = "serde", serde(transparent))]
7pub struct Argb(u32);
8
9impl Argb {
10    pub const fn from_u32(argb: u32) -> Self {
11        Self(argb)
12    }
13
14    pub const fn from_rgb(red: u8, green: u8, blue: u8) -> Self {
15        Self(u32::from_be_bytes([255, red, green, blue]))
16    }
17
18    pub const fn to_u32(self) -> u32 {
19        self.0
20    }
21
22    pub const fn channels(self) -> [u8; 4] {
23        self.0.to_be_bytes()
24    }
25}
26
27/// The selected appearance. The host resolves any system preference.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30pub enum Appearance {
31    #[default]
32    Light,
33    Dark,
34}
35
36/// Resolved foreground and background colors for a Material pairing.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct ColorPair {
39    pub foreground: Argb,
40    pub background: Argb,
41}
42
43/// All semantic color roles for one appearance, with per-role overrides.
44#[derive(Clone, Debug, PartialEq, Eq)]
45#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
46pub struct ColorScheme {
47    appearance: Appearance,
48    // Keep the serialized form keyed by role so additions can use baseline defaults.
49    #[cfg_attr(feature = "serde", serde(default))]
50    overrides: std::collections::BTreeMap<ColorRole, Argb>,
51}
52
53impl Default for ColorScheme {
54    fn default() -> Self {
55        Self::baseline(Appearance::Light)
56    }
57}
58
59impl ColorScheme {
60    pub fn baseline(appearance: Appearance) -> Self {
61        Self {
62            appearance,
63            overrides: Default::default(),
64        }
65    }
66
67    pub fn appearance(&self) -> Appearance {
68        self.appearance
69    }
70
71    pub fn color(&self, role: ColorRole) -> Argb {
72        self.overrides
73            .get(&role)
74            .copied()
75            .unwrap_or_else(|| self.baseline_color(role))
76    }
77
78    /// Overrides one role. Callers overriding a background should also check its foreground.
79    pub fn set_color(&mut self, role: ColorRole, color: Argb) {
80        if color == self.baseline_color(role) {
81            self.overrides.remove(&role);
82        } else {
83            self.overrides.insert(role, color);
84        }
85    }
86
87    fn baseline_color(&self, role: ColorRole) -> Argb {
88        match self.appearance {
89            Appearance::Light => LIGHT[role as usize],
90            Appearance::Dark => DARK[role as usize],
91        }
92    }
93
94    /// Resolves the standard foreground for a semantic background.
95    pub fn pair(&self, background: ColorRole) -> Option<ColorPair> {
96        use ColorRole::*;
97
98        let foreground = match background {
99            Background => OnBackground,
100            Error => OnError,
101            ErrorContainer => OnErrorContainer,
102            InverseSurface => InverseOnSurface,
103            Primary => OnPrimary,
104            PrimaryContainer => OnPrimaryContainer,
105            PrimaryFixed | PrimaryFixedDim => OnPrimaryFixed,
106            Secondary => OnSecondary,
107            SecondaryContainer => OnSecondaryContainer,
108            SecondaryFixed | SecondaryFixedDim => OnSecondaryFixed,
109            Surface
110            | SurfaceBright
111            | SurfaceDim
112            | SurfaceContainerLowest
113            | SurfaceContainerLow
114            | SurfaceContainer
115            | SurfaceContainerHigh
116            | SurfaceContainerHighest => OnSurface,
117            SurfaceVariant => OnSurfaceVariant,
118            Tertiary => OnTertiary,
119            TertiaryContainer => OnTertiaryContainer,
120            TertiaryFixed | TertiaryFixedDim => OnTertiaryFixed,
121            _ => return None,
122        };
123        Some(ColorPair {
124            foreground: self.color(foreground),
125            background: self.color(background),
126        })
127    }
128
129    /// Applies the Compose tonal-elevation tint to the surface role.
130    pub fn surface_at_elevation(&self, elevation: Elevation) -> Argb {
131        let surface = self.color(ColorRole::Surface);
132        let dp = elevation.dp();
133        if dp == 0.0 {
134            return surface;
135        }
136
137        let overlay_alpha = (4.5 * dp.ln_1p() + 2.0) / 100.0;
138        let [alpha, r, g, b] = surface.channels();
139        let [_, tint_r, tint_g, tint_b] = self.color(ColorRole::SurfaceTint).channels();
140        let under_alpha = f32::from(alpha) / 255.0 * (1.0 - overlay_alpha);
141        let alpha = overlay_alpha + under_alpha;
142        let composite = |under, over| {
143            ((f32::from(over) * overlay_alpha + f32::from(under) * under_alpha) / alpha).round()
144                as u8
145        };
146        Argb::from_u32(u32::from_be_bytes([
147            (alpha * 255.0).round() as u8,
148            composite(r, tint_r),
149            composite(g, tint_g),
150            composite(b, tint_b),
151        ]))
152    }
153
154    /// Generates Tonal Spot roles using MCU Spec2021. Contrast is clamped to
155    /// -1 through 1. NaN selects the default contrast (0).
156    #[cfg(feature = "dynamic-color")]
157    pub fn from_seed(seed: Argb, appearance: Appearance, contrast: f64) -> Self {
158        use material_color_utils::{
159            dynamic::color_spec::SpecVersion, scheme::SchemeTonalSpot, utils::color_utils,
160        };
161
162        let seed = color_utils::Argb(seed.to_u32() | 0xff00_0000);
163        let contrast = if contrast.is_nan() {
164            0.0
165        } else {
166            contrast.clamp(-1.0, 1.0)
167        };
168        let scheme = SchemeTonalSpot::builder(seed, appearance == Appearance::Dark, contrast)
169            .spec_version(SpecVersion::Spec2021)
170            .build();
171        let mut colors = Self::baseline(appearance);
172        for (role, color) in ColorRole::ALL.into_iter().zip(dynamic_colors(&scheme)) {
173            colors.set_color(role, color);
174        }
175        colors
176    }
177}
178
179/// The six Material elevation levels. The renderer supplies the shadow.
180#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
181pub enum Elevation {
182    #[default]
183    Level0,
184    Level1,
185    Level2,
186    Level3,
187    Level4,
188    Level5,
189}
190
191impl Elevation {
192    pub const fn dp(self) -> f32 {
193        match self {
194            Self::Level0 => MD_SYS_ELEVATION_LEVEL_0,
195            Self::Level1 => MD_SYS_ELEVATION_LEVEL_1,
196            Self::Level2 => MD_SYS_ELEVATION_LEVEL_2,
197            Self::Level3 => MD_SYS_ELEVATION_LEVEL_3,
198            Self::Level4 => MD_SYS_ELEVATION_LEVEL_4,
199            Self::Level5 => MD_SYS_ELEVATION_LEVEL_5,
200        }
201    }
202}
203
204/// Material state layer opacities.
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub enum StateLayer {
207    Hover,
208    Focus,
209    Pressed,
210    Dragged,
211}
212
213impl StateLayer {
214    pub const fn opacity(self) -> f32 {
215        match self {
216            Self::Hover => MD_SYS_STATE_HOVER_STATE_LAYER_OPACITY,
217            Self::Focus => MD_SYS_STATE_FOCUS_STATE_LAYER_OPACITY,
218            Self::Pressed => MD_SYS_STATE_PRESSED_STATE_LAYER_OPACITY,
219            Self::Dragged => MD_SYS_STATE_DRAGGED_STATE_LAYER_OPACITY,
220        }
221    }
222}
223/// Returns the contrast ratio for two CIE L* tones, clamped to 0 through 100.
224/// Returns `None` if either tone is NaN.
225#[cfg(feature = "dynamic-color")]
226pub fn contrast_ratio_of_tones(first: f64, second: f64) -> Option<f64> {
227    use material_color_utils::contrast::contrast_utils::Contrast;
228
229    if first.is_nan() || second.is_nan() {
230        return None;
231    }
232    Some(Contrast::ratio_of_tones(
233        first.clamp(0.0, 100.0),
234        second.clamp(0.0, 100.0),
235    ))
236}