Skip to main content

gpui_material_theme/
dynamic_color.rs

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