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            Info => OnInfo,
103            InfoContainer => OnInfoContainer,
104            InverseSurface => InverseOnSurface,
105            Primary => OnPrimary,
106            PrimaryContainer => OnPrimaryContainer,
107            PrimaryFixed | PrimaryFixedDim => OnPrimaryFixed,
108            Secondary => OnSecondary,
109            SecondaryContainer => OnSecondaryContainer,
110            SecondaryFixed | SecondaryFixedDim => OnSecondaryFixed,
111            Success => OnSuccess,
112            SuccessContainer => OnSuccessContainer,
113            Surface
114            | SurfaceBright
115            | SurfaceDim
116            | SurfaceContainerLowest
117            | SurfaceContainerLow
118            | SurfaceContainer
119            | SurfaceContainerHigh
120            | SurfaceContainerHighest => OnSurface,
121            SurfaceVariant => OnSurfaceVariant,
122            Tertiary => OnTertiary,
123            TertiaryContainer => OnTertiaryContainer,
124            TertiaryFixed | TertiaryFixedDim => OnTertiaryFixed,
125            Warning => OnWarning,
126            WarningContainer => OnWarningContainer,
127            _ => return None,
128        };
129        Some(ColorPair {
130            foreground: self.color(foreground),
131            background: self.color(background),
132        })
133    }
134
135    /// Interpolates all resolved sRGB and alpha channels. The target appearance
136    /// takes effect at the midpoint. Values outside 0–1 clamp, and NaN uses 0.
137    pub fn blend(&self, target: &Self, t: f32) -> Self {
138        if t.is_nan() || t <= 0.0 || self == target {
139            return self.clone();
140        }
141        if t >= 1.0 {
142            return target.clone();
143        }
144        let appearance = if t < 0.5 {
145            self.appearance
146        } else {
147            target.appearance
148        };
149        let mut blended = Self::baseline(appearance);
150        for role in ColorRole::ALL {
151            let from = self.color(role).channels();
152            let to = target.color(role).channels();
153            let channels = std::array::from_fn(|i| {
154                let start = f32::from(from[i]);
155                (start + (f32::from(to[i]) - start) * t).round() as u8
156            });
157            blended.set_color(role, Argb::from_u32(u32::from_be_bytes(channels)));
158        }
159        blended
160    }
161
162    /// Applies the Compose tonal-elevation tint to the surface role.
163    pub fn surface_at_elevation(&self, elevation: Elevation) -> Argb {
164        let surface = self.color(ColorRole::Surface);
165        let dp = elevation.dp();
166        if dp == 0.0 {
167            return surface;
168        }
169
170        let overlay_alpha = (4.5 * dp.ln_1p() + 2.0) / 100.0;
171        let [alpha, r, g, b] = surface.channels();
172        let [_, tint_r, tint_g, tint_b] = self.color(ColorRole::SurfaceTint).channels();
173        let under_alpha = f32::from(alpha) / 255.0 * (1.0 - overlay_alpha);
174        let alpha = overlay_alpha + under_alpha;
175        let composite = |under, over| {
176            ((f32::from(over) * overlay_alpha + f32::from(under) * under_alpha) / alpha).round()
177                as u8
178        };
179        Argb::from_u32(u32::from_be_bytes([
180            (alpha * 255.0).round() as u8,
181            composite(r, tint_r),
182            composite(g, tint_g),
183            composite(b, tint_b),
184        ]))
185    }
186
187    /// Generates Tonal Spot roles using MCU Spec2021. Contrast is clamped to
188    /// -1 through 1. NaN selects the default contrast (0).
189    #[cfg(feature = "dynamic-color")]
190    pub fn from_seed(seed: Argb, appearance: Appearance, contrast: f64) -> Self {
191        Self::from_seed_with(
192            seed,
193            appearance,
194            contrast,
195            crate::DynamicVariant::TonalSpot,
196            crate::SpecVersion::Spec2021,
197        )
198    }
199}
200
201/// The six Material elevation levels. The renderer supplies the shadow.
202#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
203pub enum Elevation {
204    #[default]
205    Level0,
206    Level1,
207    Level2,
208    Level3,
209    Level4,
210    Level5,
211}
212
213impl Elevation {
214    pub const fn dp(self) -> f32 {
215        match self {
216            Self::Level0 => MD_SYS_ELEVATION_LEVEL_0,
217            Self::Level1 => MD_SYS_ELEVATION_LEVEL_1,
218            Self::Level2 => MD_SYS_ELEVATION_LEVEL_2,
219            Self::Level3 => MD_SYS_ELEVATION_LEVEL_3,
220            Self::Level4 => MD_SYS_ELEVATION_LEVEL_4,
221            Self::Level5 => MD_SYS_ELEVATION_LEVEL_5,
222        }
223    }
224}
225
226/// Material state layer opacities.
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228pub enum StateLayer {
229    Hover,
230    Focus,
231    Pressed,
232    Dragged,
233}
234
235impl StateLayer {
236    pub const fn opacity(self) -> f32 {
237        match self {
238            Self::Hover => MD_SYS_STATE_HOVER_STATE_LAYER_OPACITY,
239            Self::Focus => MD_SYS_STATE_FOCUS_STATE_LAYER_OPACITY,
240            Self::Pressed => MD_SYS_STATE_PRESSED_STATE_LAYER_OPACITY,
241            Self::Dragged => MD_SYS_STATE_DRAGGED_STATE_LAYER_OPACITY,
242        }
243    }
244}
245/// Returns the contrast ratio for two CIE L* tones, clamped to 0 through 100.
246/// Returns `None` if either tone is NaN.
247#[cfg(feature = "dynamic-color")]
248pub fn contrast_ratio_of_tones(first: f64, second: f64) -> Option<f64> {
249    use material_color_utils::contrast::contrast_utils::Contrast;
250
251    if first.is_nan() || second.is_nan() {
252        return None;
253    }
254    Some(Contrast::ratio_of_tones(
255        first.clamp(0.0, 100.0),
256        second.clamp(0.0, 100.0),
257    ))
258}