Skip to main content

wgpui/
color.rs

1use anyhow::{Context as _, bail};
2use schemars::{JsonSchema, json_schema};
3use serde::{
4    Deserialize, Deserializer, Serialize, Serializer,
5    de::{self, Visitor},
6};
7use std::borrow::Cow;
8use std::{
9    fmt::{self, Display, Formatter},
10    hash::{Hash, Hasher},
11};
12
13/// Convert an RGB hex color code number to a color type
14pub fn rgb(hex: u32) -> Rgba {
15    let [_, r, g, b] = hex.to_be_bytes().map(|b| (b as f32) / 255.0);
16    Rgba { r, g, b, a: 1.0 }
17}
18
19/// Convert an RGBA hex color code number to [`Rgba`]
20pub fn rgba(hex: u32) -> Rgba {
21    let [r, g, b, a] = hex.to_be_bytes().map(|b| (b as f32) / 255.0);
22    Rgba { r, g, b, a }
23}
24
25/// Convert every premultiplied RGBA pixel to straight-alpha RGBA.
26pub(crate) fn unpremultiply_rgba(bytes: &mut [u8]) {
27    for pixel in bytes.chunks_exact_mut(4) {
28        let alpha = u32::from(pixel[3]);
29        if let Some(alpha) = std::num::NonZeroU32::new(alpha) {
30            for channel in pixel.iter_mut().take(3) {
31                *channel = (u32::from(*channel) * 255 / alpha).min(255) as u8;
32            }
33        } else {
34            pixel[..3].fill(0);
35        }
36    }
37}
38
39/// Convert native Direct2D premultiplied BGRA pixels to straight-alpha RGBA.
40#[cfg(any(target_os = "windows", test))]
41pub(crate) fn unpremultiply_bgra_to_rgba(bytes: &mut [u8]) {
42    for pixel in bytes.chunks_exact_mut(4) {
43        pixel.swap(0, 2);
44    }
45    unpremultiply_rgba(bytes);
46}
47
48/// An RGBA color
49#[derive(PartialEq, Clone, Copy, Default)]
50#[repr(C)]
51pub struct Rgba {
52    /// The red component of the color, in the range 0.0 to 1.0
53    pub r: f32,
54    /// The green component of the color, in the range 0.0 to 1.0
55    pub g: f32,
56    /// The blue component of the color, in the range 0.0 to 1.0
57    pub b: f32,
58    /// The alpha component of the color, in the range 0.0 to 1.0
59    pub a: f32,
60}
61
62impl fmt::Debug for Rgba {
63    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64        write!(f, "rgba({:#010x})", u32::from(*self))
65    }
66}
67
68impl Rgba {
69    /// Create a new [`Rgba`] color by blending this and another color together
70    pub fn blend(&self, other: Rgba) -> Self {
71        if other.a >= 1.0 {
72            other
73        } else if other.a <= 0.0 {
74            *self
75        } else {
76            Rgba {
77                r: (self.r * (1.0 - other.a)) + (other.r * other.a),
78                g: (self.g * (1.0 - other.a)) + (other.g * other.a),
79                b: (self.b * (1.0 - other.a)) + (other.b * other.a),
80                a: self.a,
81            }
82        }
83    }
84}
85
86impl From<Rgba> for u32 {
87    fn from(rgba: Rgba) -> Self {
88        let r = (rgba.r * 255.0) as u32;
89        let g = (rgba.g * 255.0) as u32;
90        let b = (rgba.b * 255.0) as u32;
91        let a = (rgba.a * 255.0) as u32;
92        (r << 24) | (g << 16) | (b << 8) | a
93    }
94}
95
96struct RgbaVisitor;
97
98impl Visitor<'_> for RgbaVisitor {
99    type Value = Rgba;
100
101    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
102        formatter.write_str("a string in the format #rrggbb or #rrggbbaa")
103    }
104
105    fn visit_str<E: de::Error>(self, value: &str) -> Result<Rgba, E> {
106        Rgba::try_from(value).map_err(E::custom)
107    }
108}
109
110impl JsonSchema for Rgba {
111    fn schema_name() -> Cow<'static, str> {
112        "Rgba".into()
113    }
114
115    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
116        json_schema!({
117            "type": "string",
118            "pattern": "^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$"
119        })
120    }
121}
122
123impl<'de> Deserialize<'de> for Rgba {
124    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
125        deserializer.deserialize_str(RgbaVisitor)
126    }
127}
128
129impl Serialize for Rgba {
130    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
131    where
132        S: Serializer,
133    {
134        let r = (self.r * 255.0).round() as u8;
135        let g = (self.g * 255.0).round() as u8;
136        let b = (self.b * 255.0).round() as u8;
137        let a = (self.a * 255.0).round() as u8;
138
139        let s = format!("#{r:02x}{g:02x}{b:02x}{a:02x}");
140        serializer.serialize_str(&s)
141    }
142}
143
144impl From<Hsla> for Rgba {
145    fn from(color: Hsla) -> Self {
146        let h = color.h;
147        let s = color.s;
148        let l = color.l;
149
150        let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
151        let x = c * (1.0 - ((h * 6.0) % 2.0 - 1.0).abs());
152        let m = l - c / 2.0;
153        let cm = c + m;
154        let xm = x + m;
155
156        let (r, g, b) = match (h * 6.0).floor() as i32 {
157            0 | 6 => (cm, xm, m),
158            1 => (xm, cm, m),
159            2 => (m, cm, xm),
160            3 => (m, xm, cm),
161            4 => (xm, m, cm),
162            _ => (cm, m, xm),
163        };
164
165        Rgba {
166            r: r.clamp(0., 1.),
167            g: g.clamp(0., 1.),
168            b: b.clamp(0., 1.),
169            a: color.a,
170        }
171    }
172}
173
174impl TryFrom<&'_ str> for Rgba {
175    type Error = anyhow::Error;
176
177    fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
178        const RGB: usize = "rgb".len();
179        const RGBA: usize = "rgba".len();
180        const RRGGBB: usize = "rrggbb".len();
181        const RRGGBBAA: usize = "rrggbbaa".len();
182
183        const EXPECTED_FORMATS: &str = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa";
184        const INVALID_UNICODE: &str = "invalid unicode characters in color";
185
186        let Some(("", hex)) = value.trim().split_once('#') else {
187            bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}");
188        };
189
190        let (r, g, b, a) = match hex.len() {
191            RGB | RGBA => {
192                let r = u8::from_str_radix(
193                    hex.get(0..1).with_context(|| {
194                        format!("{INVALID_UNICODE}: r component of #rgb/#rgba for value: '{value}'")
195                    })?,
196                    16,
197                )?;
198                let g = u8::from_str_radix(
199                    hex.get(1..2).with_context(|| {
200                        format!("{INVALID_UNICODE}: g component of #rgb/#rgba for value: '{value}'")
201                    })?,
202                    16,
203                )?;
204                let b = u8::from_str_radix(
205                    hex.get(2..3).with_context(|| {
206                        format!("{INVALID_UNICODE}: b component of #rgb/#rgba for value: '{value}'")
207                    })?,
208                    16,
209                )?;
210                let a = if hex.len() == RGBA {
211                    u8::from_str_radix(
212                        hex.get(3..4).with_context(|| {
213                            format!("{INVALID_UNICODE}: a component of #rgba for value: '{value}'")
214                        })?,
215                        16,
216                    )?
217                } else {
218                    0xf
219                };
220
221                /// Duplicates a given hex digit.
222                /// E.g., `0xf` -> `0xff`.
223                const fn duplicate(value: u8) -> u8 {
224                    (value << 4) | value
225                }
226
227                (duplicate(r), duplicate(g), duplicate(b), duplicate(a))
228            }
229            RRGGBB | RRGGBBAA => {
230                let r = u8::from_str_radix(
231                    hex.get(0..2).with_context(|| {
232                        format!(
233                            "{}: r component of #rrggbb/#rrggbbaa for value: '{}'",
234                            INVALID_UNICODE, value
235                        )
236                    })?,
237                    16,
238                )?;
239                let g = u8::from_str_radix(
240                    hex.get(2..4).with_context(|| {
241                        format!(
242                            "{INVALID_UNICODE}: g component of #rrggbb/#rrggbbaa for value: '{value}'"
243                        )
244                    })?,
245                    16,
246                )?;
247                let b = u8::from_str_radix(
248                    hex.get(4..6).with_context(|| {
249                        format!(
250                            "{INVALID_UNICODE}: b component of #rrggbb/#rrggbbaa for value: '{value}'"
251                        )
252                    })?,
253                    16,
254                )?;
255                let a = if hex.len() == RRGGBBAA {
256                    u8::from_str_radix(
257                        hex.get(6..8).with_context(|| {
258                            format!(
259                                "{INVALID_UNICODE}: a component of #rrggbbaa for value: '{value}'"
260                            )
261                        })?,
262                        16,
263                    )?
264                } else {
265                    0xff
266                };
267                (r, g, b, a)
268            }
269            _ => bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}"),
270        };
271
272        Ok(Rgba {
273            r: r as f32 / 255.,
274            g: g as f32 / 255.,
275            b: b as f32 / 255.,
276            a: a as f32 / 255.,
277        })
278    }
279}
280
281/// An HSLA color
282#[derive(Default, Copy, Clone, Debug)]
283#[repr(C)]
284pub struct Hsla {
285    /// Hue, in a range from 0 to 1
286    pub h: f32,
287
288    /// Saturation, in a range from 0 to 1
289    pub s: f32,
290
291    /// Lightness, in a range from 0 to 1
292    pub l: f32,
293
294    /// Alpha, in a range from 0 to 1
295    pub a: f32,
296}
297
298impl PartialEq for Hsla {
299    fn eq(&self, other: &Self) -> bool {
300        self.h
301            .total_cmp(&other.h)
302            .then(self.s.total_cmp(&other.s))
303            .then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
304            .is_eq()
305    }
306}
307
308impl PartialOrd for Hsla {
309    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
310        Some(self.cmp(other))
311    }
312}
313
314impl Ord for Hsla {
315    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
316        self.h
317            .total_cmp(&other.h)
318            .then(self.s.total_cmp(&other.s))
319            .then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
320    }
321}
322
323impl Eq for Hsla {}
324
325impl Hash for Hsla {
326    fn hash<H: Hasher>(&self, state: &mut H) {
327        state.write_u32(u32::from_be_bytes(self.h.to_be_bytes()));
328        state.write_u32(u32::from_be_bytes(self.s.to_be_bytes()));
329        state.write_u32(u32::from_be_bytes(self.l.to_be_bytes()));
330        state.write_u32(u32::from_be_bytes(self.a.to_be_bytes()));
331    }
332}
333
334impl Display for Hsla {
335    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
336        write!(
337            f,
338            "hsla({:.2}, {:.2}%, {:.2}%, {:.2})",
339            self.h * 360.,
340            self.s * 100.,
341            self.l * 100.,
342            self.a
343        )
344    }
345}
346
347/// Construct an [`Hsla`] object from plain values
348pub fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla {
349    Hsla {
350        h: h.clamp(0., 1.),
351        s: s.clamp(0., 1.),
352        l: l.clamp(0., 1.),
353        a: a.clamp(0., 1.),
354    }
355}
356
357/// Pure black in [`Hsla`]
358pub const fn black() -> Hsla {
359    Hsla {
360        h: 0.,
361        s: 0.,
362        l: 0.,
363        a: 1.,
364    }
365}
366
367/// Transparent black in [`Hsla`]
368pub const fn transparent_black() -> Hsla {
369    Hsla {
370        h: 0.,
371        s: 0.,
372        l: 0.,
373        a: 0.,
374    }
375}
376
377/// Transparent white in [`Hsla`]
378pub const fn transparent_white() -> Hsla {
379    Hsla {
380        h: 0.,
381        s: 0.,
382        l: 1.,
383        a: 0.,
384    }
385}
386
387/// Opaque grey in [`Hsla`], values will be clamped to the range [0, 1]
388pub fn opaque_grey(lightness: f32, opacity: f32) -> Hsla {
389    Hsla {
390        h: 0.,
391        s: 0.,
392        l: lightness.clamp(0., 1.),
393        a: opacity.clamp(0., 1.),
394    }
395}
396
397/// Pure white in [`Hsla`]
398pub const fn white() -> Hsla {
399    Hsla {
400        h: 0.,
401        s: 0.,
402        l: 1.,
403        a: 1.,
404    }
405}
406
407/// The color red in [`Hsla`]
408pub const fn red() -> Hsla {
409    Hsla {
410        h: 0.,
411        s: 1.,
412        l: 0.5,
413        a: 1.,
414    }
415}
416
417/// The color blue in [`Hsla`]
418pub const fn blue() -> Hsla {
419    Hsla {
420        h: 0.6666666667,
421        s: 1.,
422        l: 0.5,
423        a: 1.,
424    }
425}
426
427/// The color green in [`Hsla`]
428pub const fn green() -> Hsla {
429    Hsla {
430        h: 0.3333333333,
431        s: 1.,
432        l: 0.25,
433        a: 1.,
434    }
435}
436
437/// The color yellow in [`Hsla`]
438pub const fn yellow() -> Hsla {
439    Hsla {
440        h: 0.1666666667,
441        s: 1.,
442        l: 0.5,
443        a: 1.,
444    }
445}
446
447impl Hsla {
448    /// Converts this HSLA color to an RGBA color.
449    pub fn to_rgb(self) -> Rgba {
450        self.into()
451    }
452
453    /// The color red
454    pub const fn red() -> Self {
455        red()
456    }
457
458    /// The color green
459    pub const fn green() -> Self {
460        green()
461    }
462
463    /// The color blue
464    pub const fn blue() -> Self {
465        blue()
466    }
467
468    /// The color black
469    pub const fn black() -> Self {
470        black()
471    }
472
473    /// The color white
474    pub const fn white() -> Self {
475        white()
476    }
477
478    /// The color transparent black
479    pub const fn transparent_black() -> Self {
480        transparent_black()
481    }
482
483    /// Returns true if the HSLA color is fully transparent, false otherwise.
484    pub fn is_transparent(&self) -> bool {
485        self.a == 0.0
486    }
487
488    /// Returns true if the HSLA color is fully opaque, false otherwise.
489    pub fn is_opaque(&self) -> bool {
490        self.a == 1.0
491    }
492
493    /// 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.
494    ///
495    /// If `other`'s alpha value is 1.0 or greater, `other` color is fully opaque, thus `other` is returned as the output color.
496    /// If `other`'s alpha value is 0.0 or less, `other` color is fully transparent, thus `self` is returned as the output color.
497    /// Else, the output color is calculated as a blend of `self` and `other` based on their weighted alpha values.
498    ///
499    /// Assumptions:
500    /// - Alpha values are contained in the range [0, 1], with 1 as fully opaque and 0 as fully transparent.
501    /// - 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.
502    /// - RGB color components are contained in the range [0, 1].
503    /// - If `self` and `other` colors are out of the valid range, the blend operation's output and behavior is undefined.
504    pub fn blend(self, other: Hsla) -> Hsla {
505        let alpha = other.a;
506
507        if alpha >= 1.0 {
508            other
509        } else if alpha <= 0.0 {
510            self
511        } else {
512            let converted_self = Rgba::from(self);
513            let converted_other = Rgba::from(other);
514            let blended_rgb = converted_self.blend(converted_other);
515            Hsla::from(blended_rgb)
516        }
517    }
518
519    /// Returns a new HSLA color with the same hue, and lightness, but with no saturation.
520    pub fn grayscale(&self) -> Self {
521        Hsla {
522            h: self.h,
523            s: 0.,
524            l: self.l,
525            a: self.a,
526        }
527    }
528
529    /// Fade out the color by a given factor. This factor should be between 0.0 and 1.0.
530    /// Where 0.0 will leave the color unchanged, and 1.0 will completely fade out the color.
531    pub fn fade_out(&mut self, factor: f32) {
532        self.a *= 1.0 - factor.clamp(0., 1.);
533    }
534
535    /// Multiplies the alpha value of the color by a given factor
536    /// and returns a new HSLA color.
537    ///
538    /// Useful for transforming colors with dynamic opacity,
539    /// like a color from an external source.
540    ///
541    /// Example:
542    /// ```
543    /// let color = wgpui::red();
544    /// let faded_color = color.opacity(0.5);
545    /// assert_eq!(faded_color.a, 0.5);
546    /// ```
547    ///
548    /// This will return a red color with half the opacity.
549    ///
550    /// Example:
551    /// ```
552    /// use wgpui::hsla;
553    /// let color = hsla(0.7, 1.0, 0.5, 0.7); // A saturated blue
554    /// let faded_color = color.opacity(0.16);
555    /// assert!((faded_color.a - 0.112).abs() < 1e-6);
556    /// ```
557    ///
558    /// This will return a blue color with around ~10% opacity,
559    /// suitable for an element's hover or selected state.
560    ///
561    pub fn opacity(&self, factor: f32) -> Self {
562        Hsla {
563            h: self.h,
564            s: self.s,
565            l: self.l,
566            a: self.a * factor.clamp(0., 1.),
567        }
568    }
569
570    /// Returns a new HSLA color with the same hue, saturation,
571    /// and lightness, but with a new alpha value.
572    ///
573    /// Example:
574    /// ```
575    /// let color = wgpui::red();
576    /// let red_color = color.alpha(0.25);
577    /// assert_eq!(red_color.a, 0.25);
578    /// ```
579    ///
580    /// This will return a red color with half the opacity.
581    ///
582    /// Example:
583    /// ```
584    /// use wgpui::hsla;
585    /// let color = hsla(0.7, 1.0, 0.5, 0.7); // A saturated blue
586    /// let faded_color = color.alpha(0.25);
587    /// assert_eq!(faded_color.a, 0.25);
588    /// ```
589    ///
590    /// This will return a blue color with 25% opacity.
591    pub fn alpha(&self, a: f32) -> Self {
592        Hsla {
593            h: self.h,
594            s: self.s,
595            l: self.l,
596            a: a.clamp(0., 1.),
597        }
598    }
599}
600
601impl From<Rgba> for Hsla {
602    fn from(color: Rgba) -> Self {
603        let r = color.r;
604        let g = color.g;
605        let b = color.b;
606
607        let max = r.max(g.max(b));
608        let min = r.min(g.min(b));
609        let delta = max - min;
610
611        let l = (max + min) / 2.0;
612        let s = if l == 0.0 || l == 1.0 {
613            0.0
614        } else if l < 0.5 {
615            delta / (2.0 * l)
616        } else {
617            delta / (2.0 - 2.0 * l)
618        };
619
620        let h = if delta == 0.0 {
621            0.0
622        } else if max == r {
623            ((g - b) / delta).rem_euclid(6.0) / 6.0
624        } else if max == g {
625            ((b - r) / delta + 2.0) / 6.0
626        } else {
627            ((r - g) / delta + 4.0) / 6.0
628        };
629
630        Hsla {
631            h,
632            s,
633            l,
634            a: color.a,
635        }
636    }
637}
638
639impl JsonSchema for Hsla {
640    fn schema_name() -> Cow<'static, str> {
641        Rgba::schema_name()
642    }
643
644    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
645        Rgba::json_schema(generator)
646    }
647}
648
649impl Serialize for Hsla {
650    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
651    where
652        S: Serializer,
653    {
654        Rgba::from(*self).serialize(serializer)
655    }
656}
657
658impl<'de> Deserialize<'de> for Hsla {
659    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
660    where
661        D: Deserializer<'de>,
662    {
663        Ok(Rgba::deserialize(deserializer)?.into())
664    }
665}
666
667#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
668#[repr(C)]
669pub(crate) enum BackgroundTag {
670    Solid = 0,
671    LinearGradient = 1,
672    PatternSlash = 2,
673}
674
675/// A color space for color interpolation.
676///
677/// References:
678/// - <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
679/// - <https://www.w3.org/TR/css-color-4/#typedef-color-space>
680#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
681#[repr(C)]
682pub enum ColorSpace {
683    #[default]
684    /// The sRGB color space.
685    Srgb = 0,
686    /// The Oklab color space.
687    Oklab = 1,
688}
689
690impl Display for ColorSpace {
691    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
692        match self {
693            ColorSpace::Srgb => write!(f, "sRGB"),
694            ColorSpace::Oklab => write!(f, "Oklab"),
695        }
696    }
697}
698
699/// A background color, which can be either a solid color or a linear gradient.
700#[derive(Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
701#[repr(C)]
702pub struct Background {
703    pub(crate) tag: BackgroundTag,
704    pub(crate) color_space: ColorSpace,
705    pub(crate) solid: Hsla,
706    pub(crate) gradient_angle_or_pattern_height: f32,
707    pub(crate) colors: [LinearColorStop; 2],
708    /// Padding for alignment for repr(C) layout.
709    pub(crate) pad: u32,
710}
711
712impl std::fmt::Debug for Background {
713    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
714        match self.tag {
715            BackgroundTag::Solid => write!(f, "Solid({:?})", self.solid),
716            BackgroundTag::LinearGradient => {
717                write!(
718                    f,
719                    "LinearGradient({}, {:?}, {:?})",
720                    self.gradient_angle_or_pattern_height, self.colors[0], self.colors[1]
721                )
722            }
723            BackgroundTag::PatternSlash => {
724                write!(
725                    f,
726                    "PatternSlash({:?}, {})",
727                    self.solid, self.gradient_angle_or_pattern_height
728                )
729            }
730        }
731    }
732}
733
734impl Eq for Background {}
735impl Default for Background {
736    fn default() -> Self {
737        Self {
738            tag: BackgroundTag::Solid,
739            solid: Hsla::default(),
740            color_space: ColorSpace::default(),
741            gradient_angle_or_pattern_height: 0.0,
742            colors: [LinearColorStop::default(), LinearColorStop::default()],
743            pad: 0,
744        }
745    }
746}
747
748/// Creates a hash pattern background
749pub fn pattern_slash(color: Hsla, width: f32, interval: f32) -> Background {
750    let width_scaled = (width * 255.0) as u32;
751    let interval_scaled = (interval * 255.0) as u32;
752    let height = ((width_scaled * 0xFFFF) + interval_scaled) as f32;
753
754    Background {
755        tag: BackgroundTag::PatternSlash,
756        solid: color,
757        gradient_angle_or_pattern_height: height,
758        ..Default::default()
759    }
760}
761
762/// Creates a solid background color.
763pub fn solid_background(color: impl Into<Hsla>) -> Background {
764    Background {
765        solid: color.into(),
766        ..Default::default()
767    }
768}
769
770/// Creates a LinearGradient background color.
771///
772/// The gradient line's angle of direction. A value of `0.` is equivalent to top; increasing values rotate clockwise from there.
773///
774/// The `angle` is in degrees value in the range 0.0 to 360.0.
775///
776/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient>
777pub fn linear_gradient(
778    angle: f32,
779    from: impl Into<LinearColorStop>,
780    to: impl Into<LinearColorStop>,
781) -> Background {
782    Background {
783        tag: BackgroundTag::LinearGradient,
784        gradient_angle_or_pattern_height: angle,
785        colors: [from.into(), to.into()],
786        ..Default::default()
787    }
788}
789
790/// A color stop in a linear gradient.
791///
792/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#linear-color-stop>
793#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
794#[repr(C)]
795pub struct LinearColorStop {
796    /// The color of the color stop.
797    pub color: Hsla,
798    /// The percentage of the gradient, in the range 0.0 to 1.0.
799    pub percentage: f32,
800}
801
802/// Creates a new linear color stop.
803///
804/// The percentage of the gradient, in the range 0.0 to 1.0.
805pub fn linear_color_stop(color: impl Into<Hsla>, percentage: f32) -> LinearColorStop {
806    LinearColorStop {
807        color: color.into(),
808        percentage,
809    }
810}
811
812impl LinearColorStop {
813    /// Returns a new color stop with the same color, but with a modified alpha value.
814    pub fn opacity(&self, factor: f32) -> Self {
815        Self {
816            percentage: self.percentage,
817            color: self.color.opacity(factor),
818        }
819    }
820}
821
822impl Background {
823    /// Returns the solid fill color, or None for a gradient or patterned fill.
824    pub fn as_solid(&self) -> Option<Hsla> {
825        (self.tag == BackgroundTag::Solid).then_some(self.solid)
826    }
827
828    /// Use specified color space for color interpolation.
829    ///
830    /// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
831    pub fn color_space(mut self, color_space: ColorSpace) -> Self {
832        self.color_space = color_space;
833        self
834    }
835
836    /// Returns a new background color with the same hue, saturation, and lightness, but with a modified alpha value.
837    pub fn opacity(&self, factor: f32) -> Self {
838        let mut background = *self;
839        background.solid = background.solid.opacity(factor);
840        background.colors = [
841            self.colors[0].opacity(factor),
842            self.colors[1].opacity(factor),
843        ];
844        background
845    }
846
847    /// Returns whether the background color is transparent.
848    pub fn is_transparent(&self) -> bool {
849        match self.tag {
850            BackgroundTag::Solid => self.solid.is_transparent(),
851            BackgroundTag::LinearGradient => self.colors.iter().all(|c| c.color.is_transparent()),
852            BackgroundTag::PatternSlash => self.solid.is_transparent(),
853        }
854    }
855}
856
857impl From<Hsla> for Background {
858    fn from(value: Hsla) -> Self {
859        Background {
860            tag: BackgroundTag::Solid,
861            solid: value,
862            ..Default::default()
863        }
864    }
865}
866impl From<Rgba> for Background {
867    fn from(value: Rgba) -> Self {
868        Background {
869            tag: BackgroundTag::Solid,
870            solid: Hsla::from(value),
871            ..Default::default()
872        }
873    }
874}
875
876#[cfg(test)]
877mod tests {
878    use serde_json::json;
879
880    use super::*;
881
882    #[test]
883    fn premultiplied_buffers_preserve_every_color_and_alpha() {
884        let expected = [
885            251, 37, 13, 255, 59, 39, 19, 128, 17, 29, 233, 255, 0, 0, 0, 0,
886        ];
887        let mut rgba = [
888            251, 37, 13, 255, 30, 20, 10, 128, 17, 29, 233, 255, 7, 8, 9, 0,
889        ];
890        unpremultiply_rgba(&mut rgba);
891        assert_eq!(rgba, expected);
892        let mut bgra = [
893            13, 37, 251, 255, 10, 20, 30, 128, 233, 29, 17, 255, 9, 8, 7, 0,
894        ];
895        unpremultiply_bgra_to_rgba(&mut bgra);
896        assert_eq!(bgra, expected);
897    }
898
899    #[test]
900    fn test_deserialize_three_value_hex_to_rgba() {
901        let actual: Rgba = serde_json::from_value(json!("#f09")).unwrap();
902
903        assert_eq!(actual, rgba(0xff0099ff))
904    }
905
906    #[test]
907    fn test_deserialize_four_value_hex_to_rgba() {
908        let actual: Rgba = serde_json::from_value(json!("#f09f")).unwrap();
909
910        assert_eq!(actual, rgba(0xff0099ff))
911    }
912
913    #[test]
914    fn test_deserialize_six_value_hex_to_rgba() {
915        let actual: Rgba = serde_json::from_value(json!("#ff0099")).unwrap();
916
917        assert_eq!(actual, rgba(0xff0099ff))
918    }
919
920    #[test]
921    fn test_deserialize_eight_value_hex_to_rgba() {
922        let actual: Rgba = serde_json::from_value(json!("#ff0099ff")).unwrap();
923
924        assert_eq!(actual, rgba(0xff0099ff))
925    }
926
927    #[test]
928    fn test_deserialize_eight_value_hex_with_padding_to_rgba() {
929        let actual: Rgba = serde_json::from_value(json!(" #f5f5f5ff   ")).unwrap();
930
931        assert_eq!(actual, rgba(0xf5f5f5ff))
932    }
933
934    #[test]
935    fn test_deserialize_eight_value_hex_with_mixed_case_to_rgba() {
936        let actual: Rgba = serde_json::from_value(json!("#DeAdbEeF")).unwrap();
937
938        assert_eq!(actual, rgba(0xdeadbeef))
939    }
940
941    #[test]
942    fn test_background_solid() {
943        let color = Hsla::from(rgba(0xff0099ff));
944        let mut background = Background::from(color);
945        assert_eq!(background.tag, BackgroundTag::Solid);
946        assert_eq!(background.solid, color);
947
948        assert_eq!(background.opacity(0.5).solid, color.opacity(0.5));
949        assert!(!background.is_transparent());
950        background.solid = hsla(0.0, 0.0, 0.0, 0.0);
951        assert!(background.is_transparent());
952    }
953
954    #[test]
955    fn test_background_linear_gradient() {
956        let from = linear_color_stop(rgba(0xff0099ff), 0.0);
957        let to = linear_color_stop(rgba(0x00ff99ff), 1.0);
958        let background = linear_gradient(90.0, from, to);
959        assert_eq!(background.tag, BackgroundTag::LinearGradient);
960        assert_eq!(background.colors[0], from);
961        assert_eq!(background.colors[1], to);
962
963        assert_eq!(background.opacity(0.5).colors[0], from.opacity(0.5));
964        assert_eq!(background.opacity(0.5).colors[1], to.opacity(0.5));
965        assert!(!background.is_transparent());
966        assert!(background.opacity(0.0).is_transparent());
967    }
968}