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)]
45pub struct ColorScheme {
46    appearance: Appearance,
47    colors: [Argb; ColorRole::ALL.len()],
48}
49
50#[cfg(feature = "serde")]
51impl serde::Serialize for ColorScheme {
52    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
53        #[derive(serde::Serialize)]
54        #[serde(rename = "ColorScheme")]
55        struct SerializedColorScheme {
56            appearance: Appearance,
57            overrides: std::collections::BTreeMap<ColorRole, Argb>,
58        }
59
60        let mut overrides = std::collections::BTreeMap::new();
61        for role in ColorRole::ALL {
62            let color = self.colors[role as usize];
63            if color != self.baseline_color(role) {
64                overrides.insert(role, color);
65            }
66        }
67        SerializedColorScheme {
68            appearance: self.appearance,
69            overrides,
70        }
71        .serialize(serializer)
72    }
73}
74
75#[cfg(feature = "serde")]
76impl<'de> serde::Deserialize<'de> for ColorScheme {
77    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
78        #[derive(serde::Deserialize)]
79        #[serde(rename = "ColorScheme")]
80        struct SerializedColorScheme {
81            appearance: Appearance,
82            // Keep the serialized form keyed by role so additions can use baseline defaults.
83            #[serde(default)]
84            overrides: std::collections::BTreeMap<ColorRole, Argb>,
85        }
86
87        let raw = SerializedColorScheme::deserialize(deserializer)?;
88        let mut scheme = Self::baseline(raw.appearance);
89        for (role, color) in raw.overrides {
90            scheme.set_color(role, color);
91        }
92        Ok(scheme)
93    }
94}
95
96impl Default for ColorScheme {
97    fn default() -> Self {
98        Self::baseline(Appearance::Light)
99    }
100}
101
102impl ColorScheme {
103    pub const fn baseline(appearance: Appearance) -> Self {
104        Self {
105            appearance,
106            colors: match appearance {
107                Appearance::Light => LIGHT,
108                Appearance::Dark => DARK,
109            },
110        }
111    }
112
113    pub const fn appearance(&self) -> Appearance {
114        self.appearance
115    }
116
117    pub const fn color(&self, role: ColorRole) -> Argb {
118        self.colors[role as usize]
119    }
120
121    /// Overrides one role. Callers overriding a background should also check its foreground.
122    pub fn set_color(&mut self, role: ColorRole, color: Argb) {
123        self.colors[role as usize] = color;
124    }
125
126    #[cfg(feature = "serde")]
127    const fn baseline_color(&self, role: ColorRole) -> Argb {
128        match self.appearance {
129            Appearance::Light => LIGHT[role as usize],
130            Appearance::Dark => DARK[role as usize],
131        }
132    }
133
134    /// Resolves the standard foreground for a semantic background.
135    pub fn pair(&self, background: ColorRole) -> Option<ColorPair> {
136        use ColorRole::*;
137
138        let foreground = match background {
139            Background => OnBackground,
140            Error => OnError,
141            ErrorContainer => OnErrorContainer,
142            Info => OnInfo,
143            InfoContainer => OnInfoContainer,
144            InverseSurface => InverseOnSurface,
145            Primary => OnPrimary,
146            PrimaryContainer => OnPrimaryContainer,
147            PrimaryFixed | PrimaryFixedDim => OnPrimaryFixed,
148            Secondary => OnSecondary,
149            SecondaryContainer => OnSecondaryContainer,
150            SecondaryFixed | SecondaryFixedDim => OnSecondaryFixed,
151            Success => OnSuccess,
152            SuccessContainer => OnSuccessContainer,
153            Surface
154            | SurfaceBright
155            | SurfaceDim
156            | SurfaceContainerLowest
157            | SurfaceContainerLow
158            | SurfaceContainer
159            | SurfaceContainerHigh
160            | SurfaceContainerHighest => OnSurface,
161            SurfaceVariant => OnSurfaceVariant,
162            Tertiary => OnTertiary,
163            TertiaryContainer => OnTertiaryContainer,
164            TertiaryFixed | TertiaryFixedDim => OnTertiaryFixed,
165            Warning => OnWarning,
166            WarningContainer => OnWarningContainer,
167            _ => return None,
168        };
169        Some(ColorPair {
170            foreground: self.color(foreground),
171            background: self.color(background),
172        })
173    }
174
175    /// Interpolates all resolved sRGB and alpha channels. The target appearance
176    /// takes effect at the midpoint. Values outside 0–1 clamp, and NaN uses 0.
177    pub fn blend(&self, target: &Self, t: f32) -> Self {
178        if t.is_nan() || t <= 0.0 || self == target {
179            return self.clone();
180        }
181        if t >= 1.0 {
182            return target.clone();
183        }
184        let appearance = if t < 0.5 {
185            self.appearance
186        } else {
187            target.appearance
188        };
189        let colors = std::array::from_fn(|index| {
190            let from = self.colors[index].channels();
191            let to = target.colors[index].channels();
192            let channels = std::array::from_fn(|i| {
193                let start = f32::from(from[i]);
194                (start + (f32::from(to[i]) - start) * t).round() as u8
195            });
196            Argb::from_u32(u32::from_be_bytes(channels))
197        });
198        Self { appearance, colors }
199    }
200
201    /// Applies the Compose tonal-elevation tint to the surface role.
202    pub fn surface_at_elevation(&self, elevation: Elevation) -> Argb {
203        let surface = self.color(ColorRole::Surface);
204        let dp = elevation.dp();
205        if dp == 0.0 {
206            return surface;
207        }
208
209        let overlay_alpha = (4.5 * dp.ln_1p() + 2.0) / 100.0;
210        let [alpha, r, g, b] = surface.channels();
211        let [_, tint_r, tint_g, tint_b] = self.color(ColorRole::SurfaceTint).channels();
212        let under_alpha = f32::from(alpha) / 255.0 * (1.0 - overlay_alpha);
213        let alpha = overlay_alpha + under_alpha;
214        let composite = |under, over| {
215            ((f32::from(over) * overlay_alpha + f32::from(under) * under_alpha) / alpha).round()
216                as u8
217        };
218        Argb::from_u32(u32::from_be_bytes([
219            (alpha * 255.0).round() as u8,
220            composite(r, tint_r),
221            composite(g, tint_g),
222            composite(b, tint_b),
223        ]))
224    }
225
226    /// Generates Tonal Spot roles using MCU Spec2021. Contrast is clamped to
227    /// -1 through 1. NaN selects the default contrast (0).
228    #[cfg(feature = "dynamic-color")]
229    pub fn from_seed(seed: Argb, appearance: Appearance, contrast: f64) -> Self {
230        Self::from_seed_with(
231            seed,
232            appearance,
233            contrast,
234            crate::DynamicVariant::TonalSpot,
235            crate::SpecVersion::Spec2021,
236        )
237    }
238}
239
240/// The six Material elevation levels. The renderer supplies the shadow.
241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
242pub enum Elevation {
243    #[default]
244    Level0,
245    Level1,
246    Level2,
247    Level3,
248    Level4,
249    Level5,
250}
251
252impl Elevation {
253    pub const fn dp(self) -> f32 {
254        match self {
255            Self::Level0 => MD_SYS_ELEVATION_LEVEL_0,
256            Self::Level1 => MD_SYS_ELEVATION_LEVEL_1,
257            Self::Level2 => MD_SYS_ELEVATION_LEVEL_2,
258            Self::Level3 => MD_SYS_ELEVATION_LEVEL_3,
259            Self::Level4 => MD_SYS_ELEVATION_LEVEL_4,
260            Self::Level5 => MD_SYS_ELEVATION_LEVEL_5,
261        }
262    }
263}
264
265/// Material state layer opacities.
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267pub enum StateLayer {
268    Hover,
269    Focus,
270    Pressed,
271    Dragged,
272}
273
274impl StateLayer {
275    pub const fn opacity(self) -> f32 {
276        match self {
277            Self::Hover => MD_SYS_STATE_HOVER_STATE_LAYER_OPACITY,
278            Self::Focus => MD_SYS_STATE_FOCUS_STATE_LAYER_OPACITY,
279            Self::Pressed => MD_SYS_STATE_PRESSED_STATE_LAYER_OPACITY,
280            Self::Dragged => MD_SYS_STATE_DRAGGED_STATE_LAYER_OPACITY,
281        }
282    }
283}
284/// Returns the contrast ratio for two CIE L* tones, clamped to 0 through 100.
285/// Returns `None` if either tone is NaN.
286#[cfg(feature = "dynamic-color")]
287pub fn contrast_ratio_of_tones(first: f64, second: f64) -> Option<f64> {
288    use material_color_utils::contrast::contrast_utils::Contrast;
289
290    if first.is_nan() || second.is_nan() {
291        return None;
292    }
293    Some(Contrast::ratio_of_tones(
294        first.clamp(0.0, 100.0),
295        second.clamp(0.0, 100.0),
296    ))
297}