Skip to main content

gpui_material_theme/
dynamic_color.rs

1use material_color_utils::{
2    blend::blend_functions::Blend,
3    dynamic::color_spec::SpecVersion as McuSpec,
4    palettes::tonal_palette::TonalPalette,
5    scheme::{
6        SchemeContent, SchemeExpressive, SchemeFidelity, SchemeMonochrome, SchemeNeutral,
7        SchemeTonalSpot, SchemeVibrant,
8    },
9    utils::color_utils::Argb as McuArgb,
10};
11
12use crate::{
13    Appearance, Argb, ColorPair, ColorRole, ColorScheme, MaterialTheme, generated::dynamic_colors,
14};
15
16/// Resolved Material 3 four-role custom color group for one appearance.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19pub struct CustomColorGroup {
20    /// Accent color for high-emphasis custom fills and outlines.
21    pub color: Argb,
22    /// Foreground color paired with [`Self::color`].
23    pub on_color: Argb,
24    /// Tonal container fill derived from the custom seed.
25    pub color_container: Argb,
26    /// Foreground color paired with [`Self::color_container`].
27    pub on_color_container: Argb,
28}
29
30impl CustomColorGroup {
31    /// Returns the primary `(on_color, color)` foreground/background pair.
32    pub const fn pair(self) -> ColorPair {
33        ColorPair {
34            foreground: self.on_color,
35            background: self.color,
36        }
37    }
38
39    /// Returns the tonal `(on_color_container, color_container)` pair.
40    pub const fn container_pair(self) -> ColorPair {
41        ColorPair {
42            foreground: self.on_color_container,
43            background: self.color_container,
44        }
45    }
46}
47
48/// Shifts `design`'s hue toward `source` using Material Color Utilities harmonization.
49/// Input alpha channels are ignored and the returned color is opaque.
50pub fn harmonize_color(design: Argb, source: Argb) -> Argb {
51    let design = McuArgb(design.to_u32() | 0xff00_0000);
52    let source = McuArgb(source.to_u32() | 0xff00_0000);
53    Argb::from_u32(Blend::harmonize(design, source).0)
54}
55
56/// The Material dynamic color palette to derive from a seed.
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59pub enum DynamicVariant {
60    /// Default Material 3 balanced tonal palette with moderate chroma.
61    #[default]
62    TonalSpot,
63    /// High-chroma accent palette with bold secondary and tertiary hues.
64    Vibrant,
65    /// Detached, playful hue rotation for expressive Material 3 palettes.
66    Expressive,
67    /// Preserves the seed color closely in the primary palette.
68    Fidelity,
69    /// Derives accents faithful to source content colors.
70    Content,
71    /// Achromatic grayscale palette.
72    Monochrome,
73    /// Low-chroma near-neutral palette.
74    Neutral,
75}
76
77/// The requested Material Color Utilities specification.
78#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
79#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
80pub enum SpecVersion {
81    /// Material Color Utilities 2021 specification (default).
82    #[default]
83    Spec2021,
84    /// Material Color Utilities 2025 specification (applies to `TonalSpot`, `Vibrant`, `Expressive`, and `Neutral`).
85    Spec2025,
86}
87
88impl ColorScheme {
89    /// Generates a scheme for an opaque sRGB seed. Contrast clamps to −1–1,
90    /// with NaN using 0. Fidelity, Content, and Monochrome resolve with Spec2021.
91    pub fn from_seed_with(
92        seed: Argb,
93        appearance: Appearance,
94        contrast: f64,
95        variant: DynamicVariant,
96        spec_version: SpecVersion,
97    ) -> Self {
98        let seed = McuArgb(seed.to_u32() | 0xff00_0000);
99        let contrast = if contrast.is_nan() {
100            0.0
101        } else {
102            contrast.clamp(-1.0, 1.0)
103        };
104        let dark = appearance == Appearance::Dark;
105        let spec = match (spec_version, variant) {
106            (
107                SpecVersion::Spec2025,
108                DynamicVariant::TonalSpot
109                | DynamicVariant::Vibrant
110                | DynamicVariant::Expressive
111                | DynamicVariant::Neutral,
112            ) => McuSpec::Spec2025,
113            _ => McuSpec::Spec2021,
114        };
115        macro_rules! build {
116            ($scheme:ident) => {
117                $scheme::builder(seed, dark, contrast)
118                    .spec_version(spec)
119                    .build()
120            };
121        }
122        let mut scheme = match variant {
123            DynamicVariant::TonalSpot => build!(SchemeTonalSpot),
124            DynamicVariant::Vibrant => build!(SchemeVibrant),
125            DynamicVariant::Expressive => build!(SchemeExpressive),
126            DynamicVariant::Fidelity => build!(SchemeFidelity),
127            DynamicVariant::Content => build!(SchemeContent),
128            DynamicVariant::Monochrome => build!(SchemeMonochrome),
129            DynamicVariant::Neutral => build!(SchemeNeutral),
130        };
131        let mut colors = Self::baseline(appearance);
132        for (role, color) in dynamic_colors(&scheme) {
133            colors.set_color(role, color);
134        }
135        use ColorRole::*;
136        for (status_seed, roles) in [
137            (0xff00_61a4, [Info, OnInfo, InfoContainer, OnInfoContainer]),
138            (
139                0xff00_6c4e,
140                [Success, OnSuccess, SuccessContainer, OnSuccessContainer],
141            ),
142            (
143                0xff97_4800,
144                [Warning, OnWarning, WarningContainer, OnWarningContainer],
145            ),
146        ] {
147            // Resolve each custom palette with the same tone and contrast
148            // relationships as Error, against the generated surface palette.
149            scheme.error_palette =
150                TonalPalette::from_hct(Blend::harmonize(McuArgb(status_seed), seed).into());
151            scheme.argb_cache.pin().clear();
152            scheme.hct_cache.pin().clear();
153            scheme.tone_cache.pin().clear();
154            let values = [
155                scheme.error(),
156                scheme.on_error(),
157                scheme.error_container(),
158                scheme.on_error_container(),
159            ];
160            for (role, color) in roles.into_iter().zip(values) {
161                colors.set_color(role, Argb::from_u32(color.0));
162            }
163        }
164        colors
165    }
166
167    /// Resolves a Material 3 four-role [`CustomColorGroup`] for `seed` in this
168    /// scheme's appearance at default contrast (`0.0`).
169    ///
170    /// When `harmonize` is `true`, `seed` is shifted toward this scheme's
171    /// [`ColorRole::Primary`] role before tone derivation.
172    pub fn custom_color(&self, seed: Argb, harmonize: bool) -> CustomColorGroup {
173        self.custom_color_with_contrast(seed, 0.0, harmonize)
174    }
175
176    /// Resolves a Material 3 four-role [`CustomColorGroup`] for `seed` in this
177    /// scheme's appearance and requested contrast (`-1.0..=1.0`, `NaN` -> `0.0`).
178    ///
179    /// Uses MCU's error-role contrast curve against a Tonal Spot scheme seeded
180    /// from this scheme's [`ColorRole::Primary`] role.
181    pub fn custom_color_with_contrast(
182        &self,
183        seed: Argb,
184        contrast: f64,
185        harmonize: bool,
186    ) -> CustomColorGroup {
187        let primary = McuArgb(self.color(ColorRole::Primary).to_u32() | 0xff00_0000);
188        let target = if harmonize {
189            McuArgb(harmonize_color(seed, self.color(ColorRole::Primary)).to_u32())
190        } else {
191            McuArgb(seed.to_u32() | 0xff00_0000)
192        };
193        let contrast = if contrast.is_nan() {
194            0.0
195        } else {
196            contrast.clamp(-1.0, 1.0)
197        };
198        let mut scheme =
199            SchemeTonalSpot::builder(primary, self.appearance() == Appearance::Dark, contrast)
200                .spec_version(McuSpec::Spec2021)
201                .build();
202        scheme.error_palette = TonalPalette::from_hct(target.into());
203        CustomColorGroup {
204            color: Argb::from_u32(scheme.error().0),
205            on_color: Argb::from_u32(scheme.on_error().0),
206            color_container: Argb::from_u32(scheme.error_container().0),
207            on_color_container: Argb::from_u32(scheme.on_error_container().0),
208        }
209    }
210}
211
212impl MaterialTheme {
213    /// Generates colors while keeping the default typography, motion, and layout.
214    pub fn from_seed_with(
215        seed: Argb,
216        appearance: Appearance,
217        contrast: f64,
218        variant: DynamicVariant,
219        spec_version: SpecVersion,
220    ) -> Self {
221        Self {
222            colors: ColorScheme::from_seed_with(seed, appearance, contrast, variant, spec_version),
223            ..Self::default()
224        }
225    }
226}
227
228/// Bundled palette recipes, with seed colors inspired by md3.io.
229#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
230#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
231pub enum ThemePreset {
232    /// Standard Material 3 baseline purple palette (default).
233    #[default]
234    Baseline,
235    /// Tonal Spot dynamic scheme derived from the baseline seed.
236    TonalSpot,
237    /// Vibrant dynamic scheme derived from the baseline seed.
238    Vibrant,
239    /// Expressive dynamic scheme derived from the baseline seed.
240    Expressive,
241    /// Fidelity dynamic scheme derived from the baseline seed.
242    Fidelity,
243    /// Content dynamic scheme derived from the baseline seed.
244    Content,
245    /// Monochrome grayscale dynamic scheme.
246    Monochrome,
247    /// Low-chroma neutral dynamic scheme.
248    Neutral,
249    /// High-contrast (`contrast = 1.0`) Tonal Spot scheme derived from the baseline seed.
250    HighContrast,
251    /// Deep ocean blue Tonal Spot palette.
252    Ocean,
253    /// Forest green Tonal Spot palette.
254    Forest,
255    /// Bright spring green Tonal Spot palette.
256    Spring,
257    /// Warm sunset orange Tonal Spot palette.
258    Sunset,
259    /// Earthy desert ochre Tonal Spot palette.
260    Desert,
261    /// Clear summer sky blue Tonal Spot palette.
262    Summer,
263    /// Warm brown and beige Tonal Spot palette.
264    BrownBeige,
265    /// Muted sage and ivory Tonal Spot palette.
266    SageIvory,
267    /// Deep teal and caramel Tonal Spot palette.
268    TealCaramel,
269}
270
271impl ThemePreset {
272    /// All bundled presets in display order.
273    pub const ALL: [Self; 18] = [
274        Self::Baseline,
275        Self::TonalSpot,
276        Self::Vibrant,
277        Self::Expressive,
278        Self::Fidelity,
279        Self::Content,
280        Self::Monochrome,
281        Self::Neutral,
282        Self::HighContrast,
283        Self::Ocean,
284        Self::Forest,
285        Self::Spring,
286        Self::Sunset,
287        Self::Desert,
288        Self::Summer,
289        Self::BrownBeige,
290        Self::SageIvory,
291        Self::TealCaramel,
292    ];
293
294    /// Resolves the preset for the requested appearance.
295    pub fn colors(self, appearance: Appearance) -> ColorScheme {
296        use DynamicVariant as Variant;
297        const BASELINE_SEED: u32 = 0xff67_50a4;
298        let (seed, variant) = match self {
299            Self::Baseline => return ColorScheme::baseline(appearance),
300            Self::TonalSpot | Self::HighContrast => (BASELINE_SEED, Variant::TonalSpot),
301            Self::Vibrant => (BASELINE_SEED, Variant::Vibrant),
302            Self::Expressive => (BASELINE_SEED, Variant::Expressive),
303            Self::Fidelity => (BASELINE_SEED, Variant::Fidelity),
304            Self::Content => (BASELINE_SEED, Variant::Content),
305            Self::Monochrome => (BASELINE_SEED, Variant::Monochrome),
306            Self::Neutral => (BASELINE_SEED, Variant::Neutral),
307            Self::Ocean => (0xff00_6c9c, Variant::TonalSpot),
308            Self::Forest => (0xff4b_5d3a, Variant::TonalSpot),
309            Self::Spring => (0xff76_d275, Variant::TonalSpot),
310            Self::Sunset => (0xffd3_5400, Variant::TonalSpot),
311            Self::Desert => (0xff9a_7a3e, Variant::TonalSpot),
312            Self::Summer => (0xff41_96cb, Variant::TonalSpot),
313            Self::BrownBeige => (0xff3e_2723, Variant::TonalSpot),
314            Self::SageIvory => (0xff7d_8c73, Variant::TonalSpot),
315            Self::TealCaramel => (0xff2b_4d56, Variant::TonalSpot),
316        };
317        ColorScheme::from_seed_with(
318            Argb::from_u32(seed),
319            appearance,
320            f64::from(self == Self::HighContrast),
321            variant,
322            SpecVersion::Spec2021,
323        )
324    }
325
326    /// Builds a complete [`MaterialTheme`] using this preset's colors and default typography, motion, and layout.
327    pub fn theme(self, appearance: Appearance) -> MaterialTheme {
328        MaterialTheme {
329            colors: self.colors(appearance),
330            ..MaterialTheme::default()
331        }
332    }
333}