Skip to main content

gpui_component/theme/
color.rs

1use std::{collections::HashMap, fmt::Display};
2
3use gpui::{
4    Background, Hsla, LinearColorStop, SharedString, hsla, linear_color_stop, linear_gradient,
5};
6use palette::IntoColor as _;
7use serde::{Deserialize, Deserializer, de::Error as _};
8
9use anyhow::{Error, Result, anyhow};
10
11/// Create a [`gpui::Hsla`] color.
12///
13/// - h: 0..360.0
14/// - s: 0.0..100.0
15/// - l: 0.0..100.0
16#[inline]
17pub fn hsl(h: f32, s: f32, l: f32) -> Hsla {
18    hsla(h / 360., s / 100.0, l / 100.0, 1.0)
19}
20
21pub trait Colorize: Sized {
22    /// Returns a new color with the given opacity.
23    ///
24    /// The opacity is a value between 0.0 and 1.0, where 0.0 is fully transparent and 1.0 is fully opaque.
25    fn opacity(&self, opacity: f32) -> Self;
26    /// Returns a new color with each channel divided by the given divisor.
27    ///
28    /// The divisor in range of 0.0 .. 1.0
29    fn divide(&self, divisor: f32) -> Self;
30    /// Return inverted color
31    fn invert(&self) -> Self;
32    /// Return inverted lightness
33    fn invert_l(&self) -> Self;
34    /// Return a new color with the lightness increased by the given factor.
35    ///
36    /// factor range: 0.0 .. 1.0
37    fn lighten(&self, amount: f32) -> Self;
38    /// Return a new color with the darkness increased by the given factor.
39    ///
40    /// factor range: 0.0 .. 1.0
41    fn darken(&self, amount: f32) -> Self;
42    /// Return a new color with the same lightness and alpha but different hue and saturation.
43    fn apply(&self, base_color: Self) -> Self;
44
45    /// Mix two colors together, the `factor` is a value between 0.0 and 1.0 for first color.
46    fn mix(&self, other: Self, factor: f32) -> Self;
47    /// Mix two colors together in Oklab color space, the `factor` is a value between 0.0 and 1.0 for first color.
48    ///
49    /// This is similar to CSS `color-mix(in oklab, color1 factor%, color2)`.
50    fn mix_oklab(&self, other: Self, factor: f32) -> Self;
51    /// Change the `Hue` of the color by the given in range: 0.0 .. 1.0
52    fn hue(&self, hue: f32) -> Self;
53    /// Change the `Saturation` of the color by the given value in range: 0.0 .. 1.0
54    fn saturation(&self, saturation: f32) -> Self;
55    /// Change the `Lightness` of the color by the given value in range: 0.0 .. 1.0
56    fn lightness(&self, lightness: f32) -> Self;
57
58    /// Convert the color to a hex string. For example, "#F8FAFC".
59    fn to_hex(&self) -> String;
60    /// Parse a hex string to a color.
61    fn parse_hex(hex: &str) -> Result<Self>;
62}
63
64/// Helper functions for Oklab color space conversions
65mod oklab {
66    use gpui::Rgba;
67
68    /// Convert sRGB component to linear RGB
69    #[inline]
70    fn to_linear(c: f32) -> f32 {
71        if c <= 0.04045 {
72            c / 12.92
73        } else {
74            ((c + 0.055) / 1.055).powf(2.4)
75        }
76    }
77
78    /// Convert linear RGB component to sRGB
79    #[inline]
80    fn from_linear(c: f32) -> f32 {
81        if c <= 0.0031308 {
82            c * 12.92
83        } else {
84            1.055 * c.powf(1.0 / 2.4) - 0.055
85        }
86    }
87
88    /// Convert RGB to Oklab color space
89    #[allow(non_snake_case)]
90    pub fn rgb_to_oklab(rgb: Rgba) -> (f32, f32, f32) {
91        // sRGB to linear RGB
92        let lr = to_linear(rgb.color.red);
93        let lg = to_linear(rgb.color.green);
94        let lb = to_linear(rgb.color.blue);
95
96        // Linear RGB to LMS
97        let l = 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb;
98        let m = 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb;
99        let s = 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb;
100
101        // LMS to Oklab (using cube root)
102        let l_ = l.cbrt();
103        let m_ = m.cbrt();
104        let s_ = s.cbrt();
105
106        let L = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_;
107        let a = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_;
108        let b = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_;
109
110        (L, a, b)
111    }
112
113    /// Convert Oklab to RGB color space
114    #[allow(non_snake_case)]
115    pub fn oklab_to_rgb(L: f32, a: f32, b: f32) -> Rgba {
116        // Oklab to LMS
117        let l_ = L + 0.3963377774 * a + 0.2158037573 * b;
118        let m_ = L - 0.1055613458 * a - 0.0638541728 * b;
119        let s_ = L - 0.0894841775 * a - 1.2914855480 * b;
120
121        let l = l_ * l_ * l_;
122        let m = m_ * m_ * m_;
123        let s = s_ * s_ * s_;
124
125        // LMS to Linear RGB
126        let lr = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s;
127        let lg = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s;
128        let lb = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s;
129
130        // Linear RGB to sRGB
131        Rgba::new(
132            from_linear(lr).clamp(0.0, 1.0),
133            from_linear(lg).clamp(0.0, 1.0),
134            from_linear(lb).clamp(0.0, 1.0),
135            1.0,
136        )
137    }
138}
139
140impl Colorize for Hsla {
141    fn opacity(&self, factor: f32) -> Self {
142        hsla(
143            hue(*self),
144            self.color.saturation,
145            self.color.lightness,
146            self.alpha * factor.clamp(0., 1.),
147        )
148    }
149
150    fn divide(&self, divisor: f32) -> Self {
151        hsla(
152            hue(*self),
153            self.color.saturation,
154            self.color.lightness,
155            divisor,
156        )
157    }
158
159    fn invert(&self) -> Self {
160        hsla(
161            1. - hue(*self),
162            1. - self.color.saturation,
163            1. - self.color.lightness,
164            self.alpha,
165        )
166    }
167
168    fn invert_l(&self) -> Self {
169        hsla(
170            hue(*self),
171            self.color.saturation,
172            1. - self.color.lightness,
173            self.alpha,
174        )
175    }
176
177    fn lighten(&self, factor: f32) -> Self {
178        hsla(
179            hue(*self),
180            self.color.saturation,
181            self.color.lightness * (1. + factor.clamp(0., 1.)),
182            self.alpha,
183        )
184    }
185
186    fn darken(&self, factor: f32) -> Self {
187        hsla(
188            hue(*self),
189            self.color.saturation,
190            self.color.lightness * (1. - factor.clamp(0., 1.)),
191            self.alpha,
192        )
193    }
194
195    fn apply(&self, new_color: Self) -> Self {
196        hsla(
197            hue(new_color),
198            new_color.color.saturation,
199            self.color.lightness,
200            self.alpha,
201        )
202    }
203
204    /// Reference:
205    /// https://github.com/bevyengine/bevy/blob/85eceb022da0326b47ac2b0d9202c9c9f01835bb/crates/bevy_color/src/hsla.rs#L112
206    fn mix(&self, other: Self, factor: f32) -> Self {
207        let factor = factor.clamp(0.0, 1.0);
208        let inv = 1.0 - factor;
209
210        #[inline]
211        fn lerp_hue(a: f32, b: f32, t: f32) -> f32 {
212            let diff = (b - a + 180.0).rem_euclid(360.) - 180.;
213            (a + diff * t).rem_euclid(360.0)
214        }
215
216        hsla(
217            lerp_hue(hue(*self) * 360., hue(other) * 360., factor) / 360.,
218            self.color.saturation * factor + other.color.saturation * inv,
219            self.color.lightness * factor + other.color.lightness * inv,
220            self.alpha * factor + other.alpha * inv,
221        )
222    }
223
224    #[allow(non_snake_case)]
225    fn mix_oklab(&self, other: Self, factor: f32) -> Self {
226        let factor = factor.clamp(0.0, 1.0);
227        let inv = 1.0 - factor;
228
229        // Interpolate alpha first
230        let result_alpha = self.alpha * factor + other.alpha * inv;
231
232        // Handle the case where result alpha is zero
233        if result_alpha == 0.0 {
234            return hsla(0., 0., 0., 0.);
235        }
236
237        // Convert both colors to RGB
238        let rgb1: gpui::Rgba = (*self).into_color();
239        let rgb2: gpui::Rgba = other.into_color();
240
241        // Convert to Oklab color space
242        let (l1, a1, b1) = oklab::rgb_to_oklab(rgb1);
243        let (l2, a2, b2) = oklab::rgb_to_oklab(rgb2);
244
245        // Premultiply alpha in Oklab space (using alpha-premultiplied interpolation)
246        // This matches CSS color-mix behavior
247        let alpha1 = self.alpha;
248        let alpha2 = other.alpha;
249
250        // Premultiply
251        let l1_pm = l1 * alpha1;
252        let a1_pm = a1 * alpha1;
253        let b1_pm = b1 * alpha1;
254
255        let l2_pm = l2 * alpha2;
256        let a2_pm = a2 * alpha2;
257        let b2_pm = b2 * alpha2;
258
259        // Interpolate premultiplied values
260        let L_pm = l1_pm * factor + l2_pm * inv;
261        let a_pm = a1_pm * factor + a2_pm * inv;
262        let b_pm = b1_pm * factor + b2_pm * inv;
263
264        // Unpremultiply
265        let L = L_pm / result_alpha;
266        let a = a_pm / result_alpha;
267        let b = b_pm / result_alpha;
268
269        // Convert back to RGB
270        let mut rgb = oklab::oklab_to_rgb(L, a, b);
271        rgb.alpha = result_alpha;
272
273        // Convert RGB to HSLA
274        let color: Hsla = rgb.into_color();
275        color
276    }
277
278    fn to_hex(&self) -> String {
279        let rgb: gpui::Rgba = (*self).into_color();
280
281        if rgb.alpha < 1. {
282            return format!(
283                "#{:02X}{:02X}{:02X}{:02X}",
284                (rgb.color.red * 255.).round() as u32,
285                (rgb.color.green * 255.).round() as u32,
286                (rgb.color.blue * 255.).round() as u32,
287                (self.alpha * 255.).round() as u32
288            );
289        }
290
291        format!(
292            "#{:02X}{:02X}{:02X}",
293            (rgb.color.red * 255.).round() as u32,
294            (rgb.color.green * 255.).round() as u32,
295            (rgb.color.blue * 255.).round() as u32
296        )
297    }
298
299    fn parse_hex(hex: &str) -> Result<Self> {
300        let hex = hex.trim_start_matches('#');
301        let len = hex.len();
302        if len != 6 && len != 8 {
303            return Err(anyhow::anyhow!("invalid hex color"));
304        }
305
306        let r = u8::from_str_radix(&hex[0..2], 16)? as f32 / 255.;
307        let g = u8::from_str_radix(&hex[2..4], 16)? as f32 / 255.;
308        let b = u8::from_str_radix(&hex[4..6], 16)? as f32 / 255.;
309        let a = if len == 8 {
310            u8::from_str_radix(&hex[6..8], 16)? as f32 / 255.
311        } else {
312            1.
313        };
314
315        let v = gpui::Rgba::new(r, g, b, a);
316        let color: Hsla = v.into_color();
317        Ok(color)
318    }
319
320    fn hue(&self, hue: f32) -> Self {
321        hsla(
322            hue.clamp(0., 1.),
323            self.color.saturation,
324            self.color.lightness,
325            self.alpha,
326        )
327    }
328
329    fn saturation(&self, saturation: f32) -> Self {
330        hsla(
331            hue(*self),
332            saturation.clamp(0., 1.),
333            self.color.lightness,
334            self.alpha,
335        )
336    }
337
338    fn lightness(&self, lightness: f32) -> Self {
339        hsla(
340            hue(*self),
341            self.color.saturation,
342            lightness.clamp(0., 1.),
343            self.alpha,
344        )
345    }
346}
347
348#[inline]
349fn hue(color: Hsla) -> f32 {
350    color.color.hue.into_degrees().rem_euclid(360.) / 360.
351}
352
353pub(crate) static DEFAULT_COLORS: once_cell::sync::Lazy<ShadcnColors> =
354    once_cell::sync::Lazy::new(|| {
355        serde_json::from_str(include_str!("./default-colors.json"))
356            .expect("failed to parse default-colors.json")
357    });
358
359type ColorScales = HashMap<usize, ShadcnColor>;
360
361mod color_scales {
362    use std::collections::HashMap;
363
364    use super::{ColorScales, ShadcnColor};
365
366    use serde::de::{Deserialize, Deserializer};
367
368    pub fn deserialize<'de, D>(deserializer: D) -> Result<ColorScales, D::Error>
369    where
370        D: Deserializer<'de>,
371    {
372        let mut map = HashMap::new();
373        for color in Vec::<ShadcnColor>::deserialize(deserializer)? {
374            map.insert(color.scale, color);
375        }
376        Ok(map)
377    }
378}
379
380/// Enum representing the available color names.
381#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
382pub enum ColorName {
383    White,
384    Black,
385    Neutral,
386    Gray,
387    Red,
388    Orange,
389    Amber,
390    Yellow,
391    Lime,
392    Green,
393    Emerald,
394    Teal,
395    Cyan,
396    Sky,
397    Blue,
398    Indigo,
399    Violet,
400    Purple,
401    Fuchsia,
402    Pink,
403    Rose,
404}
405
406impl Display for ColorName {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        write!(f, "{:?}", self)
409    }
410}
411
412// Strict color name parser.
413impl TryFrom<&str> for ColorName {
414    type Error = anyhow::Error;
415    fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
416        match value.to_lowercase().as_str() {
417            "white" => Ok(ColorName::White),
418            "black" => Ok(ColorName::Black),
419            "neutral" => Ok(ColorName::Neutral),
420            "gray" => Ok(ColorName::Gray),
421            "red" => Ok(ColorName::Red),
422            "orange" => Ok(ColorName::Orange),
423            "amber" => Ok(ColorName::Amber),
424            "yellow" => Ok(ColorName::Yellow),
425            "lime" => Ok(ColorName::Lime),
426            "green" => Ok(ColorName::Green),
427            "emerald" => Ok(ColorName::Emerald),
428            "teal" => Ok(ColorName::Teal),
429            "cyan" => Ok(ColorName::Cyan),
430            "sky" => Ok(ColorName::Sky),
431            "blue" => Ok(ColorName::Blue),
432            "indigo" => Ok(ColorName::Indigo),
433            "violet" => Ok(ColorName::Violet),
434            "purple" => Ok(ColorName::Purple),
435            "fuchsia" => Ok(ColorName::Fuchsia),
436            "pink" => Ok(ColorName::Pink),
437            "rose" => Ok(ColorName::Rose),
438            _ => Err(anyhow::anyhow!("Invalid color name")),
439        }
440    }
441}
442
443impl TryFrom<SharedString> for ColorName {
444    type Error = anyhow::Error;
445    fn try_from(value: SharedString) -> std::result::Result<Self, Self::Error> {
446        value.as_ref().try_into()
447    }
448}
449
450impl ColorName {
451    /// Returns all available color names.
452    pub fn all() -> [Self; 19] {
453        [
454            ColorName::Neutral,
455            ColorName::Gray,
456            ColorName::Red,
457            ColorName::Orange,
458            ColorName::Amber,
459            ColorName::Yellow,
460            ColorName::Lime,
461            ColorName::Green,
462            ColorName::Emerald,
463            ColorName::Teal,
464            ColorName::Cyan,
465            ColorName::Sky,
466            ColorName::Blue,
467            ColorName::Indigo,
468            ColorName::Violet,
469            ColorName::Purple,
470            ColorName::Fuchsia,
471            ColorName::Pink,
472            ColorName::Rose,
473        ]
474    }
475
476    /// Returns the color for the given scale.
477    ///
478    /// The `scale` is any of `[50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]`
479    /// falls back to 500 if out of range.
480    pub fn scale(&self, scale: usize) -> Hsla {
481        if self == &ColorName::White {
482            return DEFAULT_COLORS.white.hsla;
483        }
484        if self == &ColorName::Black {
485            return DEFAULT_COLORS.black.hsla;
486        }
487
488        let colors = match self {
489            ColorName::Neutral => &DEFAULT_COLORS.neutral,
490            ColorName::Gray => &DEFAULT_COLORS.gray,
491            ColorName::Red => &DEFAULT_COLORS.red,
492            ColorName::Orange => &DEFAULT_COLORS.orange,
493            ColorName::Amber => &DEFAULT_COLORS.amber,
494            ColorName::Yellow => &DEFAULT_COLORS.yellow,
495            ColorName::Lime => &DEFAULT_COLORS.lime,
496            ColorName::Green => &DEFAULT_COLORS.green,
497            ColorName::Emerald => &DEFAULT_COLORS.emerald,
498            ColorName::Teal => &DEFAULT_COLORS.teal,
499            ColorName::Cyan => &DEFAULT_COLORS.cyan,
500            ColorName::Sky => &DEFAULT_COLORS.sky,
501            ColorName::Blue => &DEFAULT_COLORS.blue,
502            ColorName::Indigo => &DEFAULT_COLORS.indigo,
503            ColorName::Violet => &DEFAULT_COLORS.violet,
504            ColorName::Purple => &DEFAULT_COLORS.purple,
505            ColorName::Fuchsia => &DEFAULT_COLORS.fuchsia,
506            ColorName::Pink => &DEFAULT_COLORS.pink,
507            ColorName::Rose => &DEFAULT_COLORS.rose,
508            _ => unreachable!(),
509        };
510
511        if let Some(color) = colors.get(&scale) {
512            color.hsla
513        } else {
514            colors.get(&500).unwrap().hsla
515        }
516    }
517}
518
519#[derive(Debug, Clone, PartialEq, serde::Deserialize)]
520pub(crate) struct ShadcnColors {
521    pub(crate) black: ShadcnColor,
522    pub(crate) white: ShadcnColor,
523    #[serde(with = "color_scales")]
524    pub(crate) slate: ColorScales,
525    #[serde(with = "color_scales")]
526    pub(crate) gray: ColorScales,
527    #[serde(with = "color_scales")]
528    pub(crate) zinc: ColorScales,
529    #[serde(with = "color_scales")]
530    pub(crate) neutral: ColorScales,
531    #[serde(with = "color_scales")]
532    pub(crate) stone: ColorScales,
533    #[serde(with = "color_scales")]
534    pub(crate) red: ColorScales,
535    #[serde(with = "color_scales")]
536    pub(crate) orange: ColorScales,
537    #[serde(with = "color_scales")]
538    pub(crate) amber: ColorScales,
539    #[serde(with = "color_scales")]
540    pub(crate) yellow: ColorScales,
541    #[serde(with = "color_scales")]
542    pub(crate) lime: ColorScales,
543    #[serde(with = "color_scales")]
544    pub(crate) green: ColorScales,
545    #[serde(with = "color_scales")]
546    pub(crate) emerald: ColorScales,
547    #[serde(with = "color_scales")]
548    pub(crate) teal: ColorScales,
549    #[serde(with = "color_scales")]
550    pub(crate) cyan: ColorScales,
551    #[serde(with = "color_scales")]
552    pub(crate) sky: ColorScales,
553    #[serde(with = "color_scales")]
554    pub(crate) blue: ColorScales,
555    #[serde(with = "color_scales")]
556    pub(crate) indigo: ColorScales,
557    #[serde(with = "color_scales")]
558    pub(crate) violet: ColorScales,
559    #[serde(with = "color_scales")]
560    pub(crate) purple: ColorScales,
561    #[serde(with = "color_scales")]
562    pub(crate) fuchsia: ColorScales,
563    #[serde(with = "color_scales")]
564    pub(crate) pink: ColorScales,
565    #[serde(with = "color_scales")]
566    pub(crate) rose: ColorScales,
567}
568
569#[derive(Debug, Clone, Copy, PartialEq, serde::Deserialize)]
570pub(crate) struct ShadcnColor {
571    #[serde(default)]
572    pub(crate) scale: usize,
573    #[serde(deserialize_with = "from_hsl_channel", alias = "hslChannel")]
574    pub(crate) hsla: Hsla,
575}
576
577/// Deserialize Hsla from a string in the format "210 40% 98%"
578fn from_hsl_channel<'de, D>(deserializer: D) -> Result<Hsla, D::Error>
579where
580    D: Deserializer<'de>,
581{
582    let s: String = Deserialize::deserialize(deserializer).unwrap();
583
584    let mut parts = s.split_whitespace();
585    if parts.clone().count() != 3 {
586        return Err(D::Error::custom(
587            "expected hslChannel has 3 parts, e.g: '210 40% 98%'",
588        ));
589    }
590
591    fn parse_number(s: &str) -> f32 {
592        s.trim_end_matches('%')
593            .parse()
594            .expect("failed to parse number")
595    }
596
597    let (h, s, l) = (
598        parse_number(parts.next().unwrap()),
599        parse_number(parts.next().unwrap()),
600        parse_number(parts.next().unwrap()),
601    );
602
603    Ok(hsl(h, s, l))
604}
605
606macro_rules! color_method {
607    ($color:tt, $scale:tt) => {
608        paste::paste! {
609            #[inline]
610            #[allow(unused)]
611            pub fn [<$color _ $scale>]() -> Hsla {
612                if let Some(color) = DEFAULT_COLORS.$color.get(&($scale as usize)) {
613                    return color.hsla;
614                }
615
616                black()
617            }
618        }
619    };
620}
621
622macro_rules! color_methods {
623    ($color:tt) => {
624        paste::paste! {
625            /// Get color by scale number.
626            ///
627            /// The possible scale numbers are:
628            /// 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950
629            ///
630            /// If the scale number is not found, it will return black color.
631            #[inline]
632            pub fn [<$color>](scale: usize) -> Hsla {
633                if let Some(color) = DEFAULT_COLORS.$color.get(&scale) {
634                    return color.hsla;
635                }
636
637                black()
638            }
639        }
640
641        color_method!($color, 50);
642        color_method!($color, 100);
643        color_method!($color, 200);
644        color_method!($color, 300);
645        color_method!($color, 400);
646        color_method!($color, 500);
647        color_method!($color, 600);
648        color_method!($color, 700);
649        color_method!($color, 800);
650        color_method!($color, 900);
651        color_method!($color, 950);
652    };
653}
654
655pub fn black() -> Hsla {
656    DEFAULT_COLORS.black.hsla
657}
658
659pub fn white() -> Hsla {
660    DEFAULT_COLORS.white.hsla
661}
662
663color_methods!(slate);
664color_methods!(gray);
665color_methods!(zinc);
666color_methods!(neutral);
667color_methods!(stone);
668color_methods!(red);
669color_methods!(orange);
670color_methods!(amber);
671color_methods!(yellow);
672color_methods!(lime);
673color_methods!(green);
674color_methods!(emerald);
675color_methods!(teal);
676color_methods!(cyan);
677color_methods!(sky);
678color_methods!(blue);
679color_methods!(indigo);
680color_methods!(violet);
681color_methods!(purple);
682color_methods!(fuchsia);
683color_methods!(pink);
684color_methods!(rose);
685
686/// Try to parse the color, HEX or [Tailwind Color](https://tailwindcss.com/docs/colors) expression.
687///
688/// # Parameter `color` should be one string value listed below:
689///
690/// - `#RRGGBB` - The HEX color string.
691/// - `#RRGGBBAA` - The HEX color string with alpha.
692///
693/// Or the Tailwind Color format:
694///
695/// - `name` - The color name `black`, `white`, or any other defined in `crate::color`.
696/// - `name-scale` - The color name with scale.
697/// - `name/opacity` - The color name with opacity, `opacity` should be an integer between 0 and 100.
698/// - `name-scale/opacity` - The color name with scale and opacity.
699///
700pub fn try_parse_color(color: &str) -> Result<Hsla> {
701    if color.starts_with("#") {
702        return Hsla::parse_hex(color);
703    }
704
705    let mut name = String::new();
706    let mut scale = None;
707    let mut opacity = None;
708    // 0: name, 1: scale, 2: opacity
709    let mut state = 0;
710    let mut part = String::new();
711
712    for c in color.chars() {
713        match c {
714            '-' if state == 0 => {
715                name = std::mem::take(&mut part);
716                state = 1;
717            }
718            '/' if state <= 1 => {
719                if state == 0 {
720                    name = std::mem::take(&mut part);
721                } else if state == 1 {
722                    scale = part.parse::<usize>().ok();
723                    part.clear();
724                }
725                state = 2;
726            }
727            _ => part.push(c),
728        }
729    }
730
731    match state {
732        0 => name = part,
733        1 => scale = part.parse::<usize>().ok(),
734        2 => opacity = part.parse::<f32>().ok(),
735        _ => {}
736    }
737
738    if name.is_empty() {
739        return Err(anyhow!("Empty color name"));
740    }
741
742    let mut hsla = match name.as_str() {
743        "black" => Ok::<Hsla, Error>(crate::black()),
744        "white" => Ok(crate::white()),
745        _ => {
746            let color_name = ColorName::try_from(name.as_str())?;
747            if let Some(scale) = scale {
748                Ok(color_name.scale(scale))
749            } else {
750                Ok(color_name.scale(500))
751            }
752        }
753    }?;
754
755    if let Some(opacity) = opacity {
756        if opacity > 100. {
757            return Err(anyhow!("Invalid color opacity"));
758        }
759        hsla = hsla.opacity(opacity / 100.);
760    }
761
762    Ok(hsla)
763}
764
765/// Deserialize theme colors from the string syntax accepted by
766/// [`try_parse_color`]. Palette's structural `Hsla` deserializer cannot read
767/// the hex and named colors used by GPUI theme files.
768pub(crate) fn deserialize_optional_hsla<'de, D>(deserializer: D) -> Result<Option<Hsla>, D::Error>
769where
770    D: Deserializer<'de>,
771{
772    Option::<String>::deserialize(deserializer)?.map_or(Ok(None), |value| {
773        try_parse_color(&value).map(Some).map_err(serde::de::Error::custom)
774    })
775}
776
777/// Try to parse a theme background value.
778///
779/// Supports all values accepted by [`try_parse_color`] and CSS-style two-stop
780/// `linear-gradient(...)` values.
781pub fn try_parse_background(background: &str) -> Result<Background> {
782    if let Ok(color) = try_parse_color(background) {
783        return Ok(color.into());
784    }
785
786    let gradient = parse_linear_gradient(background)?;
787    Ok(linear_gradient(gradient.angle, gradient.from, gradient.to))
788}
789
790/// Parse a background, clamping every color stop's alpha to at most `max`.
791///
792/// Unlike [`Background::opacity`], which scales all stops by a single factor,
793/// this caps each gradient stop independently, so a bright `to` stop (or a
794/// transparent `from` stop) can never push the rendered highlight past `max`.
795pub(crate) fn try_parse_background_clamped(background: &str, max: f32) -> Result<Background> {
796    if let Ok(color) = try_parse_color(background) {
797        let mut color = color;
798        color.alpha = color.alpha.min(max);
799        return Ok(color.into());
800    }
801
802    let gradient = parse_linear_gradient(background)?;
803    let clamp = |stop: LinearColorStop| {
804        let mut color: Hsla = stop.color.into();
805        color.alpha = color.alpha.min(max);
806        linear_color_stop(color, stop.percentage)
807    };
808    Ok(linear_gradient(
809        gradient.angle,
810        clamp(gradient.from),
811        clamp(gradient.to),
812    ))
813}
814
815pub(crate) fn try_parse_theme_color(color: &str) -> Result<Hsla> {
816    if let Ok(color) = try_parse_color(color) {
817        return Ok(color);
818    }
819
820    Ok(parse_linear_gradient(color)?.from.color.into())
821}
822
823struct ParsedLinearGradient {
824    angle: f32,
825    from: LinearColorStop,
826    to: LinearColorStop,
827}
828
829fn parse_linear_gradient(background: &str) -> Result<ParsedLinearGradient> {
830    const PREFIX: &str = "linear-gradient(";
831
832    let background = background.trim();
833    if !background.to_ascii_lowercase().starts_with(PREFIX) || !background.ends_with(')') {
834        return Err(anyhow!("Unsupported background value"));
835    }
836
837    let inner = &background[PREFIX.len()..background.len() - 1];
838    let parts = split_top_level_commas(inner);
839    let (angle, from, to) = match parts.as_slice() {
840        [from, to] => (
841            180.,
842            parse_linear_color_stop(from, 0.)?,
843            parse_linear_color_stop(to, 1.)?,
844        ),
845        [angle, from, to] => (
846            parse_linear_gradient_angle(angle)?,
847            parse_linear_color_stop(from, 0.)?,
848            parse_linear_color_stop(to, 1.)?,
849        ),
850        _ => {
851            return Err(anyhow!(
852                "Expected linear-gradient with two color stops, e.g. linear-gradient(135deg, #000, #fff)"
853            ));
854        }
855    };
856
857    Ok(ParsedLinearGradient { angle, from, to })
858}
859
860fn split_top_level_commas(value: &str) -> Vec<String> {
861    let mut parts = Vec::new();
862    let mut depth = 0usize;
863    let mut start = 0usize;
864
865    for (ix, ch) in value.char_indices() {
866        match ch {
867            '(' => depth += 1,
868            ')' => depth = depth.saturating_sub(1),
869            ',' if depth == 0 => {
870                parts.push(value[start..ix].trim().to_string());
871                start = ix + ch.len_utf8();
872            }
873            _ => {}
874        }
875    }
876
877    parts.push(value[start..].trim().to_string());
878    parts
879}
880
881fn parse_linear_gradient_angle(angle: &str) -> Result<f32> {
882    let angle = angle.trim().to_ascii_lowercase();
883
884    if let Some(degrees) = angle.strip_suffix("deg") {
885        return Ok(degrees.trim().parse::<f32>()?.rem_euclid(360.));
886    }
887
888    if let Some(direction) = angle.strip_prefix("to ") {
889        return parse_linear_gradient_direction(direction);
890    }
891
892    Err(anyhow!("Unsupported linear-gradient angle: {angle}"))
893}
894
895fn parse_linear_gradient_direction(direction: &str) -> Result<f32> {
896    let mut top = false;
897    let mut right = false;
898    let mut bottom = false;
899    let mut left = false;
900
901    for part in direction.split_whitespace() {
902        match part {
903            "top" => top = true,
904            "right" => right = true,
905            "bottom" => bottom = true,
906            "left" => left = true,
907            _ => {
908                return Err(anyhow!(
909                    "Unsupported linear-gradient direction: {direction}"
910                ));
911            }
912        }
913    }
914
915    match (top, right, bottom, left) {
916        (true, false, false, false) => Ok(0.),
917        (false, true, false, false) => Ok(90.),
918        (false, false, true, false) => Ok(180.),
919        (false, false, false, true) => Ok(270.),
920        (true, true, false, false) => Ok(45.),
921        (false, true, true, false) => Ok(135.),
922        (false, false, true, true) => Ok(225.),
923        (true, false, false, true) => Ok(315.),
924        _ => Err(anyhow!(
925            "Unsupported linear-gradient direction: {direction}"
926        )),
927    }
928}
929
930fn parse_linear_color_stop(stop: &str, default_percentage: f32) -> Result<LinearColorStop> {
931    let stop = stop.trim();
932    let mut parts = stop.split_whitespace().collect::<Vec<_>>();
933    let percentage = parts
934        .last()
935        .and_then(|part| part.strip_suffix('%'))
936        .map(|part| part.parse::<f32>().map(|value| value / 100.))
937        .transpose()?
938        .unwrap_or(default_percentage);
939
940    if stop.ends_with('%') {
941        parts.pop();
942    }
943
944    let color = parts.join(" ");
945    if color.is_empty() {
946        return Err(anyhow!("Expected color in linear-gradient color stop"));
947    }
948
949    Ok(linear_color_stop(
950        try_parse_color(&color)?,
951        percentage.clamp(0., 1.),
952    ))
953}
954
955#[cfg(test)]
956mod tests {
957    use gpui::{rgb, rgba};
958
959    use super::*;
960
961    #[test]
962    fn test_default_colors() {
963        assert_eq!(white(), hsl(0.0, 0.0, 100.0));
964        assert_eq!(black(), hsl(0.0, 0.0, 0.0));
965
966        assert_eq!(slate_50(), hsl(210.0, 40.0, 98.0));
967        assert_eq!(slate_100(), hsl(210.0, 40.0, 96.1));
968        assert_eq!(slate_900(), hsl(222.2, 47.4, 11.2));
969
970        assert_eq!(red_50(), hsl(0.0, 85.7, 97.3));
971        assert_eq!(yellow_100(), hsl(54.9, 96.7, 88.0));
972        assert_eq!(green_200(), hsl(141.0, 78.9, 85.1));
973        assert_eq!(cyan_300(), hsl(187.0, 92.4, 69.0));
974        assert_eq!(blue_400(), hsl(213.1, 93.9, 67.8));
975        assert_eq!(indigo_500(), hsl(238.7, 83.5, 66.7));
976    }
977
978    #[test]
979    fn test_to_hex_string() {
980        let color: Hsla = rgb(0xf8fafc).into_color();
981        assert_eq!(color.to_hex(), "#F8FAFC");
982
983        let color: Hsla = rgb(0xfef2f2).into_color();
984        assert_eq!(color.to_hex(), "#FEF2F2");
985
986        let color: Hsla = rgba(0x0413fcaa).into_color();
987        assert_eq!(color.to_hex(), "#0413FCAA");
988    }
989
990    #[test]
991    fn test_from_hex_string() {
992        let color: Hsla = Hsla::parse_hex("#F8FAFC").unwrap();
993        assert_eq!(color, rgb(0xf8fafc).into_color());
994
995        let color: Hsla = Hsla::parse_hex("#FEF2F2").unwrap();
996        assert_eq!(color, rgb(0xfef2f2).into_color());
997
998        let color: Hsla = Hsla::parse_hex("#0413FCAA").unwrap();
999        assert_eq!(color, rgba(0x0413fcaa).into_color());
1000    }
1001
1002    #[test]
1003    fn test_lighten() {
1004        let color = super::hsl(240.0, 5.0, 30.0);
1005        let color = color.lighten(0.5);
1006        assert_eq!(color.color.lightness, 0.45000002);
1007        let color = color.lighten(0.5);
1008        assert_eq!(color.color.lightness, 0.675);
1009        let color = color.lighten(0.1);
1010        assert_eq!(color.color.lightness, 0.7425);
1011    }
1012
1013    #[test]
1014    fn test_darken() {
1015        let color = super::hsl(240.0, 5.0, 96.0);
1016        let color = color.darken(0.5);
1017        assert_eq!(color.color.lightness, 0.48);
1018        let color = color.darken(0.5);
1019        assert_eq!(color.color.lightness, 0.24);
1020    }
1021
1022    #[test]
1023    fn test_mix() {
1024        let red = Hsla::parse_hex("#FF0000").unwrap();
1025        let blue = Hsla::parse_hex("#0000FF").unwrap();
1026        let green = Hsla::parse_hex("#00FF00").unwrap();
1027        let yellow = Hsla::parse_hex("#FFFF00").unwrap();
1028
1029        assert_eq!(red.mix(blue, 0.5).to_hex(), "#FF00FF");
1030        assert_eq!(green.mix(red, 0.5).to_hex(), "#FFFF00");
1031        assert_eq!(blue.mix(yellow, 0.2).to_hex(), "#0099FF");
1032    }
1033
1034    #[test]
1035    fn test_mix_oklab() {
1036        let red = Hsla::parse_hex("#FF0000").unwrap();
1037        let blue = Hsla::parse_hex("#0000FF").unwrap();
1038        let transparent = gpui::hsla(0., 0., 0., 0.);
1039
1040        // Test mixing red with transparent (similar to CSS color-mix example)
1041        // color-mix(in oklab, red 20%, transparent) should give red with 20% opacity
1042        let result = red.mix_oklab(transparent, 0.2);
1043        assert!((result.alpha - 0.2).abs() < 0.01); // Alpha should be 20%
1044
1045        // The color should remain red (hue should be preserved)
1046        let rgb_result: gpui::Rgba = result.into_color();
1047        let rgb_red: gpui::Rgba = red.into_color();
1048        // Allow some tolerance due to color space conversions
1049        assert!(
1050            (rgb_result.color.red - rgb_red.color.red).abs() < 0.05,
1051            "Red channel should be preserved"
1052        );
1053        assert!(
1054            rgb_result.color.green < 0.05,
1055            "Green channel should be near 0"
1056        );
1057        assert!(
1058            rgb_result.color.blue < 0.05,
1059            "Blue channel should be near 0"
1060        );
1061
1062        // Test basic color mixing in Oklab space
1063        let purple = red.mix_oklab(blue, 0.5);
1064        // Oklab mixing should produce different results than HSL mixing
1065        let purple_hsl = red.mix(blue, 0.5);
1066        assert_ne!(purple.to_hex(), purple_hsl.to_hex());
1067
1068        // Test factor boundaries (allowing small floating point errors)
1069        let result_0 = red.mix_oklab(blue, 0.0);
1070        let result_1 = red.mix_oklab(blue, 1.0);
1071
1072        // Check that result is close to expected (within 1 color unit per channel)
1073        let rgb_0: gpui::Rgba = result_0.into_color();
1074        let rgb_blue: gpui::Rgba = blue.into_color();
1075        assert!((rgb_0.color.red - rgb_blue.color.red).abs() < 0.01);
1076        assert!((rgb_0.color.green - rgb_blue.color.green).abs() < 0.01);
1077        assert!((rgb_0.color.blue - rgb_blue.color.blue).abs() < 0.01);
1078
1079        let rgb_1: gpui::Rgba = result_1.into_color();
1080        let rgb_red: gpui::Rgba = red.into_color();
1081        assert!((rgb_1.color.red - rgb_red.color.red).abs() < 0.01);
1082        assert!((rgb_1.color.green - rgb_red.color.green).abs() < 0.01);
1083        assert!((rgb_1.color.blue - rgb_red.color.blue).abs() < 0.01);
1084    }
1085
1086    #[test]
1087    fn test_color_name() {
1088        assert_eq!(ColorName::Purple.to_string(), "Purple");
1089        assert_eq!(format!("{}", ColorName::Green), "Green");
1090        assert_eq!(format!("{:?}", ColorName::Yellow), "Yellow");
1091
1092        let color = ColorName::Green;
1093        assert_eq!(color.scale(500).to_hex(), "#22C55E");
1094        assert_eq!(color.scale(1500).to_hex(), "#22C55E");
1095
1096        for name in ColorName::all().iter() {
1097            let name1: ColorName = name.to_string().as_str().try_into().unwrap();
1098            assert_eq!(name1, *name);
1099        }
1100    }
1101
1102    #[test]
1103    fn test_h_s_l() {
1104        let color = hsl(260., 94., 80.);
1105        assert_eq!(color.hue(200. / 360.), hsl(200., 94., 80.));
1106        assert_eq!(color.saturation(74. / 100.), hsl(260., 74., 80.));
1107        assert_eq!(color.lightness(74. / 100.), hsl(260., 94., 74.));
1108    }
1109
1110    #[test]
1111    fn test_try_parse_color() {
1112        assert_eq!(
1113            try_parse_color("#F2F200").ok(),
1114            Some(hsla(0.16666667, 1., 0.4745098, 1.0))
1115        );
1116        assert_eq!(
1117            try_parse_color("#00f21888").ok(),
1118            Some(hsla(0.34986225, 1.0, 0.4745098, 0.53333336))
1119        );
1120        assert_eq!(try_parse_color("black").ok(), Some(crate::black()));
1121        assert_eq!(try_parse_color("white-800").ok(), Some(crate::white()));
1122        assert_eq!(try_parse_color("red").ok(), Some(crate::red_500()));
1123        assert_eq!(try_parse_color("blue-600").ok(), Some(crate::blue_600()));
1124        assert_eq!(
1125            try_parse_color("pink/33").ok(),
1126            Some(crate::pink_500().opacity(0.33))
1127        );
1128        assert_eq!(
1129            try_parse_color("orange-300/66").ok(),
1130            Some(crate::orange_300().opacity(0.66))
1131        );
1132    }
1133
1134    #[test]
1135    fn test_try_parse_background_linear_gradient() {
1136        let from = try_parse_color("#4F46E5").unwrap();
1137        let to = try_parse_color("#06B6D4").unwrap();
1138
1139        assert_eq!(
1140            try_parse_background("linear-gradient(135deg, #4F46E5, #06B6D4)").unwrap(),
1141            gpui::linear_gradient(
1142                135.,
1143                gpui::linear_color_stop(from, 0.),
1144                gpui::linear_color_stop(to, 1.)
1145            )
1146        );
1147    }
1148
1149    #[test]
1150    fn test_try_parse_background_linear_gradient_direction_and_stops() {
1151        assert_eq!(
1152            try_parse_background("linear-gradient(to right, red-500 25%, blue-600 75%)").unwrap(),
1153            gpui::linear_gradient(
1154                90.,
1155                gpui::linear_color_stop(crate::red_500(), 0.25),
1156                gpui::linear_color_stop(crate::blue_600(), 0.75)
1157            )
1158        );
1159    }
1160}