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