1use anyhow::{bail, Context};
2use serde::de::{self, Deserialize, Deserializer, Visitor};
3use std::{
4 fmt::{self, Display, Formatter},
5 hash::{Hash, Hasher},
6};
7
8/// Convert an RGB hex color code number to a color type
9pub fn rgb(hex: u32) -> Rgba {
10 let r = ((hex >> 16) & 0xFF) as f32 / 255.0;
11 let g = ((hex >> 8) & 0xFF) as f32 / 255.0;
12 let b = (hex & 0xFF) as f32 / 255.0;
13 Rgba { r, g, b, a: 1.0 }
14}
15
16/// Convert an RGBA hex color code number to [`Rgba`]
17pub fn rgba(hex: u32) -> Rgba {
18 let r = ((hex >> 24) & 0xFF) as f32 / 255.0;
19 let g = ((hex >> 16) & 0xFF) as f32 / 255.0;
20 let b = ((hex >> 8) & 0xFF) as f32 / 255.0;
21 let a = (hex & 0xFF) as f32 / 255.0;
22 Rgba { r, g, b, a }
23}
24
25/// Swap from RGBA with premultiplied alpha to BGRA
26pub(crate) fn swap_rgba_pa_to_bgra(color: &mut [u8]) {
27 color.swap(0, 2);
28 if color[3] > 0 {
29 let a = color[3] as f32 / 255.;
30 color[0] = (color[0] as f32 / a) as u8;
31 color[1] = (color[1] as f32 / a) as u8;
32 color[2] = (color[2] as f32 / a) as u8;
33 }
34}
35
36/// An RGBA color
37#[derive(PartialEq, Clone, Copy, Default)]
38pub struct Rgba {
39 /// The red component of the color, in the range 0.0 to 1.0
40 pub r: f32,
41 /// The green component of the color, in the range 0.0 to 1.0
42 pub g: f32,
43 /// The blue component of the color, in the range 0.0 to 1.0
44 pub b: f32,
45 /// The alpha component of the color, in the range 0.0 to 1.0
46 pub a: f32,
47}
48
49impl fmt::Debug for Rgba {
50 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 write!(f, "rgba({:#010x})", u32::from(*self))
52 }
53}
54
55impl Rgba {
56 /// Create a new [`Rgba`] color by blending this and another color together
57 pub fn blend(&self, other: Rgba) -> Self {
58 if other.a >= 1.0 {
59 other
60 } else if other.a <= 0.0 {
61 return *self;
62 } else {
63 return Rgba {
64 r: (self.r * (1.0 - other.a)) + (other.r * other.a),
65 g: (self.g * (1.0 - other.a)) + (other.g * other.a),
66 b: (self.b * (1.0 - other.a)) + (other.b * other.a),
67 a: self.a,
68 };
69 }
70 }
71}
72
73impl From<Rgba> for u32 {
74 fn from(rgba: Rgba) -> Self {
75 let r = (rgba.r * 255.0) as u32;
76 let g = (rgba.g * 255.0) as u32;
77 let b = (rgba.b * 255.0) as u32;
78 let a = (rgba.a * 255.0) as u32;
79 (r << 24) | (g << 16) | (b << 8) | a
80 }
81}
82
83struct RgbaVisitor;
84
85impl<'de> Visitor<'de> for RgbaVisitor {
86 type Value = Rgba;
87
88 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
89 formatter.write_str("a string in the format #rrggbb or #rrggbbaa")
90 }
91
92 fn visit_str<E: de::Error>(self, value: &str) -> Result<Rgba, E> {
93 Rgba::try_from(value).map_err(E::custom)
94 }
95}
96
97impl<'de> Deserialize<'de> for Rgba {
98 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
99 deserializer.deserialize_str(RgbaVisitor)
100 }
101}
102
103impl From<Hsla> for Rgba {
104 fn from(color: Hsla) -> Self {
105 let h = color.h;
106 let s = color.s;
107 let l = color.l;
108
109 let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
110 let x = c * (1.0 - ((h * 6.0) % 2.0 - 1.0).abs());
111 let m = l - c / 2.0;
112 let cm = c + m;
113 let xm = x + m;
114
115 let (r, g, b) = match (h * 6.0).floor() as i32 {
116 0 | 6 => (cm, xm, m),
117 1 => (xm, cm, m),
118 2 => (m, cm, xm),
119 3 => (m, xm, cm),
120 4 => (xm, m, cm),
121 _ => (cm, m, xm),
122 };
123
124 Rgba {
125 r,
126 g,
127 b,
128 a: color.a,
129 }
130 }
131}
132
133impl TryFrom<&'_ str> for Rgba {
134 type Error = anyhow::Error;
135
136 fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
137 const RGB: usize = "rgb".len();
138 const RGBA: usize = "rgba".len();
139 const RRGGBB: usize = "rrggbb".len();
140 const RRGGBBAA: usize = "rrggbbaa".len();
141
142 const EXPECTED_FORMATS: &str = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa";
143 const INVALID_UNICODE: &str = "invalid unicode characters in color";
144
145 let Some(("", hex)) = value.trim().split_once('#') else {
146 bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}");
147 };
148
149 let (r, g, b, a) = match hex.len() {
150 RGB | RGBA => {
151 let r = u8::from_str_radix(
152 hex.get(0..1).with_context(|| {
153 format!("{INVALID_UNICODE}: r component of #rgb/#rgba for value: '{value}'")
154 })?,
155 16,
156 )?;
157 let g = u8::from_str_radix(
158 hex.get(1..2).with_context(|| {
159 format!("{INVALID_UNICODE}: g component of #rgb/#rgba for value: '{value}'")
160 })?,
161 16,
162 )?;
163 let b = u8::from_str_radix(
164 hex.get(2..3).with_context(|| {
165 format!("{INVALID_UNICODE}: b component of #rgb/#rgba for value: '{value}'")
166 })?,
167 16,
168 )?;
169 let a = if hex.len() == RGBA {
170 u8::from_str_radix(
171 hex.get(3..4).with_context(|| {
172 format!("{INVALID_UNICODE}: a component of #rgba for value: '{value}'")
173 })?,
174 16,
175 )?
176 } else {
177 0xf
178 };
179
180 /// Duplicates a given hex digit.
181 /// E.g., `0xf` -> `0xff`.
182 const fn duplicate(value: u8) -> u8 {
183 value << 4 | value
184 }
185
186 (duplicate(r), duplicate(g), duplicate(b), duplicate(a))
187 }
188 RRGGBB | RRGGBBAA => {
189 let r = u8::from_str_radix(
190 hex.get(0..2).with_context(|| {
191 format!(
192 "{}: r component of #rrggbb/#rrggbbaa for value: '{}'",
193 INVALID_UNICODE, value
194 )
195 })?,
196 16,
197 )?;
198 let g = u8::from_str_radix(
199 hex.get(2..4).with_context(|| {
200 format!(
201 "{INVALID_UNICODE}: g component of #rrggbb/#rrggbbaa for value: '{value}'"
202 )
203 })?,
204 16,
205 )?;
206 let b = u8::from_str_radix(
207 hex.get(4..6).with_context(|| {
208 format!(
209 "{INVALID_UNICODE}: b component of #rrggbb/#rrggbbaa for value: '{value}'"
210 )
211 })?,
212 16,
213 )?;
214 let a = if hex.len() == RRGGBBAA {
215 u8::from_str_radix(
216 hex.get(6..8).with_context(|| {
217 format!(
218 "{INVALID_UNICODE}: a component of #rrggbbaa for value: '{value}'"
219 )
220 })?,
221 16,
222 )?
223 } else {
224 0xff
225 };
226 (r, g, b, a)
227 }
228 _ => bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}"),
229 };
230
231 Ok(Rgba {
232 r: r as f32 / 255.,
233 g: g as f32 / 255.,
234 b: b as f32 / 255.,
235 a: a as f32 / 255.,
236 })
237 }
238}
239
240/// An HSLA color
241#[derive(Default, Copy, Clone, Debug)]
242#[repr(C)]
243pub struct Hsla {
244 /// Hue, in a range from 0 to 1
245 pub h: f32,
246
247 /// Saturation, in a range from 0 to 1
248 pub s: f32,
249
250 /// Lightness, in a range from 0 to 1
251 pub l: f32,
252
253 /// Alpha, in a range from 0 to 1
254 pub a: f32,
255}
256
257impl PartialEq for Hsla {
258 fn eq(&self, other: &Self) -> bool {
259 self.h
260 .total_cmp(&other.h)
261 .then(self.s.total_cmp(&other.s))
262 .then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
263 .is_eq()
264 }
265}
266
267impl PartialOrd for Hsla {
268 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
269 Some(self.cmp(other))
270 }
271}
272
273impl Ord for Hsla {
274 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
275 self.h
276 .total_cmp(&other.h)
277 .then(self.s.total_cmp(&other.s))
278 .then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
279 }
280}
281
282impl Eq for Hsla {}
283
284impl Hash for Hsla {
285 fn hash<H: Hasher>(&self, state: &mut H) {
286 state.write_u32(u32::from_be_bytes(self.h.to_be_bytes()));
287 state.write_u32(u32::from_be_bytes(self.s.to_be_bytes()));
288 state.write_u32(u32::from_be_bytes(self.l.to_be_bytes()));
289 state.write_u32(u32::from_be_bytes(self.a.to_be_bytes()));
290 }
291}
292
293impl Display for Hsla {
294 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
295 write!(
296 f,
297 "hsla({:.2}, {:.2}%, {:.2}%, {:.2})",
298 self.h * 360.,
299 self.s * 100.,
300 self.l * 100.,
301 self.a
302 )
303 }
304}
305
306/// Construct an [`Hsla`] object from plain values
307pub fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla {
308 Hsla {
309 h: h.clamp(0., 1.),
310 s: s.clamp(0., 1.),
311 l: l.clamp(0., 1.),
312 a: a.clamp(0., 1.),
313 }
314}
315
316/// Pure black in [`Hsla`]
317pub fn black() -> Hsla {
318 Hsla {
319 h: 0.,
320 s: 0.,
321 l: 0.,
322 a: 1.,
323 }
324}
325
326/// Transparent black in [`Hsla`]
327pub fn transparent_black() -> Hsla {
328 Hsla {
329 h: 0.,
330 s: 0.,
331 l: 0.,
332 a: 0.,
333 }
334}
335
336/// Transparent black in [`Hsla`]
337pub fn transparent_white() -> Hsla {
338 Hsla {
339 h: 0.,
340 s: 0.,
341 l: 1.,
342 a: 0.,
343 }
344}
345
346/// Opaque grey in [`Hsla`], values will be clamped to the range [0, 1]
347pub fn opaque_grey(lightness: f32, opacity: f32) -> Hsla {
348 Hsla {
349 h: 0.,
350 s: 0.,
351 l: lightness.clamp(0., 1.),
352 a: opacity.clamp(0., 1.),
353 }
354}
355
356/// Pure white in [`Hsla`]
357pub fn white() -> Hsla {
358 Hsla {
359 h: 0.,
360 s: 0.,
361 l: 1.,
362 a: 1.,
363 }
364}
365
366/// The color red in [`Hsla`]
367pub fn red() -> Hsla {
368 Hsla {
369 h: 0.,
370 s: 1.,
371 l: 0.5,
372 a: 1.,
373 }
374}
375
376/// The color blue in [`Hsla`]
377pub fn blue() -> Hsla {
378 Hsla {
379 h: 0.6,
380 s: 1.,
381 l: 0.5,
382 a: 1.,
383 }
384}
385
386/// The color green in [`Hsla`]
387pub fn green() -> Hsla {
388 Hsla {
389 h: 0.33,
390 s: 1.,
391 l: 0.5,
392 a: 1.,
393 }
394}
395
396/// The color yellow in [`Hsla`]
397pub fn yellow() -> Hsla {
398 Hsla {
399 h: 0.16,
400 s: 1.,
401 l: 0.5,
402 a: 1.,
403 }
404}
405
406impl Hsla {
407 /// Converts this HSLA color to an RGBA color.
408 pub fn to_rgb(self) -> Rgba {
409 self.into()
410 }
411
412 /// The color red
413 pub fn red() -> Self {
414 red()
415 }
416
417 /// The color green
418 pub fn green() -> Self {
419 green()
420 }
421
422 /// The color blue
423 pub fn blue() -> Self {
424 blue()
425 }
426
427 /// The color black
428 pub fn black() -> Self {
429 black()
430 }
431
432 /// The color white
433 pub fn white() -> Self {
434 white()
435 }
436
437 /// The color transparent black
438 pub fn transparent_black() -> Self {
439 transparent_black()
440 }
441
442 /// Returns true if the HSLA color is fully transparent, false otherwise.
443 pub fn is_transparent(&self) -> bool {
444 self.a == 0.0
445 }
446
447 /// 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.
448 ///
449 /// If `other`'s alpha value is 1.0 or greater, `other` color is fully opaque, thus `other` is returned as the output color.
450 /// If `other`'s alpha value is 0.0 or less, `other` color is fully transparent, thus `self` is returned as the output color.
451 /// Else, the output color is calculated as a blend of `self` and `other` based on their weighted alpha values.
452 ///
453 /// Assumptions:
454 /// - Alpha values are contained in the range [0, 1], with 1 as fully opaque and 0 as fully transparent.
455 /// - 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 its own alpha value.
456 /// - RGB color components are contained in the range [0, 1].
457 /// - If `self` and `other` colors are out of the valid range, the blend operation's output and behavior is undefined.
458 pub fn blend(self, other: Hsla) -> Hsla {
459 let alpha = other.a;
460
461 if alpha >= 1.0 {
462 other
463 } else if alpha <= 0.0 {
464 return self;
465 } else {
466 let converted_self = Rgba::from(self);
467 let converted_other = Rgba::from(other);
468 let blended_rgb = converted_self.blend(converted_other);
469 return Hsla::from(blended_rgb);
470 }
471 }
472
473 /// Returns a new HSLA color with the same hue, and lightness, but with no saturation.
474 pub fn grayscale(&self) -> Self {
475 Hsla {
476 h: self.h,
477 s: 0.,
478 l: self.l,
479 a: self.a,
480 }
481 }
482
483 /// Fade out the color by a given factor. This factor should be between 0.0 and 1.0.
484 /// Where 0.0 will leave the color unchanged, and 1.0 will completely fade out the color.
485 pub fn fade_out(&mut self, factor: f32) {
486 self.a *= 1.0 - factor.clamp(0., 1.);
487 }
488
489 /// Returns a new HSLA color with the same hue, saturation, and lightness, but with a modified alpha value.
490 pub fn opacity(&self, factor: f32) -> Self {
491 Hsla {
492 h: self.h,
493 s: self.s,
494 l: self.l,
495 a: self.a * factor.clamp(0., 1.),
496 }
497 }
498}
499
500impl From<Rgba> for Hsla {
501 fn from(color: Rgba) -> Self {
502 let r = color.r;
503 let g = color.g;
504 let b = color.b;
505
506 let max = r.max(g.max(b));
507 let min = r.min(g.min(b));
508 let delta = max - min;
509
510 let l = (max + min) / 2.0;
511 let s = if l == 0.0 || l == 1.0 {
512 0.0
513 } else if l < 0.5 {
514 delta / (2.0 * l)
515 } else {
516 delta / (2.0 - 2.0 * l)
517 };
518
519 let h = if delta == 0.0 {
520 0.0
521 } else if max == r {
522 ((g - b) / delta).rem_euclid(6.0) / 6.0
523 } else if max == g {
524 ((b - r) / delta + 2.0) / 6.0
525 } else {
526 ((r - g) / delta + 4.0) / 6.0
527 };
528
529 Hsla {
530 h,
531 s,
532 l,
533 a: color.a,
534 }
535 }
536}
537
538impl<'de> Deserialize<'de> for Hsla {
539 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
540 where
541 D: Deserializer<'de>,
542 {
543 // First, deserialize it into Rgba
544 let rgba = Rgba::deserialize(deserializer)?;
545
546 // Then, use the From<Rgba> for Hsla implementation to convert it
547 Ok(Hsla::from(rgba))
548 }
549}
550
551#[cfg(test)]
552mod tests {
553 use serde_json::json;
554
555 use super::*;
556
557 #[test]
558 fn test_deserialize_three_value_hex_to_rgba() {
559 let actual: Rgba = serde_json::from_value(json!("#f09")).unwrap();
560
561 assert_eq!(actual, rgba(0xff0099ff))
562 }
563
564 #[test]
565 fn test_deserialize_four_value_hex_to_rgba() {
566 let actual: Rgba = serde_json::from_value(json!("#f09f")).unwrap();
567
568 assert_eq!(actual, rgba(0xff0099ff))
569 }
570
571 #[test]
572 fn test_deserialize_six_value_hex_to_rgba() {
573 let actual: Rgba = serde_json::from_value(json!("#ff0099")).unwrap();
574
575 assert_eq!(actual, rgba(0xff0099ff))
576 }
577
578 #[test]
579 fn test_deserialize_eight_value_hex_to_rgba() {
580 let actual: Rgba = serde_json::from_value(json!("#ff0099ff")).unwrap();
581
582 assert_eq!(actual, rgba(0xff0099ff))
583 }
584
585 #[test]
586 fn test_deserialize_eight_value_hex_with_padding_to_rgba() {
587 let actual: Rgba = serde_json::from_value(json!(" #f5f5f5ff ")).unwrap();
588
589 assert_eq!(actual, rgba(0xf5f5f5ff))
590 }
591
592 #[test]
593 fn test_deserialize_eight_value_hex_with_mixed_case_to_rgba() {
594 let actual: Rgba = serde_json::from_value(json!("#DeAdbEeF")).unwrap();
595
596 assert_eq!(actual, rgba(0xdeadbeef))
597 }
598}