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