1#![allow(dead_code)]
2
3use anyhow::bail;
4use serde::de::{self, Deserialize, Deserializer, Visitor};
5use std::fmt;
6
7pub fn rgb<C: From<Rgba>>(hex: u32) -> C {
8 let r = ((hex >> 16) & 0xFF) as f32 / 255.0;
9 let g = ((hex >> 8) & 0xFF) as f32 / 255.0;
10 let b = (hex & 0xFF) as f32 / 255.0;
11 Rgba { r, g, b, a: 1.0 }.into()
12}
13
14pub fn rgba(hex: u32) -> Rgba {
15 let r = ((hex >> 24) & 0xFF) as f32 / 255.0;
16 let g = ((hex >> 16) & 0xFF) as f32 / 255.0;
17 let b = ((hex >> 8) & 0xFF) as f32 / 255.0;
18 let a = (hex & 0xFF) as f32 / 255.0;
19 Rgba { r, g, b, a }
20}
21
22#[derive(PartialEq, Clone, Copy, Default)]
23pub struct Rgba {
24 pub r: f32,
25 pub g: f32,
26 pub b: f32,
27 pub a: f32,
28}
29
30impl fmt::Debug for Rgba {
31 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32 write!(f, "rgba({:#010x})", u32::from(*self))
33 }
34}
35
36impl Rgba {
37 pub fn blend(&self, other: Rgba) -> Self {
38 if other.a >= 1.0 {
39 return other;
40 } else if other.a <= 0.0 {
41 return *self;
42 } else {
43 return Rgba {
44 r: (self.r * (1.0 - other.a)) + (other.r * other.a),
45 g: (self.g * (1.0 - other.a)) + (other.g * other.a),
46 b: (self.b * (1.0 - other.a)) + (other.b * other.a),
47 a: self.a,
48 };
49 }
50 }
51}
52
53impl From<Rgba> for u32 {
54 fn from(rgba: Rgba) -> Self {
55 let r = (rgba.r * 255.0) as u32;
56 let g = (rgba.g * 255.0) as u32;
57 let b = (rgba.b * 255.0) as u32;
58 let a = (rgba.a * 255.0) as u32;
59 (r << 24) | (g << 16) | (b << 8) | a
60 }
61}
62
63struct RgbaVisitor;
64
65impl<'de> Visitor<'de> for RgbaVisitor {
66 type Value = Rgba;
67
68 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
69 formatter.write_str("a string in the format #rrggbb or #rrggbbaa")
70 }
71
72 fn visit_str<E: de::Error>(self, value: &str) -> Result<Rgba, E> {
73 Rgba::try_from(value).map_err(E::custom)
74 }
75}
76
77impl<'de> Deserialize<'de> for Rgba {
78 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
79 deserializer.deserialize_str(RgbaVisitor)
80 }
81}
82
83impl From<Hsla> for Rgba {
84 fn from(color: Hsla) -> Self {
85 let h = color.h;
86 let s = color.s;
87 let l = color.l;
88
89 let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
90 let x = c * (1.0 - ((h * 6.0) % 2.0 - 1.0).abs());
91 let m = l - c / 2.0;
92 let cm = c + m;
93 let xm = x + m;
94
95 let (r, g, b) = match (h * 6.0).floor() as i32 {
96 0 | 6 => (cm, xm, m),
97 1 => (xm, cm, m),
98 2 => (m, cm, xm),
99 3 => (m, xm, cm),
100 4 => (xm, m, cm),
101 _ => (cm, m, xm),
102 };
103
104 Rgba {
105 r,
106 g,
107 b,
108 a: color.a,
109 }
110 }
111}
112
113impl TryFrom<&'_ str> for Rgba {
114 type Error = anyhow::Error;
115
116 fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
117 const RGB: usize = "rgb".len();
118 const RGBA: usize = "rgba".len();
119 const RRGGBB: usize = "rrggbb".len();
120 const RRGGBBAA: usize = "rrggbbaa".len();
121
122 const EXPECTED_FORMATS: &'static str = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa";
123
124 let Some(("", hex)) = value.trim().split_once('#') else {
125 bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}");
126 };
127
128 let (r, g, b, a) = match hex.len() {
129 RGB | RGBA => {
130 let r = u8::from_str_radix(&hex[0..1], 16)?;
131 let g = u8::from_str_radix(&hex[1..2], 16)?;
132 let b = u8::from_str_radix(&hex[2..3], 16)?;
133 let a = if hex.len() == RGBA {
134 u8::from_str_radix(&hex[3..4], 16)?
135 } else {
136 0xf
137 };
138
139 /// Duplicates a given hex digit.
140 /// E.g., `0xf` -> `0xff`.
141 const fn duplicate(value: u8) -> u8 {
142 value << 4 | value
143 }
144
145 (duplicate(r), duplicate(g), duplicate(b), duplicate(a))
146 }
147 RRGGBB | RRGGBBAA => {
148 let r = u8::from_str_radix(&hex[0..2], 16)?;
149 let g = u8::from_str_radix(&hex[2..4], 16)?;
150 let b = u8::from_str_radix(&hex[4..6], 16)?;
151 let a = if hex.len() == RRGGBBAA {
152 u8::from_str_radix(&hex[6..8], 16)?
153 } else {
154 0xff
155 };
156 (r, g, b, a)
157 }
158 _ => bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}"),
159 };
160
161 Ok(Rgba {
162 r: r as f32 / 255.,
163 g: g as f32 / 255.,
164 b: b as f32 / 255.,
165 a: a as f32 / 255.,
166 })
167 }
168}
169
170#[derive(Default, Copy, Clone, Debug, PartialEq)]
171#[repr(C)]
172pub struct Hsla {
173 pub h: f32,
174 pub s: f32,
175 pub l: f32,
176 pub a: f32,
177}
178
179impl Hsla {
180 pub fn to_rgb(self) -> Rgba {
181 self.into()
182 }
183}
184
185impl Eq for Hsla {}
186
187pub fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla {
188 Hsla {
189 h: h.clamp(0., 1.),
190 s: s.clamp(0., 1.),
191 l: l.clamp(0., 1.),
192 a: a.clamp(0., 1.),
193 }
194}
195
196pub fn black() -> Hsla {
197 Hsla {
198 h: 0.,
199 s: 0.,
200 l: 0.,
201 a: 1.,
202 }
203}
204
205pub fn transparent_black() -> Hsla {
206 Hsla {
207 h: 0.,
208 s: 0.,
209 l: 0.,
210 a: 0.,
211 }
212}
213
214pub fn white() -> Hsla {
215 Hsla {
216 h: 0.,
217 s: 0.,
218 l: 1.,
219 a: 1.,
220 }
221}
222
223pub fn red() -> Hsla {
224 Hsla {
225 h: 0.,
226 s: 1.,
227 l: 0.5,
228 a: 1.,
229 }
230}
231
232pub fn blue() -> Hsla {
233 Hsla {
234 h: 0.6,
235 s: 1.,
236 l: 0.5,
237 a: 1.,
238 }
239}
240
241impl Hsla {
242 /// Returns true if the HSLA color is fully transparent, false otherwise.
243 pub fn is_transparent(&self) -> bool {
244 self.a == 0.0
245 }
246
247 /// Blends `other` on top of `self` based on `other`'s alpha value. The resulting color is a combination of `self`'s and `other`'s colors.
248 ///
249 /// If `other`'s alpha value is 1.0 or greater, `other` color is fully opaque, thus `other` is returned as the output color.
250 /// If `other`'s alpha value is 0.0 or less, `other` color is fully transparent, thus `self` is returned as the output color.
251 /// Else, the output color is calculated as a blend of `self` and `other` based on their weighted alpha values.
252 ///
253 /// Assumptions:
254 /// - Alpha values are contained in the range [0, 1], with 1 as fully opaque and 0 as fully transparent.
255 /// - The relative contributions of `self` and `other` is based on `self`'s alpha value (`self.a`) and `other`'s alpha value (`other.a`), `self` contributing `self.a * (1.0 - other.a)` and `other` contributing it's own alpha value.
256 /// - RGB color components are contained in the range [0, 1].
257 /// - If `self` and `other` colors are out of the valid range, the blend operation's output and behavior is undefined.
258 pub fn blend(self, other: Hsla) -> Hsla {
259 let alpha = other.a;
260
261 if alpha >= 1.0 {
262 return other;
263 } else if alpha <= 0.0 {
264 return self;
265 } else {
266 let converted_self = Rgba::from(self);
267 let converted_other = Rgba::from(other);
268 let blended_rgb = converted_self.blend(converted_other);
269 return Hsla::from(blended_rgb);
270 }
271 }
272
273 /// Fade out the color by a given factor. This factor should be between 0.0 and 1.0.
274 /// Where 0.0 will leave the color unchanged, and 1.0 will completely fade out the color.
275 pub fn fade_out(&mut self, factor: f32) {
276 self.a *= 1.0 - factor.clamp(0., 1.);
277 }
278}
279
280// impl From<Hsla> for Rgba {
281// fn from(value: Hsla) -> Self {
282// let h = value.h;
283// let s = value.s;
284// let l = value.l;
285
286// let c = (1 - |2L - 1|) X s
287// }
288// }
289
290impl From<Rgba> for Hsla {
291 fn from(color: Rgba) -> Self {
292 let r = color.r;
293 let g = color.g;
294 let b = color.b;
295
296 let max = r.max(g.max(b));
297 let min = r.min(g.min(b));
298 let delta = max - min;
299
300 let l = (max + min) / 2.0;
301 let s = if l == 0.0 || l == 1.0 {
302 0.0
303 } else if l < 0.5 {
304 delta / (2.0 * l)
305 } else {
306 delta / (2.0 - 2.0 * l)
307 };
308
309 let h = if delta == 0.0 {
310 0.0
311 } else if max == r {
312 ((g - b) / delta).rem_euclid(6.0) / 6.0
313 } else if max == g {
314 ((b - r) / delta + 2.0) / 6.0
315 } else {
316 ((r - g) / delta + 4.0) / 6.0
317 };
318
319 Hsla {
320 h,
321 s,
322 l,
323 a: color.a,
324 }
325 }
326}
327
328impl<'de> Deserialize<'de> for Hsla {
329 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
330 where
331 D: Deserializer<'de>,
332 {
333 // First, deserialize it into Rgba
334 let rgba = Rgba::deserialize(deserializer)?;
335
336 // Then, use the From<Rgba> for Hsla implementation to convert it
337 Ok(Hsla::from(rgba))
338 }
339}
340
341#[cfg(test)]
342mod tests {
343 use serde_json::json;
344
345 use super::*;
346
347 #[test]
348 fn test_deserialize_three_value_hex_to_rgba() {
349 let actual: Rgba = serde_json::from_value(json!("#f09")).unwrap();
350
351 assert_eq!(actual, rgba(0xff0099ff))
352 }
353
354 #[test]
355 fn test_deserialize_four_value_hex_to_rgba() {
356 let actual: Rgba = serde_json::from_value(json!("#f09f")).unwrap();
357
358 assert_eq!(actual, rgba(0xff0099ff))
359 }
360
361 #[test]
362 fn test_deserialize_six_value_hex_to_rgba() {
363 let actual: Rgba = serde_json::from_value(json!("#ff0099")).unwrap();
364
365 assert_eq!(actual, rgba(0xff0099ff))
366 }
367
368 #[test]
369 fn test_deserialize_eight_value_hex_to_rgba() {
370 let actual: Rgba = serde_json::from_value(json!("#ff0099ff")).unwrap();
371
372 assert_eq!(actual, rgba(0xff0099ff))
373 }
374
375 #[test]
376 fn test_deserialize_eight_value_hex_with_padding_to_rgba() {
377 let actual: Rgba = serde_json::from_value(json!(" #f5f5f5ff ")).unwrap();
378
379 assert_eq!(actual, rgba(0xf5f5f5ff))
380 }
381
382 #[test]
383 fn test_deserialize_eight_value_hex_with_mixed_case_to_rgba() {
384 let actual: Rgba = serde_json::from_value(json!("#DeAdbEeF")).unwrap();
385
386 assert_eq!(actual, rgba(0xdeadbeef))
387 }
388}