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, Hash)]
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/// How an application selects between light, dark, and OS-provided appearance.
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
115#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
116pub enum AppearanceMode {
117    /// Always use light appearance.
118    Light,
119    /// Always use dark appearance.
120    Dark,
121    /// Follow the operating system or host window appearance (default).
122    #[default]
123    System,
124}
125
126impl AppearanceMode {
127    /// Resolves this mode into a concrete [`Appearance`], falling back to `system`
128    /// when `self` is [`Self::System`].
129    pub const fn resolve(self, system: Appearance) -> Appearance {
130        match self {
131            Self::Light => Appearance::Light,
132            Self::Dark => Appearance::Dark,
133            Self::System => system,
134        }
135    }
136}
137
138impl From<Appearance> for AppearanceMode {
139    fn from(appearance: Appearance) -> Self {
140        match appearance {
141            Appearance::Light => Self::Light,
142            Appearance::Dark => Self::Dark,
143        }
144    }
145}
146
147/// A semantic Material [`ColorRole`] or an explicit literal [`Argb`] color.
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
149#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
150pub enum ColorSpec {
151    /// Resolve dynamically against the active [`ColorScheme`].
152    Role(ColorRole),
153    /// Use an explicit packed sRGB color.
154    Custom(Argb),
155}
156
157impl ColorSpec {
158    /// Resolves this color specification against `scheme`.
159    pub const fn resolve(self, scheme: &ColorScheme) -> Argb {
160        match self {
161            Self::Role(role) => scheme.color(role),
162            Self::Custom(argb) => argb,
163        }
164    }
165}
166
167impl From<ColorRole> for ColorSpec {
168    fn from(role: ColorRole) -> Self {
169        Self::Role(role)
170    }
171}
172
173impl From<Argb> for ColorSpec {
174    fn from(argb: Argb) -> Self {
175        Self::Custom(argb)
176    }
177}
178
179/// Resolved foreground and background colors for a Material pairing.
180#[derive(Clone, Copy, Debug, PartialEq, Eq)]
181pub struct ColorPair {
182    /// Foreground content color (text, icons, indicators).
183    pub foreground: Argb,
184    /// Background container or surface color.
185    pub background: Argb,
186}
187
188/// All semantic color roles for one appearance, with per-role overrides.
189#[derive(Clone, Debug, PartialEq, Eq)]
190pub struct ColorScheme {
191    appearance: Appearance,
192    colors: [Argb; ColorRole::ALL.len()],
193}
194
195#[cfg(feature = "serde")]
196impl serde::Serialize for ColorScheme {
197    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
198        #[derive(serde::Serialize)]
199        #[serde(rename = "ColorScheme")]
200        struct SerializedColorScheme {
201            appearance: Appearance,
202            overrides: std::collections::BTreeMap<ColorRole, Argb>,
203        }
204
205        let mut overrides = std::collections::BTreeMap::new();
206        for role in ColorRole::ALL {
207            let color = self.colors[role as usize];
208            if color != self.baseline_color(role) {
209                overrides.insert(role, color);
210            }
211        }
212        SerializedColorScheme {
213            appearance: self.appearance,
214            overrides,
215        }
216        .serialize(serializer)
217    }
218}
219
220#[cfg(feature = "serde")]
221impl<'de> serde::Deserialize<'de> for ColorScheme {
222    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
223        #[derive(serde::Deserialize)]
224        #[serde(rename = "ColorScheme")]
225        struct SerializedColorScheme {
226            appearance: Appearance,
227            // Keep the serialized form keyed by role so additions can use baseline defaults.
228            #[serde(default)]
229            overrides: std::collections::BTreeMap<ColorRole, Argb>,
230        }
231
232        let raw = SerializedColorScheme::deserialize(deserializer)?;
233        let mut scheme = Self::baseline(raw.appearance);
234        for (role, color) in raw.overrides {
235            scheme.set_color(role, color);
236        }
237        Ok(scheme)
238    }
239}
240
241impl Default for ColorScheme {
242    fn default() -> Self {
243        Self::baseline(Appearance::Light)
244    }
245}
246
247impl ColorScheme {
248    /// Returns the baseline Material 3 color scheme for the given [`Appearance`].
249    pub const fn baseline(appearance: Appearance) -> Self {
250        Self {
251            appearance,
252            colors: match appearance {
253                Appearance::Light => LIGHT,
254                Appearance::Dark => DARK,
255            },
256        }
257    }
258
259    /// Returns the [`Appearance`] (light or dark) associated with this scheme.
260    pub const fn appearance(&self) -> Appearance {
261        self.appearance
262    }
263
264    /// Resolves a semantic [`ColorRole`] to its packed [`Argb`] value.
265    pub const fn color(&self, role: ColorRole) -> Argb {
266        self.colors[role as usize]
267    }
268
269    /// Overrides one role. Callers overriding a background should also check its foreground.
270    pub fn set_color(&mut self, role: ColorRole, color: Argb) {
271        self.colors[role as usize] = color;
272    }
273
274    /// Fluent counterpart to [`Self::set_color`].
275    pub fn with_color(mut self, role: ColorRole, color: Argb) -> Self {
276        self.set_color(role, color);
277        self
278    }
279
280    #[cfg(feature = "serde")]
281    const fn baseline_color(&self, role: ColorRole) -> Argb {
282        match self.appearance {
283            Appearance::Light => LIGHT[role as usize],
284            Appearance::Dark => DARK[role as usize],
285        }
286    }
287
288    /// Resolves the standard foreground for a semantic background.
289    pub fn pair(&self, background: ColorRole) -> Option<ColorPair> {
290        let foreground = background.on_role()?;
291        Some(ColorPair {
292            foreground: self.color(foreground),
293            background: self.color(background),
294        })
295    }
296
297    /// Interpolates all resolved sRGB and alpha channels. The target appearance
298    /// takes effect at the midpoint. Values outside 0–1 clamp, and NaN uses 0.
299    pub fn blend(&self, target: &Self, t: f32) -> Self {
300        if t.is_nan() || t <= 0.0 || self == target {
301            return self.clone();
302        }
303        if t >= 1.0 {
304            return target.clone();
305        }
306        let appearance = if t < 0.5 {
307            self.appearance
308        } else {
309            target.appearance
310        };
311        let colors = std::array::from_fn(|index| {
312            let from = self.colors[index].channels();
313            let to = target.colors[index].channels();
314            let channels = std::array::from_fn(|i| {
315                let start = f32::from(from[i]);
316                (start + (f32::from(to[i]) - start) * t).round() as u8
317            });
318            Argb::from_u32(u32::from_be_bytes(channels))
319        });
320        Self { appearance, colors }
321    }
322
323    /// Applies the Compose tonal-elevation tint to the surface role.
324    pub fn surface_at_elevation(&self, elevation: Elevation) -> Argb {
325        let surface = self.color(ColorRole::Surface);
326        let dp = elevation.dp();
327        if dp == 0.0 {
328            return surface;
329        }
330
331        let overlay_alpha = (4.5 * dp.ln_1p() + 2.0) / 100.0;
332        let [alpha, r, g, b] = surface.channels();
333        let [_, tint_r, tint_g, tint_b] = self.color(ColorRole::SurfaceTint).channels();
334        let under_alpha = f32::from(alpha) / 255.0 * (1.0 - overlay_alpha);
335        let alpha = overlay_alpha + under_alpha;
336        let composite = |under, over| {
337            ((f32::from(over) * overlay_alpha + f32::from(under) * under_alpha) / alpha).round()
338                as u8
339        };
340        Argb::from_u32(u32::from_be_bytes([
341            (alpha * 255.0).round() as u8,
342            composite(r, tint_r),
343            composite(g, tint_g),
344            composite(b, tint_b),
345        ]))
346    }
347
348    /// Generates Tonal Spot roles using MCU Spec2021. Contrast is clamped to
349    /// -1 through 1. NaN selects the default contrast (0).
350    #[cfg(feature = "dynamic-color")]
351    pub fn from_seed(seed: Argb, appearance: Appearance, contrast: f64) -> Self {
352        Self::from_seed_with(
353            seed,
354            appearance,
355            contrast,
356            crate::DynamicVariant::TonalSpot,
357            crate::SpecVersion::Spec2021,
358        )
359    }
360}
361
362/// The six Material elevation levels. The renderer supplies the shadow.
363#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
364pub enum Elevation {
365    /// Resting elevation (`0 dp`, default).
366    #[default]
367    Level0,
368    /// Low elevation (`1 dp`).
369    Level1,
370    /// Medium-low elevation (`3 dp`).
371    Level2,
372    /// Medium elevation (`6 dp`).
373    Level3,
374    /// Medium-high elevation (`8 dp`).
375    Level4,
376    /// Highest elevation (`12 dp`).
377    Level5,
378}
379
380impl Elevation {
381    /// Returns the Material elevation height in density-independent pixels (`dp`).
382    pub const fn dp(self) -> f32 {
383        match self {
384            Self::Level0 => MD_SYS_ELEVATION_LEVEL_0,
385            Self::Level1 => MD_SYS_ELEVATION_LEVEL_1,
386            Self::Level2 => MD_SYS_ELEVATION_LEVEL_2,
387            Self::Level3 => MD_SYS_ELEVATION_LEVEL_3,
388            Self::Level4 => MD_SYS_ELEVATION_LEVEL_4,
389            Self::Level5 => MD_SYS_ELEVATION_LEVEL_5,
390        }
391    }
392}
393
394/// Material state layer opacities.
395#[derive(Clone, Copy, Debug, PartialEq, Eq)]
396pub enum StateLayer {
397    /// Pointer hover state layer.
398    Hover,
399    /// Keyboard or programmatic focus state layer.
400    Focus,
401    /// Active press state layer.
402    Pressed,
403    /// Active drag state layer.
404    Dragged,
405}
406
407impl StateLayer {
408    /// Returns the normalized Material state-layer opacity (`0.0..=1.0`).
409    pub const fn opacity(self) -> f32 {
410        match self {
411            Self::Hover => MD_SYS_STATE_HOVER_STATE_LAYER_OPACITY,
412            Self::Focus => MD_SYS_STATE_FOCUS_STATE_LAYER_OPACITY,
413            Self::Pressed => MD_SYS_STATE_PRESSED_STATE_LAYER_OPACITY,
414            Self::Dragged => MD_SYS_STATE_DRAGGED_STATE_LAYER_OPACITY,
415        }
416    }
417}
418/// Returns the contrast ratio for two CIE L* tones, clamped to 0 through 100.
419/// Returns `None` if either tone is NaN.
420#[cfg(feature = "dynamic-color")]
421pub fn contrast_ratio_of_tones(first: f64, second: f64) -> Option<f64> {
422    use material_color_utils::contrast::contrast_utils::Contrast;
423
424    if first.is_nan() || second.is_nan() {
425        return None;
426    }
427    Some(Contrast::ratio_of_tones(
428        first.clamp(0.0, 100.0),
429        second.clamp(0.0, 100.0),
430    ))
431}