color.rs

  1#![allow(dead_code)]
  2
  3use serde::de::{self, Deserialize, Deserializer, Visitor};
  4use smallvec::SmallVec;
  5use std::fmt;
  6use std::{num::ParseIntError, ops::Range};
  7
  8pub fn rgb<C: From<Rgba>>(hex: u32) -> C {
  9    let r = ((hex >> 16) & 0xFF) as f32 / 255.0;
 10    let g = ((hex >> 8) & 0xFF) as f32 / 255.0;
 11    let b = (hex & 0xFF) as f32 / 255.0;
 12    Rgba { r, g, b, a: 1.0 }.into()
 13}
 14
 15#[derive(Clone, Copy, Default, Debug)]
 16pub struct Rgba {
 17    pub r: f32,
 18    pub g: f32,
 19    pub b: f32,
 20    pub a: f32,
 21}
 22
 23struct RgbaVisitor;
 24
 25impl<'de> Visitor<'de> for RgbaVisitor {
 26    type Value = Rgba;
 27
 28    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
 29        formatter.write_str("a string in the format #rrggbb or #rrggbbaa")
 30    }
 31
 32    fn visit_str<E: de::Error>(self, value: &str) -> Result<Rgba, E> {
 33        if value.len() == 7 || value.len() == 9 {
 34            let r = u8::from_str_radix(&value[1..3], 16).unwrap() as f32 / 255.0;
 35            let g = u8::from_str_radix(&value[3..5], 16).unwrap() as f32 / 255.0;
 36            let b = u8::from_str_radix(&value[5..7], 16).unwrap() as f32 / 255.0;
 37            let a = if value.len() == 9 {
 38                u8::from_str_radix(&value[7..9], 16).unwrap() as f32 / 255.0
 39            } else {
 40                1.0
 41            };
 42            Ok(Rgba { r, g, b, a })
 43        } else {
 44            Err(E::custom(
 45                "Bad format for RGBA. Expected #rrggbb or #rrggbbaa.",
 46            ))
 47        }
 48    }
 49}
 50
 51impl<'de> Deserialize<'de> for Rgba {
 52    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
 53        deserializer.deserialize_str(RgbaVisitor)
 54    }
 55}
 56
 57pub trait Lerp {
 58    fn lerp(&self, level: f32) -> Hsla;
 59}
 60
 61impl Lerp for Range<Hsla> {
 62    fn lerp(&self, level: f32) -> Hsla {
 63        let level = level.clamp(0., 1.);
 64        Hsla {
 65            h: self.start.h + (level * (self.end.h - self.start.h)),
 66            s: self.start.s + (level * (self.end.s - self.start.s)),
 67            l: self.start.l + (level * (self.end.l - self.start.l)),
 68            a: self.start.a + (level * (self.end.a - self.start.a)),
 69        }
 70    }
 71}
 72
 73impl From<gpui::color::Color> for Rgba {
 74    fn from(value: gpui::color::Color) -> Self {
 75        Self {
 76            r: value.0.r as f32 / 255.0,
 77            g: value.0.g as f32 / 255.0,
 78            b: value.0.b as f32 / 255.0,
 79            a: value.0.a as f32 / 255.0,
 80        }
 81    }
 82}
 83
 84impl From<Hsla> for Rgba {
 85    fn from(color: Hsla) -> Self {
 86        let h = color.h;
 87        let s = color.s;
 88        let l = color.l;
 89
 90        let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
 91        let x = c * (1.0 - ((h * 6.0) % 2.0 - 1.0).abs());
 92        let m = l - c / 2.0;
 93        let cm = c + m;
 94        let xm = x + m;
 95
 96        let (r, g, b) = match (h * 6.0).floor() as i32 {
 97            0 | 6 => (cm, xm, m),
 98            1 => (xm, cm, m),
 99            2 => (m, cm, xm),
100            3 => (m, xm, cm),
101            4 => (xm, m, cm),
102            _ => (cm, m, xm),
103        };
104
105        Rgba {
106            r,
107            g,
108            b,
109            a: color.a,
110        }
111    }
112}
113
114impl TryFrom<&'_ str> for Rgba {
115    type Error = ParseIntError;
116
117    fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
118        let r = u8::from_str_radix(&value[1..3], 16)? as f32 / 255.0;
119        let g = u8::from_str_radix(&value[3..5], 16)? as f32 / 255.0;
120        let b = u8::from_str_radix(&value[5..7], 16)? as f32 / 255.0;
121        let a = if value.len() > 7 {
122            u8::from_str_radix(&value[7..9], 16)? as f32 / 255.0
123        } else {
124            1.0
125        };
126
127        Ok(Rgba { r, g, b, a })
128    }
129}
130
131impl Into<gpui::color::Color> for Rgba {
132    fn into(self) -> gpui::color::Color {
133        gpui::color::rgba(self.r, self.g, self.b, self.a)
134    }
135}
136
137#[derive(Default, Copy, Clone, Debug, PartialEq)]
138pub struct Hsla {
139    pub h: f32,
140    pub s: f32,
141    pub l: f32,
142    pub a: f32,
143}
144
145pub fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla {
146    Hsla {
147        h: h.clamp(0., 1.),
148        s: s.clamp(0., 1.),
149        l: l.clamp(0., 1.),
150        a: a.clamp(0., 1.),
151    }
152}
153
154pub fn black() -> Hsla {
155    Hsla {
156        h: 0.,
157        s: 0.,
158        l: 0.,
159        a: 1.,
160    }
161}
162
163impl From<Rgba> for Hsla {
164    fn from(color: Rgba) -> Self {
165        let r = color.r;
166        let g = color.g;
167        let b = color.b;
168
169        let max = r.max(g.max(b));
170        let min = r.min(g.min(b));
171        let delta = max - min;
172
173        let l = (max + min) / 2.0;
174        let s = if l == 0.0 || l == 1.0 {
175            0.0
176        } else if l < 0.5 {
177            delta / (2.0 * l)
178        } else {
179            delta / (2.0 - 2.0 * l)
180        };
181
182        let h = if delta == 0.0 {
183            0.0
184        } else if max == r {
185            ((g - b) / delta).rem_euclid(6.0) / 6.0
186        } else if max == g {
187            ((b - r) / delta + 2.0) / 6.0
188        } else {
189            ((r - g) / delta + 4.0) / 6.0
190        };
191
192        Hsla {
193            h,
194            s,
195            l,
196            a: color.a,
197        }
198    }
199}
200
201impl Hsla {
202    /// Scales the saturation and lightness by the given values, clamping at 1.0.
203    pub fn scale_sl(mut self, s: f32, l: f32) -> Self {
204        self.s = (self.s * s).clamp(0., 1.);
205        self.l = (self.l * l).clamp(0., 1.);
206        self
207    }
208
209    /// Increases the saturation of the color by a certain amount, with a max
210    /// value of 1.0.
211    pub fn saturate(mut self, amount: f32) -> Self {
212        self.s += amount;
213        self.s = self.s.clamp(0.0, 1.0);
214        self
215    }
216
217    /// Decreases the saturation of the color by a certain amount, with a min
218    /// value of 0.0.
219    pub fn desaturate(mut self, amount: f32) -> Self {
220        self.s -= amount;
221        self.s = self.s.max(0.0);
222        if self.s < 0.0 {
223            self.s = 0.0;
224        }
225        self
226    }
227
228    /// Brightens the color by increasing the lightness by a certain amount,
229    /// with a max value of 1.0.
230    pub fn brighten(mut self, amount: f32) -> Self {
231        self.l += amount;
232        self.l = self.l.clamp(0.0, 1.0);
233        self
234    }
235
236    /// Darkens the color by decreasing the lightness by a certain amount,
237    /// with a max value of 0.0.
238    pub fn darken(mut self, amount: f32) -> Self {
239        self.l -= amount;
240        self.l = self.l.clamp(0.0, 1.0);
241        self
242    }
243}
244
245impl From<gpui::color::Color> for Hsla {
246    fn from(value: gpui::color::Color) -> Self {
247        Rgba::from(value).into()
248    }
249}
250
251impl Into<gpui::color::Color> for Hsla {
252    fn into(self) -> gpui::color::Color {
253        Rgba::from(self).into()
254    }
255}
256
257impl<'de> Deserialize<'de> for Hsla {
258    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
259    where
260        D: Deserializer<'de>,
261    {
262        // First, deserialize it into Rgba
263        let rgba = Rgba::deserialize(deserializer)?;
264
265        // Then, use the From<Rgba> for Hsla implementation to convert it
266        Ok(Hsla::from(rgba))
267    }
268}
269
270pub struct ColorScale {
271    colors: SmallVec<[Hsla; 2]>,
272    positions: SmallVec<[f32; 2]>,
273}
274
275pub fn scale<I, C>(colors: I) -> ColorScale
276where
277    I: IntoIterator<Item = C>,
278    C: Into<Hsla>,
279{
280    let mut scale = ColorScale {
281        colors: colors.into_iter().map(Into::into).collect(),
282        positions: SmallVec::new(),
283    };
284    let num_colors: f32 = scale.colors.len() as f32 - 1.0;
285    scale.positions = (0..scale.colors.len())
286        .map(|i| i as f32 / num_colors)
287        .collect();
288    scale
289}
290
291impl ColorScale {
292    fn at(&self, t: f32) -> Hsla {
293        // Ensure that the input is within [0.0, 1.0]
294        debug_assert!(
295            0.0 <= t && t <= 1.0,
296            "t value {} is out of range. Expected value in range 0.0 to 1.0",
297            t
298        );
299
300        let position = match self
301            .positions
302            .binary_search_by(|a| a.partial_cmp(&t).unwrap())
303        {
304            Ok(index) | Err(index) => index,
305        };
306        let lower_bound = position.saturating_sub(1);
307        let upper_bound = position.min(self.colors.len() - 1);
308        let lower_color = &self.colors[lower_bound];
309        let upper_color = &self.colors[upper_bound];
310
311        match upper_bound.checked_sub(lower_bound) {
312            Some(0) | None => *lower_color,
313            Some(_) => {
314                let interval_t = (t - self.positions[lower_bound])
315                    / (self.positions[upper_bound] - self.positions[lower_bound]);
316                let h = lower_color.h + interval_t * (upper_color.h - lower_color.h);
317                let s = lower_color.s + interval_t * (upper_color.s - lower_color.s);
318                let l = lower_color.l + interval_t * (upper_color.l - lower_color.l);
319                let a = lower_color.a + interval_t * (upper_color.a - lower_color.a);
320                Hsla { h, s, l, a }
321            }
322        }
323    }
324}