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