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    /// Creates an [`Argb`] from a packed `0xAARRGGBB` integer.
11    pub const fn from_u32(argb: u32) -> Self {
12        Self(argb)
13    }
14
15    /// Creates an opaque (`alpha = 255`) sRGB color.
16    pub const fn from_rgb(red: u8, green: u8, blue: u8) -> Self {
17        Self(u32::from_be_bytes([255, red, green, blue]))
18    }
19
20    /// Creates an sRGB color from explicit red, green, blue, and alpha channels.
21    pub const fn from_rgba(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
22        Self(u32::from_be_bytes([alpha, red, green, blue]))
23    }
24
25    /// Returns a copy of this color with its alpha channel replaced.
26    pub const fn with_alpha(self, alpha: u8) -> Self {
27        let [_, red, green, blue] = self.channels();
28        Self::from_rgba(red, green, blue, alpha)
29    }
30
31    /// Returns the packed `0xAARRGGBB` representation.
32    pub const fn to_u32(self) -> u32 {
33        self.0
34    }
35
36    /// Returns the color channels in `[alpha, red, green, blue]` order.
37    pub const fn channels(self) -> [u8; 4] {
38        self.0.to_be_bytes()
39    }
40
41    /// Returns the 8-bit alpha channel.
42    pub const fn alpha(self) -> u8 {
43        self.channels()[0]
44    }
45
46    /// Returns the 8-bit red channel.
47    pub const fn red(self) -> u8 {
48        self.channels()[1]
49    }
50
51    /// Returns the 8-bit green channel.
52    pub const fn green(self) -> u8 {
53        self.channels()[2]
54    }
55
56    /// Returns the 8-bit blue channel.
57    pub const fn blue(self) -> u8 {
58        self.channels()[3]
59    }
60}
61
62impl ColorRole {
63    /// Returns the standard Material foreground role paired with this semantic
64    /// background role, or `None` when this role is not a paired background.
65    pub const fn on_role(self) -> Option<Self> {
66        use ColorRole::*;
67
68        Some(match self {
69            Background => OnBackground,
70            Error => OnError,
71            ErrorContainer => OnErrorContainer,
72            Info => OnInfo,
73            InfoContainer => OnInfoContainer,
74            InverseSurface => InverseOnSurface,
75            Primary => OnPrimary,
76            PrimaryContainer => OnPrimaryContainer,
77            PrimaryFixed | PrimaryFixedDim => OnPrimaryFixed,
78            Secondary => OnSecondary,
79            SecondaryContainer => OnSecondaryContainer,
80            SecondaryFixed | SecondaryFixedDim => OnSecondaryFixed,
81            Success => OnSuccess,
82            SuccessContainer => OnSuccessContainer,
83            Surface
84            | SurfaceBright
85            | SurfaceDim
86            | SurfaceContainerLowest
87            | SurfaceContainerLow
88            | SurfaceContainer
89            | SurfaceContainerHigh
90            | SurfaceContainerHighest => OnSurface,
91            SurfaceVariant => OnSurfaceVariant,
92            Tertiary => OnTertiary,
93            TertiaryContainer => OnTertiaryContainer,
94            TertiaryFixed | TertiaryFixedDim => OnTertiaryFixed,
95            Warning => OnWarning,
96            WarningContainer => OnWarningContainer,
97            _ => return None,
98        })
99    }
100}
101
102/// The selected appearance. The host resolves any system preference.
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
105pub enum Appearance {
106    /// Light mode (default).
107    #[default]
108    Light,
109    /// Dark mode.
110    Dark,
111}
112
113/// Resolved foreground and background colors for a Material pairing.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct ColorPair {
116    /// Foreground content color (text, icons, indicators).
117    pub foreground: Argb,
118    /// Background container or surface color.
119    pub background: Argb,
120}
121
122/// All semantic color roles for one appearance, with per-role overrides.
123#[derive(Clone, Debug, PartialEq, Eq)]
124pub struct ColorScheme {
125    appearance: Appearance,
126    colors: [Argb; ColorRole::ALL.len()],
127}
128
129#[cfg(feature = "serde")]
130impl serde::Serialize for ColorScheme {
131    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
132        #[derive(serde::Serialize)]
133        #[serde(rename = "ColorScheme")]
134        struct SerializedColorScheme {
135            appearance: Appearance,
136            overrides: std::collections::BTreeMap<ColorRole, Argb>,
137        }
138
139        let mut overrides = std::collections::BTreeMap::new();
140        for role in ColorRole::ALL {
141            let color = self.colors[role as usize];
142            if color != self.baseline_color(role) {
143                overrides.insert(role, color);
144            }
145        }
146        SerializedColorScheme {
147            appearance: self.appearance,
148            overrides,
149        }
150        .serialize(serializer)
151    }
152}
153
154#[cfg(feature = "serde")]
155impl<'de> serde::Deserialize<'de> for ColorScheme {
156    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
157        #[derive(serde::Deserialize)]
158        #[serde(rename = "ColorScheme")]
159        struct SerializedColorScheme {
160            appearance: Appearance,
161            // Keep the serialized form keyed by role so additions can use baseline defaults.
162            #[serde(default)]
163            overrides: std::collections::BTreeMap<ColorRole, Argb>,
164        }
165
166        let raw = SerializedColorScheme::deserialize(deserializer)?;
167        let mut scheme = Self::baseline(raw.appearance);
168        for (role, color) in raw.overrides {
169            scheme.set_color(role, color);
170        }
171        Ok(scheme)
172    }
173}
174
175impl Default for ColorScheme {
176    fn default() -> Self {
177        Self::baseline(Appearance::Light)
178    }
179}
180
181impl ColorScheme {
182    /// Returns the baseline Material 3 color scheme for the given [`Appearance`].
183    pub const fn baseline(appearance: Appearance) -> Self {
184        Self {
185            appearance,
186            colors: match appearance {
187                Appearance::Light => LIGHT,
188                Appearance::Dark => DARK,
189            },
190        }
191    }
192
193    /// Returns the [`Appearance`] (light or dark) associated with this scheme.
194    pub const fn appearance(&self) -> Appearance {
195        self.appearance
196    }
197
198    /// Resolves a semantic [`ColorRole`] to its packed [`Argb`] value.
199    pub const fn color(&self, role: ColorRole) -> Argb {
200        self.colors[role as usize]
201    }
202
203    /// Overrides one role. Callers overriding a background should also check its foreground.
204    pub fn set_color(&mut self, role: ColorRole, color: Argb) {
205        self.colors[role as usize] = color;
206    }
207
208    /// Fluent counterpart to [`Self::set_color`].
209    pub fn with_color(mut self, role: ColorRole, color: Argb) -> Self {
210        self.set_color(role, color);
211        self
212    }
213
214    #[cfg(feature = "serde")]
215    const fn baseline_color(&self, role: ColorRole) -> Argb {
216        match self.appearance {
217            Appearance::Light => LIGHT[role as usize],
218            Appearance::Dark => DARK[role as usize],
219        }
220    }
221
222    /// Resolves the standard foreground for a semantic background.
223    pub fn pair(&self, background: ColorRole) -> Option<ColorPair> {
224        let foreground = background.on_role()?;
225        Some(ColorPair {
226            foreground: self.color(foreground),
227            background: self.color(background),
228        })
229    }
230
231    /// Interpolates all resolved sRGB and alpha channels. The target appearance
232    /// takes effect at the midpoint. Values outside 0–1 clamp, and NaN uses 0.
233    pub fn blend(&self, target: &Self, t: f32) -> Self {
234        if t.is_nan() || t <= 0.0 || self == target {
235            return self.clone();
236        }
237        if t >= 1.0 {
238            return target.clone();
239        }
240        let appearance = if t < 0.5 {
241            self.appearance
242        } else {
243            target.appearance
244        };
245        let colors = std::array::from_fn(|index| {
246            let from = self.colors[index].channels();
247            let to = target.colors[index].channels();
248            let channels = std::array::from_fn(|i| {
249                let start = f32::from(from[i]);
250                (start + (f32::from(to[i]) - start) * t).round() as u8
251            });
252            Argb::from_u32(u32::from_be_bytes(channels))
253        });
254        Self { appearance, colors }
255    }
256
257    /// Applies the Compose tonal-elevation tint to the surface role.
258    pub fn surface_at_elevation(&self, elevation: Elevation) -> Argb {
259        let surface = self.color(ColorRole::Surface);
260        let dp = elevation.dp();
261        if dp == 0.0 {
262            return surface;
263        }
264
265        let overlay_alpha = (4.5 * dp.ln_1p() + 2.0) / 100.0;
266        let [alpha, r, g, b] = surface.channels();
267        let [_, tint_r, tint_g, tint_b] = self.color(ColorRole::SurfaceTint).channels();
268        let under_alpha = f32::from(alpha) / 255.0 * (1.0 - overlay_alpha);
269        let alpha = overlay_alpha + under_alpha;
270        let composite = |under, over| {
271            ((f32::from(over) * overlay_alpha + f32::from(under) * under_alpha) / alpha).round()
272                as u8
273        };
274        Argb::from_u32(u32::from_be_bytes([
275            (alpha * 255.0).round() as u8,
276            composite(r, tint_r),
277            composite(g, tint_g),
278            composite(b, tint_b),
279        ]))
280    }
281
282    /// Generates Tonal Spot roles using MCU Spec2021. Contrast is clamped to
283    /// -1 through 1. NaN selects the default contrast (0).
284    #[cfg(feature = "dynamic-color")]
285    pub fn from_seed(seed: Argb, appearance: Appearance, contrast: f64) -> Self {
286        Self::from_seed_with(
287            seed,
288            appearance,
289            contrast,
290            crate::DynamicVariant::TonalSpot,
291            crate::SpecVersion::Spec2021,
292        )
293    }
294}
295
296/// The six Material elevation levels. The renderer supplies the shadow.
297#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
298pub enum Elevation {
299    /// Resting elevation (`0 dp`, default).
300    #[default]
301    Level0,
302    /// Low elevation (`1 dp`).
303    Level1,
304    /// Medium-low elevation (`3 dp`).
305    Level2,
306    /// Medium elevation (`6 dp`).
307    Level3,
308    /// Medium-high elevation (`8 dp`).
309    Level4,
310    /// Highest elevation (`12 dp`).
311    Level5,
312}
313
314impl Elevation {
315    /// Returns the Material elevation height in density-independent pixels (`dp`).
316    pub const fn dp(self) -> f32 {
317        match self {
318            Self::Level0 => MD_SYS_ELEVATION_LEVEL_0,
319            Self::Level1 => MD_SYS_ELEVATION_LEVEL_1,
320            Self::Level2 => MD_SYS_ELEVATION_LEVEL_2,
321            Self::Level3 => MD_SYS_ELEVATION_LEVEL_3,
322            Self::Level4 => MD_SYS_ELEVATION_LEVEL_4,
323            Self::Level5 => MD_SYS_ELEVATION_LEVEL_5,
324        }
325    }
326}
327
328/// Material state layer opacities.
329#[derive(Clone, Copy, Debug, PartialEq, Eq)]
330pub enum StateLayer {
331    /// Pointer hover state layer.
332    Hover,
333    /// Keyboard or programmatic focus state layer.
334    Focus,
335    /// Active press state layer.
336    Pressed,
337    /// Active drag state layer.
338    Dragged,
339}
340
341impl StateLayer {
342    /// Returns the normalized Material state-layer opacity (`0.0..=1.0`).
343    pub const fn opacity(self) -> f32 {
344        match self {
345            Self::Hover => MD_SYS_STATE_HOVER_STATE_LAYER_OPACITY,
346            Self::Focus => MD_SYS_STATE_FOCUS_STATE_LAYER_OPACITY,
347            Self::Pressed => MD_SYS_STATE_PRESSED_STATE_LAYER_OPACITY,
348            Self::Dragged => MD_SYS_STATE_DRAGGED_STATE_LAYER_OPACITY,
349        }
350    }
351}
352/// Returns the contrast ratio for two CIE L* tones, clamped to 0 through 100.
353/// Returns `None` if either tone is NaN.
354#[cfg(feature = "dynamic-color")]
355pub fn contrast_ratio_of_tones(first: f64, second: f64) -> Option<f64> {
356    use material_color_utils::contrast::contrast_utils::Contrast;
357
358    if first.is_nan() || second.is_nan() {
359        return None;
360    }
361    Some(Contrast::ratio_of_tones(
362        first.clamp(0.0, 100.0),
363        second.clamp(0.0, 100.0),
364    ))
365}