Skip to main content

gpui/
color.rs

1use anyhow::{Context as _, bail};
2#[cfg(feature = "schemars")]
3use schemars::{JsonSchema, json_schema};
4use serde::{
5    Deserialize, Deserializer, Serialize, Serializer,
6    de::{self, Visitor},
7};
8#[cfg(feature = "schemars")]
9use std::borrow::Cow;
10use std::{
11    fmt::{self, Display, Formatter},
12    hash::{Hash, Hasher},
13};
14
15/// Convert an RGB hex color code number to a color type
16pub fn rgb(hex: u32) -> Rgba {
17    let [_, r, g, b] = hex.to_be_bytes().map(|b| (b as f32) / 255.0);
18    Rgba { r, g, b, a: 1.0 }
19}
20
21/// Convert an RGBA hex color code number to [`Rgba`]
22pub fn rgba(hex: u32) -> Rgba {
23    let [r, g, b, a] = hex.to_be_bytes().map(|b| (b as f32) / 255.0);
24    Rgba { r, g, b, a }
25}
26
27/// Swap from RGBA with premultiplied alpha to BGRA
28pub fn swap_rgba_pa_to_bgra(color: &mut [u8]) {
29    color.swap(0, 2);
30    if color[3] > 0 {
31        let a = color[3] as f32 / 255.;
32        color[0] = (color[0] as f32 / a) as u8;
33        color[1] = (color[1] as f32 / a) as u8;
34        color[2] = (color[2] as f32 / a) as u8;
35    }
36}
37
38/// An RGBA color
39#[derive(PartialEq, Clone, Copy, Default)]
40#[repr(C)]
41pub struct Rgba {
42    /// The red component of the color, in the range 0.0 to 1.0
43    pub r: f32,
44    /// The green component of the color, in the range 0.0 to 1.0
45    pub g: f32,
46    /// The blue component of the color, in the range 0.0 to 1.0
47    pub b: f32,
48    /// The alpha component of the color, in the range 0.0 to 1.0
49    pub a: f32,
50}
51
52impl fmt::Debug for Rgba {
53    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54        write!(f, "rgba({:#010x})", u32::from(*self))
55    }
56}
57
58impl Rgba {
59    /// Create a new [`Rgba`] color by blending this and another color together
60    pub fn blend(&self, other: Rgba) -> Self {
61        if other.a >= 1.0 {
62            other
63        } else if other.a <= 0.0 {
64            *self
65        } else {
66            Rgba {
67                r: (self.r * (1.0 - other.a)) + (other.r * other.a),
68                g: (self.g * (1.0 - other.a)) + (other.g * other.a),
69                b: (self.b * (1.0 - other.a)) + (other.b * other.a),
70                a: self.a,
71            }
72        }
73    }
74
75    /// Returns a new RGBA color with the same red, green and blue channels, but
76    /// with a new alpha value.
77    ///
78    /// Example:
79    /// ```
80    /// use gpui::rgba;
81    /// let color = rgba(0xFF0000FF);
82    /// let faded = color.alpha(0.25);
83    /// assert_eq!(faded.a, 0.25);
84    /// ```
85    ///
86    /// This will return a red color with 25% opacity.
87    ///
88    /// Example:
89    /// ```
90    /// use gpui::rgba;
91    /// let color = rgba(0x3399FFCC);
92    /// let transparent = color.alpha(0.0);
93    /// assert_eq!(transparent.a, 0.0);
94    /// ```
95    ///
96    /// This will return the same blue color, fully transparent.
97    pub fn alpha(&self, a: f32) -> Self {
98        Rgba {
99            r: self.r,
100            g: self.g,
101            b: self.b,
102            a: a.clamp(0., 1.),
103        }
104    }
105
106    /// Returns a new RGBA color with the same red, green, and blue channels,
107    /// but with the alpha channel multiplied by the given factor.
108    ///
109    /// Example:
110    /// ```
111    /// use gpui::rgba;
112    /// let color = rgba(0xFF0000FF); // Fully opaque red
113    /// let faded = color.opacity(0.5);
114    /// assert_eq!(faded.a, 0.5);
115    /// ```
116    ///
117    /// This will return a red color with 50% opacity.
118    ///
119    /// Example:
120    /// ```
121    /// use gpui::rgba;
122    /// let color = rgba(0x3399FFCC); // A light blue with 80% opacity
123    /// let faded = color.opacity(0.5);
124    /// assert!((faded.a - 0.4).abs() < 1e-6);
125    /// ```
126    ///
127    /// This will return the same blue color scaled down to 40% opacity.
128    pub fn opacity(&self, factor: f32) -> Self {
129        Rgba {
130            r: self.r,
131            g: self.g,
132            b: self.b,
133            a: self.a * factor.clamp(0., 1.),
134        }
135    }
136}
137
138impl From<Rgba> for u32 {
139    fn from(rgba: Rgba) -> Self {
140        let r = (rgba.r * 255.0) as u32;
141        let g = (rgba.g * 255.0) as u32;
142        let b = (rgba.b * 255.0) as u32;
143        let a = (rgba.a * 255.0) as u32;
144        (r << 24) | (g << 16) | (b << 8) | a
145    }
146}
147
148struct RgbaVisitor;
149
150impl Visitor<'_> for RgbaVisitor {
151    type Value = Rgba;
152
153    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
154        formatter.write_str("a string in the format #rrggbb or #rrggbbaa")
155    }
156
157    fn visit_str<E: de::Error>(self, value: &str) -> Result<Rgba, E> {
158        Rgba::try_from(value).map_err(E::custom)
159    }
160}
161
162#[cfg(feature = "schemars")]
163impl JsonSchema for Rgba {
164    fn schema_name() -> Cow<'static, str> {
165        "Rgba".into()
166    }
167
168    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
169        json_schema!({
170            "type": "string",
171            "pattern": "^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$"
172        })
173    }
174}
175
176impl<'de> Deserialize<'de> for Rgba {
177    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
178        deserializer.deserialize_str(RgbaVisitor)
179    }
180}
181
182impl Serialize for Rgba {
183    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
184    where
185        S: Serializer,
186    {
187        let r = (self.r * 255.0).round() as u8;
188        let g = (self.g * 255.0).round() as u8;
189        let b = (self.b * 255.0).round() as u8;
190        let a = (self.a * 255.0).round() as u8;
191
192        let s = format!("#{r:02x}{g:02x}{b:02x}{a:02x}");
193        serializer.serialize_str(&s)
194    }
195}
196
197impl From<Hsla> for Rgba {
198    fn from(color: Hsla) -> Self {
199        let h = color.h;
200        let s = color.s;
201        let l = color.l;
202
203        let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
204        let x = c * (1.0 - ((h * 6.0) % 2.0 - 1.0).abs());
205        let m = l - c / 2.0;
206        let cm = c + m;
207        let xm = x + m;
208
209        let (r, g, b) = match (h * 6.0).floor() as i32 {
210            0 | 6 => (cm, xm, m),
211            1 => (xm, cm, m),
212            2 => (m, cm, xm),
213            3 => (m, xm, cm),
214            4 => (xm, m, cm),
215            _ => (cm, m, xm),
216        };
217
218        Rgba {
219            r: r.clamp(0., 1.),
220            g: g.clamp(0., 1.),
221            b: b.clamp(0., 1.),
222            a: color.a,
223        }
224    }
225}
226
227impl TryFrom<&'_ str> for Rgba {
228    type Error = anyhow::Error;
229
230    fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
231        const RGB: usize = "rgb".len();
232        const RGBA: usize = "rgba".len();
233        const RRGGBB: usize = "rrggbb".len();
234        const RRGGBBAA: usize = "rrggbbaa".len();
235
236        const EXPECTED_FORMATS: &str = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa";
237        const INVALID_UNICODE: &str = "invalid unicode characters in color";
238
239        let Some(("", hex)) = value.trim().split_once('#') else {
240            bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}");
241        };
242
243        let (r, g, b, a) = match hex.len() {
244            RGB | RGBA => {
245                let r = u8::from_str_radix(
246                    hex.get(0..1).with_context(|| {
247                        format!("{INVALID_UNICODE}: r component of #rgb/#rgba for value: '{value}'")
248                    })?,
249                    16,
250                )?;
251                let g = u8::from_str_radix(
252                    hex.get(1..2).with_context(|| {
253                        format!("{INVALID_UNICODE}: g component of #rgb/#rgba for value: '{value}'")
254                    })?,
255                    16,
256                )?;
257                let b = u8::from_str_radix(
258                    hex.get(2..3).with_context(|| {
259                        format!("{INVALID_UNICODE}: b component of #rgb/#rgba for value: '{value}'")
260                    })?,
261                    16,
262                )?;
263                let a = if hex.len() == RGBA {
264                    u8::from_str_radix(
265                        hex.get(3..4).with_context(|| {
266                            format!("{INVALID_UNICODE}: a component of #rgba for value: '{value}'")
267                        })?,
268                        16,
269                    )?
270                } else {
271                    0xf
272                };
273
274                /// Duplicates a given hex digit.
275                /// E.g., `0xf` -> `0xff`.
276                const fn duplicate(value: u8) -> u8 {
277                    (value << 4) | value
278                }
279
280                (duplicate(r), duplicate(g), duplicate(b), duplicate(a))
281            }
282            RRGGBB | RRGGBBAA => {
283                let r = u8::from_str_radix(
284                    hex.get(0..2).with_context(|| {
285                        format!(
286                            "{}: r component of #rrggbb/#rrggbbaa for value: '{}'",
287                            INVALID_UNICODE, value
288                        )
289                    })?,
290                    16,
291                )?;
292                let g = u8::from_str_radix(
293                    hex.get(2..4).with_context(|| {
294                        format!(
295                            "{INVALID_UNICODE}: g component of #rrggbb/#rrggbbaa for value: '{value}'"
296                        )
297                    })?,
298                    16,
299                )?;
300                let b = u8::from_str_radix(
301                    hex.get(4..6).with_context(|| {
302                        format!(
303                            "{INVALID_UNICODE}: b component of #rrggbb/#rrggbbaa for value: '{value}'"
304                        )
305                    })?,
306                    16,
307                )?;
308                let a = if hex.len() == RRGGBBAA {
309                    u8::from_str_radix(
310                        hex.get(6..8).with_context(|| {
311                            format!(
312                                "{INVALID_UNICODE}: a component of #rrggbbaa for value: '{value}'"
313                            )
314                        })?,
315                        16,
316                    )?
317                } else {
318                    0xff
319                };
320                (r, g, b, a)
321            }
322            _ => bail!("invalid RGBA hex color: '{value}'. {EXPECTED_FORMATS}"),
323        };
324
325        Ok(Rgba {
326            r: r as f32 / 255.,
327            g: g as f32 / 255.,
328            b: b as f32 / 255.,
329            a: a as f32 / 255.,
330        })
331    }
332}
333
334/// An HSLA color
335#[derive(Default, Copy, Clone, Debug)]
336#[repr(C)]
337pub struct Hsla {
338    /// Hue, in a range from 0 to 1
339    pub h: f32,
340
341    /// Saturation, in a range from 0 to 1
342    pub s: f32,
343
344    /// Lightness, in a range from 0 to 1
345    pub l: f32,
346
347    /// Alpha, in a range from 0 to 1
348    pub a: f32,
349}
350
351#[cfg(feature = "proptest")]
352mod property {
353    use super::Hsla;
354    use proptest::prelude::*;
355
356    impl Hsla {
357        /// Proptest [`Strategy`] that produces opaque colors (i.e. alpha = 1).
358        ///
359        /// For truly arbitrary colors, use the [`Arbitrary`] implementation.
360        pub fn opaque_strategy() -> impl Strategy<Value = Self> {
361            (0.0f32..=1.0, 0.0f32..=1.0, 0.0f32..=1.0).prop_map(|(h, s, l)| Hsla { h, s, l, a: 1. })
362        }
363    }
364
365    impl Arbitrary for Hsla {
366        type Strategy = BoxedStrategy<Self>;
367        type Parameters = ();
368
369        fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
370            (0.0f32..=1.0, 0.0f32..=1.0, 0.0f32..=1.0, 0.0f32..=1.0)
371                .prop_map(|(h, s, l, a)| Hsla { h, s, l, a })
372                .boxed()
373        }
374    }
375}
376
377impl PartialEq for Hsla {
378    fn eq(&self, other: &Self) -> bool {
379        self.h
380            .total_cmp(&other.h)
381            .then(self.s.total_cmp(&other.s))
382            .then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
383            .is_eq()
384    }
385}
386
387impl PartialOrd for Hsla {
388    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
389        Some(self.cmp(other))
390    }
391}
392
393impl Ord for Hsla {
394    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
395        self.h
396            .total_cmp(&other.h)
397            .then(self.s.total_cmp(&other.s))
398            .then(self.l.total_cmp(&other.l).then(self.a.total_cmp(&other.a)))
399    }
400}
401
402impl Eq for Hsla {}
403
404impl Hash for Hsla {
405    fn hash<H: Hasher>(&self, state: &mut H) {
406        state.write_u32(u32::from_be_bytes(self.h.to_be_bytes()));
407        state.write_u32(u32::from_be_bytes(self.s.to_be_bytes()));
408        state.write_u32(u32::from_be_bytes(self.l.to_be_bytes()));
409        state.write_u32(u32::from_be_bytes(self.a.to_be_bytes()));
410    }
411}
412
413impl Display for Hsla {
414    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
415        write!(
416            f,
417            "hsla({:.2}, {:.2}%, {:.2}%, {:.2})",
418            self.h * 360.,
419            self.s * 100.,
420            self.l * 100.,
421            self.a
422        )
423    }
424}
425
426/// Construct an [`Hsla`] object from plain values
427pub const fn hsla(h: f32, s: f32, l: f32, a: f32) -> Hsla {
428    Hsla {
429        h: h.clamp(0., 1.),
430        s: s.clamp(0., 1.),
431        l: l.clamp(0., 1.),
432        a: a.clamp(0., 1.),
433    }
434}
435
436/// Pure black in [`Hsla`]
437pub const fn black() -> Hsla {
438    Hsla {
439        h: 0.,
440        s: 0.,
441        l: 0.,
442        a: 1.,
443    }
444}
445
446/// Transparent black in [`Hsla`]
447pub const fn transparent_black() -> Hsla {
448    Hsla {
449        h: 0.,
450        s: 0.,
451        l: 0.,
452        a: 0.,
453    }
454}
455
456/// Transparent white in [`Hsla`]
457pub const fn transparent_white() -> Hsla {
458    Hsla {
459        h: 0.,
460        s: 0.,
461        l: 1.,
462        a: 0.,
463    }
464}
465
466/// Opaque grey in [`Hsla`], values will be clamped to the range [0, 1]
467pub const fn opaque_grey(lightness: f32, opacity: f32) -> Hsla {
468    Hsla {
469        h: 0.,
470        s: 0.,
471        l: lightness.clamp(0., 1.),
472        a: opacity.clamp(0., 1.),
473    }
474}
475
476/// Pure white in [`Hsla`]
477pub const fn white() -> Hsla {
478    Hsla {
479        h: 0.,
480        s: 0.,
481        l: 1.,
482        a: 1.,
483    }
484}
485
486/// The color red in [`Hsla`]
487pub const fn red() -> Hsla {
488    Hsla {
489        h: 0.,
490        s: 1.,
491        l: 0.5,
492        a: 1.,
493    }
494}
495
496/// The color blue in [`Hsla`]
497pub const fn blue() -> Hsla {
498    Hsla {
499        h: 0.6666666667,
500        s: 1.,
501        l: 0.5,
502        a: 1.,
503    }
504}
505
506/// The color green in [`Hsla`]
507pub const fn green() -> Hsla {
508    Hsla {
509        h: 0.3333333333,
510        s: 1.,
511        l: 0.25,
512        a: 1.,
513    }
514}
515
516/// The color yellow in [`Hsla`]
517pub const fn yellow() -> Hsla {
518    Hsla {
519        h: 0.1666666667,
520        s: 1.,
521        l: 0.5,
522        a: 1.,
523    }
524}
525
526impl Hsla {
527    /// Converts this HSLA color to an RGBA color.
528    pub fn to_rgb(self) -> Rgba {
529        self.into()
530    }
531
532    /// The color red
533    pub const fn red() -> Self {
534        red()
535    }
536
537    /// The color green
538    pub const fn green() -> Self {
539        green()
540    }
541
542    /// The color blue
543    pub const fn blue() -> Self {
544        blue()
545    }
546
547    /// The color black
548    pub const fn black() -> Self {
549        black()
550    }
551
552    /// The color white
553    pub const fn white() -> Self {
554        white()
555    }
556
557    /// The color transparent black
558    pub const fn transparent_black() -> Self {
559        transparent_black()
560    }
561
562    /// Returns true if the HSLA color is fully transparent, false otherwise.
563    pub fn is_transparent(&self) -> bool {
564        self.a == 0.0
565    }
566
567    /// Returns true if the HSLA color is fully opaque, false otherwise.
568    pub fn is_opaque(&self) -> bool {
569        self.a == 1.0
570    }
571
572    /// 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.
573    ///
574    /// If `other`'s alpha value is 1.0 or greater, `other` color is fully opaque, thus `other` is returned as the output color.
575    /// If `other`'s alpha value is 0.0 or less, `other` color is fully transparent, thus `self` is returned as the output color.
576    /// Else, the output color is calculated as a blend of `self` and `other` based on their weighted alpha values.
577    ///
578    /// Assumptions:
579    /// - Alpha values are contained in the range [0, 1], with 1 as fully opaque and 0 as fully transparent.
580    /// - 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.
581    /// - RGB color components are contained in the range [0, 1].
582    /// - If `self` and `other` colors are out of the valid range, the blend operation's output and behavior is undefined.
583    pub fn blend(self, other: Hsla) -> Hsla {
584        let alpha = other.a;
585
586        if alpha >= 1.0 {
587            other
588        } else if alpha <= 0.0 {
589            self
590        } else {
591            let converted_self = Rgba::from(self);
592            let converted_other = Rgba::from(other);
593            let blended_rgb = converted_self.blend(converted_other);
594            Hsla::from(blended_rgb)
595        }
596    }
597
598    /// Returns a new HSLA color with the same hue, and lightness, but with no saturation.
599    pub fn grayscale(&self) -> Self {
600        Hsla {
601            h: self.h,
602            s: 0.,
603            l: self.l,
604            a: self.a,
605        }
606    }
607
608    /// Fade out the color by a given factor. This factor should be between 0.0 and 1.0.
609    /// Where 0.0 will leave the color unchanged, and 1.0 will completely fade out the color.
610    pub fn fade_out(&mut self, factor: f32) {
611        self.a *= 1.0 - factor.clamp(0., 1.);
612    }
613
614    /// Multiplies the alpha value of the color by a given factor
615    /// and returns a new HSLA color.
616    ///
617    /// Useful for transforming colors with dynamic opacity,
618    /// like a color from an external source.
619    ///
620    /// Example:
621    /// ```
622    /// let color = gpui::red();
623    /// let faded_color = color.opacity(0.5);
624    /// assert_eq!(faded_color.a, 0.5);
625    /// ```
626    ///
627    /// This will return a red color with half the opacity.
628    ///
629    /// Example:
630    /// ```
631    /// use gpui::hsla;
632    /// let color = hsla(0.7, 1.0, 0.5, 0.7); // A saturated blue
633    /// let faded_color = color.opacity(0.16);
634    /// assert!((faded_color.a - 0.112).abs() < 1e-6);
635    /// ```
636    ///
637    /// This will return a blue color with around ~10% opacity,
638    /// suitable for an element's hover or selected state.
639    ///
640    pub fn opacity(&self, factor: f32) -> Self {
641        Hsla {
642            h: self.h,
643            s: self.s,
644            l: self.l,
645            a: self.a * factor.clamp(0., 1.),
646        }
647    }
648
649    /// Returns a new HSLA color with the same hue, saturation,
650    /// and lightness, but with a new alpha value.
651    ///
652    /// Example:
653    /// ```
654    /// let color = gpui::red();
655    /// let red_color = color.alpha(0.25);
656    /// assert_eq!(red_color.a, 0.25);
657    /// ```
658    ///
659    /// This will return a red color with 25% opacity.
660    ///
661    /// Example:
662    /// ```
663    /// use gpui::hsla;
664    /// let color = hsla(0.7, 1.0, 0.5, 0.7); // A saturated blue
665    /// let faded_color = color.alpha(0.25);
666    /// assert_eq!(faded_color.a, 0.25);
667    /// ```
668    ///
669    /// This will return a blue color with 25% opacity.
670    pub fn alpha(&self, a: f32) -> Self {
671        Hsla {
672            h: self.h,
673            s: self.s,
674            l: self.l,
675            a: a.clamp(0., 1.),
676        }
677    }
678}
679
680impl From<Rgba> for Hsla {
681    fn from(color: Rgba) -> Self {
682        let r = color.r;
683        let g = color.g;
684        let b = color.b;
685
686        let max = r.max(g.max(b));
687        let min = r.min(g.min(b));
688        let delta = max - min;
689
690        let l = (max + min) / 2.0;
691        let s = if l == 0.0 || l == 1.0 {
692            0.0
693        } else if l < 0.5 {
694            delta / (2.0 * l)
695        } else {
696            delta / (2.0 - 2.0 * l)
697        };
698
699        let h = if delta == 0.0 {
700            0.0
701        } else if max == r {
702            ((g - b) / delta).rem_euclid(6.0) / 6.0
703        } else if max == g {
704            ((b - r) / delta + 2.0) / 6.0
705        } else {
706            ((r - g) / delta + 4.0) / 6.0
707        };
708
709        Hsla {
710            h,
711            s,
712            l,
713            a: color.a,
714        }
715    }
716}
717
718#[cfg(feature = "schemars")]
719impl JsonSchema for Hsla {
720    fn schema_name() -> Cow<'static, str> {
721        Rgba::schema_name()
722    }
723
724    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
725        Rgba::json_schema(generator)
726    }
727}
728
729impl Serialize for Hsla {
730    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
731    where
732        S: Serializer,
733    {
734        Rgba::from(*self).serialize(serializer)
735    }
736}
737
738impl<'de> Deserialize<'de> for Hsla {
739    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
740    where
741        D: Deserializer<'de>,
742    {
743        Ok(Rgba::deserialize(deserializer)?.into())
744    }
745}
746
747#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
748#[cfg_attr(feature = "schemars", derive(JsonSchema))]
749#[repr(C)]
750pub(crate) enum BackgroundTag {
751    Solid = 0,
752    LinearGradient = 1,
753    PatternSlash = 2,
754    Checkerboard = 3,
755    RadialGradient = 4,
756    ConicGradient = 5,
757}
758
759/// How many colour stops a gradient [`Background`] carries inline.
760///
761/// The stops live IN the `Background` rather than behind an index into a side
762/// buffer, because a side buffer would need a second binding on DirectX, a
763/// second storage buffer on wgpu, a second `[[buffer(n)]]` on Metal and — the
764/// expensive one — a second instance TEXTURE on WebGL2, where instance data is
765/// unpacked by hand. Eight is the smallest power of two that covers everything
766/// real CSS in this tree asks for (the widest is a seven-stop hue wheel), and
767/// a caller with more stops splits the gradient into layered bands instead
768/// (`vn_css`'s `gradient_layers`), which is exact rather than approximate.
769pub const GRADIENT_STOPS: usize = 8;
770
771/// `Background::flags` — the ramp restarts every period instead of clamping at
772/// the ends (`repeating-linear-gradient()` and friends).
773pub(crate) const BG_REPEATING: u32 = 1 << 0;
774/// `Background::flags` — `tile` holds a `background-size` / `background-position`
775/// pair, and the gradient is evaluated in TILE space rather than box space.
776pub(crate) const BG_TILED: u32 = 1 << 1;
777/// `Background::flags` — `gradient_angle_or_pattern_height` holds a CORNER index
778/// (0 = to top right, 1 = to bottom right, 2 = to bottom left, 3 = to top left)
779/// rather than an angle. CSS aims a corner gradient's line at the actual corner,
780/// so the angle depends on the box's aspect ratio, which only the shader knows.
781pub(crate) const BG_CORNER: u32 = 1 << 2;
782/// `Background::flags` — with [`BG_TILED`], the tile does NOT repeat along x
783/// (`background-repeat: no-repeat` / `repeat-y`): everything outside the one
784/// tile is transparent rather than another copy of it.
785pub(crate) const BG_NO_REPEAT_X: u32 = 1 << 3;
786/// `Background::flags` — as [`BG_NO_REPEAT_X`], along y.
787pub(crate) const BG_NO_REPEAT_Y: u32 = 1 << 4;
788/// `Background::flags` — `params[0..2]` is an offset in PIXELS from the box's
789/// top left corner rather than a fraction of the box.
790pub(crate) const BG_CENTER_PX: u32 = 1 << 5;
791/// `Background::flags` — `params[2..4]` is a pair of radii in PIXELS rather
792/// than fractions of the box.
793pub(crate) const BG_RADIUS_PX: u32 = 1 << 6;
794/// `Background::flags` — the tile's WIDTH is a fraction of the box's rather
795/// than a length (`background-size: 50% …`).
796pub(crate) const BG_TILE_W_FRACTION: u32 = 1 << 7;
797/// `Background::flags` — as [`BG_TILE_W_FRACTION`], for the tile's height.
798pub(crate) const BG_TILE_H_FRACTION: u32 = 1 << 8;
799/// `Background::flags` — the tile's x OFFSET is a fraction of the space the
800/// tile leaves in the box, which is how CSS defines a percentage
801/// `background-position` (`50%` centres the tile, it does not move it by half
802/// the box).
803pub(crate) const BG_TILE_X_FRACTION: u32 = 1 << 9;
804/// `Background::flags` — as [`BG_TILE_X_FRACTION`], for the y offset.
805pub(crate) const BG_TILE_Y_FRACTION: u32 = 1 << 10;
806/// `Background::flags` (vue-native fork) — paint this background only in the
807/// quad's BORDER area, the ring between the outer edge and the inner edge the
808/// border widths make. Inside the inner edge the quad is transparent. The
809/// border colour still blends over the ring. This is what [`Style::vn_mask_ring`]
810/// paints with: the quad's border widths are the element's border plus its
811/// padding, so the ring is the padding and border area, and the content box
812/// stays empty.
813///
814/// [`Style::vn_mask_ring`]: crate::Style::vn_mask_ring
815pub(crate) const BG_RING: u32 = 1 << 11;
816/// `Background::flags` — bit `BG_STOP_PX_SHIFT + i` marks stop `i`'s
817/// `percentage` as an ABSOLUTE length in pixels along the gradient line rather
818/// than a fraction of it. `linear-gradient(white 1px, transparent 1px)` — the
819/// hard-stop idiom every CSS grid pattern is built from — has no percentage
820/// form, and the gradient line's length is a shader-side quantity.
821pub(crate) const BG_STOP_PX_SHIFT: u32 = 16;
822/// `Background::flags` — bit `BG_STOP_CALC_SHIFT + i` marks stop `i`'s
823/// `percentage` as two packed halves, a fraction of the gradient line (high)
824/// plus a length in pixels (low): `calc(100% - 20px)`.
825pub(crate) const BG_STOP_CALC_SHIFT: u32 = 24;
826
827/// `v` as IEEE half-precision bits, rounded to nearest even; out-of-range
828/// values clamp to the largest finite half.
829fn f16_bits(v: f32) -> u16 {
830    let x = v.to_bits();
831    let sign = ((x >> 16) & 0x8000) as u16;
832    let exp = ((x >> 23) & 0xff) as i32 - 127 + 15;
833    let man = x & 0x7f_ffff;
834    let round = |bits: u32, shift: u32| {
835        let kept = bits >> shift;
836        let rest = bits & ((1 << shift) - 1);
837        let mid = 1 << (shift - 1);
838        if rest > mid || (rest == mid && kept & 1 == 1) {
839            kept + 1
840        } else {
841            kept
842        }
843    };
844    if !v.is_finite() || exp >= 31 {
845        return sign | 0x7bff;
846    }
847    if exp <= 0 {
848        if exp < -10 {
849            return sign;
850        }
851        return sign | round(man | 0x80_0000, (14 - exp) as u32) as u16;
852    }
853    sign | round(((exp as u32) << 23) | man, 13).min(0x7bff) as u16
854}
855
856/// A color space for color interpolation.
857///
858/// References:
859/// - <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
860/// - <https://www.w3.org/TR/css-color-4/#typedef-color-space>
861#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
862#[cfg_attr(feature = "schemars", derive(JsonSchema))]
863#[repr(C)]
864pub enum ColorSpace {
865    #[default]
866    /// The sRGB color space.
867    Srgb = 0,
868    /// The Oklab color space.
869    Oklab = 1,
870}
871
872impl Display for ColorSpace {
873    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
874        match self {
875            ColorSpace::Srgb => write!(f, "sRGB"),
876            ColorSpace::Oklab => write!(f, "Oklab"),
877        }
878    }
879}
880
881/// A background: a solid colour, one of the two procedural patterns, or a
882/// linear / radial / conic gradient of up to [`GRADIENT_STOPS`] stops,
883/// optionally repeating and optionally tiled across the box.
884///
885/// The layout is the GPU layout — see the `Quad` word map in `scene.rs` and the
886/// hand-mirrored `struct Background` in each backend's shader. Adding a field
887/// here is a six-file change; the checklist is on `Quad`.
888#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
889#[cfg_attr(feature = "schemars", derive(JsonSchema))]
890#[repr(C)]
891pub struct Background {
892    pub(crate) tag: BackgroundTag,
893    pub(crate) color_space: ColorSpace,
894    pub(crate) solid: Hsla,
895    /// The gradient line's angle in degrees for a linear gradient (or a corner
896    /// index when [`BG_CORNER`] is set), the start angle for a conic gradient,
897    /// and the pattern period for the two procedural tags.
898    pub(crate) gradient_angle_or_pattern_height: f32,
899    pub(crate) colors: [LinearColorStop; GRADIENT_STOPS],
900    /// How many of `colors` are live. Zero for a non-gradient tag.
901    pub(crate) stop_count: u32,
902    /// `BG_*` bits above.
903    pub(crate) flags: u32,
904    /// Radial: `[cx, cy, rx, ry]`. The centre is a FRACTION of the box; the
905    /// radii are fractions too when `rx >= 0`, and when `rx < 0` the pair is an
906    /// extent keyword instead — `-rx` is 1 `closest-side`, 2 `farthest-side`,
907    /// 3 `closest-corner`, 4 `farthest-corner`, and `ry` is 0 for a circle and
908    /// 1 for an ellipse. Conic: `[cx, cy, _, _]`. Unused otherwise.
909    pub(crate) params: [f32; 4],
910    /// `[width, height, offset_x, offset_y]` in pixels when [`BG_TILED`] is
911    /// set: `background-size` and `background-position`.
912    pub(crate) tile: [f32; 4],
913}
914
915impl std::fmt::Debug for Background {
916    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
917        let stops = &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)];
918        match self.tag {
919            BackgroundTag::Solid => write!(f, "Solid({:?})", self.solid),
920            BackgroundTag::LinearGradient => write!(
921                f,
922                "LinearGradient({}, {:?}, flags {:#x}, tile {:?})",
923                self.gradient_angle_or_pattern_height, stops, self.flags, self.tile
924            ),
925            BackgroundTag::RadialGradient => write!(
926                f,
927                "RadialGradient({:?}, {:?}, flags {:#x}, tile {:?})",
928                self.params, stops, self.flags, self.tile
929            ),
930            BackgroundTag::ConicGradient => write!(
931                f,
932                "ConicGradient({}, {:?}, {:?}, flags {:#x}, tile {:?})",
933                self.gradient_angle_or_pattern_height, self.params, stops, self.flags, self.tile
934            ),
935            BackgroundTag::PatternSlash => write!(
936                f,
937                "PatternSlash({:?}, {})",
938                self.solid, self.gradient_angle_or_pattern_height
939            ),
940            BackgroundTag::Checkerboard => write!(
941                f,
942                "Checkerboard({:?}, {})",
943                self.solid, self.gradient_angle_or_pattern_height
944            ),
945        }
946    }
947}
948
949impl Eq for Background {}
950impl Default for Background {
951    fn default() -> Self {
952        Self {
953            tag: BackgroundTag::Solid,
954            solid: Hsla::default(),
955            color_space: ColorSpace::default(),
956            gradient_angle_or_pattern_height: 0.0,
957            colors: [LinearColorStop::default(); GRADIENT_STOPS],
958            stop_count: 0,
959            flags: 0,
960            params: [0.0; 4],
961            tile: [0.0; 4],
962        }
963    }
964}
965
966/// Creates a hash pattern background
967pub fn pattern_slash(color: impl Into<Hsla>, width: f32, interval: f32) -> Background {
968    let width_scaled = (width * 255.0) as u32;
969    let interval_scaled = (interval * 255.0) as u32;
970    let height = ((width_scaled * 0xFFFF) + interval_scaled) as f32;
971
972    Background {
973        tag: BackgroundTag::PatternSlash,
974        solid: color.into(),
975        gradient_angle_or_pattern_height: height,
976        ..Default::default()
977    }
978}
979
980/// Creates a checkerboard pattern background
981pub fn checkerboard(color: impl Into<Hsla>, size: f32) -> Background {
982    Background {
983        tag: BackgroundTag::Checkerboard,
984        solid: color.into(),
985        gradient_angle_or_pattern_height: size,
986        ..Default::default()
987    }
988}
989
990/// Creates a solid background color.
991pub fn solid_background(color: impl Into<Hsla>) -> Background {
992    Background {
993        solid: color.into(),
994        ..Default::default()
995    }
996}
997
998/// Creates a LinearGradient background color.
999///
1000/// The gradient line's angle of direction. A value of `0.` is equivalent to top; increasing values rotate clockwise from there.
1001///
1002/// The `angle` is in degrees value in the range 0.0 to 360.0.
1003///
1004/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient>
1005pub fn linear_gradient(
1006    angle: f32,
1007    from: impl Into<LinearColorStop>,
1008    to: impl Into<LinearColorStop>,
1009) -> Background {
1010    gradient_with_stops(
1011        BackgroundTag::LinearGradient,
1012        angle,
1013        &[from.into(), to.into()],
1014    )
1015}
1016
1017/// A linear gradient with up to [`GRADIENT_STOPS`] stops. Extra stops are
1018/// dropped from the middle rather than the ends, so the ramp always starts and
1019/// finishes on the colours the caller asked for.
1020pub fn linear_gradient_stops(angle: f32, stops: &[LinearColorStop]) -> Background {
1021    gradient_with_stops(BackgroundTag::LinearGradient, angle, stops)
1022}
1023
1024/// A radial gradient, centred on the box and reaching its farthest corner —
1025/// CSS's defaults. [`Background::at`], [`Background::with_radii`] and
1026/// [`Background::with_extent`] change each of those.
1027pub fn radial_gradient(stops: &[LinearColorStop]) -> Background {
1028    let mut background = gradient_with_stops(BackgroundTag::RadialGradient, 0.0, stops);
1029    background.params = [0.5, 0.5, -4.0, 1.0];
1030    background
1031}
1032
1033/// A conic gradient. `from_angle` is in degrees clockwise from twelve o'clock;
1034/// the centre defaults to the middle of the box.
1035pub fn conic_gradient(from_angle: f32, stops: &[LinearColorStop]) -> Background {
1036    let mut background = gradient_with_stops(BackgroundTag::ConicGradient, from_angle, stops);
1037    background.params = [0.5, 0.5, 0.0, 0.0];
1038    background
1039}
1040
1041fn gradient_with_stops(tag: BackgroundTag, angle: f32, stops: &[LinearColorStop]) -> Background {
1042    let mut colors = [LinearColorStop::default(); GRADIENT_STOPS];
1043    let n = stops.len().min(GRADIENT_STOPS);
1044    if stops.len() <= GRADIENT_STOPS {
1045        colors[..n].copy_from_slice(&stops[..n]);
1046    } else {
1047        // Keep both ends and spread the rest evenly through the middle. A
1048        // caller that cannot afford the loss splits into bands instead.
1049        colors[0] = stops[0];
1050        colors[GRADIENT_STOPS - 1] = stops[stops.len() - 1];
1051        for (i, slot) in colors[1..GRADIENT_STOPS - 1].iter_mut().enumerate() {
1052            let t = (i + 1) as f32 / (GRADIENT_STOPS - 1) as f32;
1053            *slot = stops[((t * (stops.len() - 1) as f32).round() as usize).min(stops.len() - 1)];
1054        }
1055    }
1056    Background {
1057        tag,
1058        gradient_angle_or_pattern_height: angle,
1059        colors,
1060        stop_count: n as u32,
1061        ..Default::default()
1062    }
1063}
1064
1065/// A color stop in a linear gradient.
1066///
1067/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#linear-color-stop>
1068#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1069#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1070#[repr(C)]
1071pub struct LinearColorStop {
1072    /// The color of the color stop.
1073    pub color: Hsla,
1074    /// The percentage of the gradient, in the range 0.0 to 1.0.
1075    pub percentage: f32,
1076}
1077
1078/// Creates a new linear color stop.
1079///
1080/// The percentage of the gradient, in the range 0.0 to 1.0.
1081pub fn linear_color_stop(color: impl Into<Hsla>, percentage: f32) -> LinearColorStop {
1082    LinearColorStop {
1083        color: color.into(),
1084        percentage,
1085    }
1086}
1087
1088impl LinearColorStop {
1089    /// Returns a new color stop with the same color, but with a modified alpha value.
1090    pub fn opacity(&self, factor: f32) -> Self {
1091        Self {
1092            percentage: self.percentage,
1093            color: self.color.opacity(factor),
1094        }
1095    }
1096}
1097
1098impl Background {
1099    /// Returns the solid color if this is a solid background, None otherwise.
1100    pub fn as_solid(&self) -> Option<Hsla> {
1101        if self.tag == BackgroundTag::Solid {
1102            Some(self.solid)
1103        } else {
1104            None
1105        }
1106    }
1107
1108    /// vue-native fork: this background, painted only in the border area of
1109    /// the quad it fills ([`BG_RING`]).
1110    pub(crate) fn ring(mut self) -> Self {
1111        self.flags |= BG_RING;
1112        self
1113    }
1114
1115    /// vue-native fork: whether this is a [`Self::ring`] background.
1116    pub(crate) fn is_ring(&self) -> bool {
1117        self.flags & BG_RING != 0
1118    }
1119
1120    /// Use specified color space for color interpolation.
1121    ///
1122    /// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
1123    pub fn color_space(mut self, color_space: ColorSpace) -> Self {
1124        self.color_space = color_space;
1125        self
1126    }
1127
1128    /// Returns a new background color with the same hue, saturation, and lightness, but with a modified alpha value.
1129    pub fn opacity(&self, factor: f32) -> Self {
1130        let mut background = *self;
1131        background.solid = background.solid.opacity(factor);
1132        for stop in &mut background.colors {
1133            *stop = stop.opacity(factor);
1134        }
1135        background
1136    }
1137
1138    /// Returns whether the background color is transparent.
1139    pub fn is_transparent(&self) -> bool {
1140        match self.tag {
1141            BackgroundTag::Solid | BackgroundTag::PatternSlash | BackgroundTag::Checkerboard => {
1142                self.solid.is_transparent()
1143            }
1144            BackgroundTag::LinearGradient
1145            | BackgroundTag::RadialGradient
1146            | BackgroundTag::ConicGradient => self.live_stops()
1147                .iter()
1148                .all(|c| c.color.is_transparent()),
1149        }
1150    }
1151
1152    /// The stops that actually take part in the ramp.
1153    pub fn live_stops(&self) -> &[LinearColorStop] {
1154        &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)]
1155    }
1156
1157    /// Restarts the ramp every period instead of clamping at the ends —
1158    /// `repeating-linear-gradient()` and its radial and conic siblings.
1159    pub fn repeating(mut self, on: bool) -> Self {
1160        set_flag(&mut self.flags, BG_REPEATING, on);
1161        self
1162    }
1163
1164    /// Evaluates the gradient inside one tile and paves the box with copies of
1165    /// it — CSS's `background-size` + `background-position` +
1166    /// `background-repeat`.
1167    ///
1168    /// Each of the four numbers is a length in pixels unless its `*_fraction`
1169    /// flag is set, when a SIZE is a fraction of the box and an OFFSET is a
1170    /// fraction of the space the tile leaves in it (which is what a percentage
1171    /// `background-position` means). A zero or negative size clears the tiling.
1172    pub fn tiled(
1173        mut self,
1174        size: (f32, f32),
1175        size_fraction: (bool, bool),
1176        offset: (f32, f32),
1177        offset_fraction: (bool, bool),
1178        repeat: (bool, bool),
1179    ) -> Self {
1180        let on = size.0 > 0.0 && size.1 > 0.0;
1181        set_flag(&mut self.flags, BG_TILED, on);
1182        set_flag(&mut self.flags, BG_NO_REPEAT_X, on && !repeat.0);
1183        set_flag(&mut self.flags, BG_NO_REPEAT_Y, on && !repeat.1);
1184        set_flag(&mut self.flags, BG_TILE_W_FRACTION, on && size_fraction.0);
1185        set_flag(&mut self.flags, BG_TILE_H_FRACTION, on && size_fraction.1);
1186        set_flag(&mut self.flags, BG_TILE_X_FRACTION, on && offset_fraction.0);
1187        set_flag(&mut self.flags, BG_TILE_Y_FRACTION, on && offset_fraction.1);
1188        self.tile = if on {
1189            [size.0, size.1, offset.0, offset.1]
1190        } else {
1191            [0.0; 4]
1192        };
1193        self
1194    }
1195
1196    /// Whether this background is painted as a repeated tile.
1197    pub fn is_tiled(&self) -> bool {
1198        self.flags & BG_TILED != 0
1199    }
1200
1201    /// Aims a linear gradient's line at one of the box's corners the way CSS
1202    /// does — `0` top right, `1` bottom right, `2` bottom left, `3` top left.
1203    /// The angle then depends on the box's aspect ratio, so it is resolved in
1204    /// the shader rather than here.
1205    pub fn to_corner(mut self, corner: u8) -> Self {
1206        set_flag(&mut self.flags, BG_CORNER, true);
1207        self.gradient_angle_or_pattern_height = corner as f32;
1208        self
1209    }
1210
1211    /// Marks stop `index`'s position as an absolute length in pixels along the
1212    /// gradient line rather than a fraction of it.
1213    pub fn stop_in_pixels(mut self, index: usize) -> Self {
1214        if index < GRADIENT_STOPS {
1215            self.flags |= 1 << (BG_STOP_PX_SHIFT + index as u32);
1216        }
1217        self
1218    }
1219
1220    /// Places stop `index` at `fraction` of the gradient line plus `pixels`,
1221    /// both kept at half precision.
1222    pub fn stop_at_calc(mut self, index: usize, fraction: f32, pixels: f32) -> Self {
1223        if index < GRADIENT_STOPS {
1224            let bits = (u32::from(f16_bits(fraction)) << 16) | u32::from(f16_bits(pixels));
1225            self.colors[index].percentage = f32::from_bits(bits);
1226            self.flags &= !(1 << (BG_STOP_PX_SHIFT + index as u32));
1227            self.flags |= 1 << (BG_STOP_CALC_SHIFT + index as u32);
1228        }
1229        self
1230    }
1231
1232    /// Moves a radial or conic gradient's centre — `at <position>`. The pair is
1233    /// a fraction of the box unless `in_pixels`, when it is an offset from the
1234    /// box's top left corner.
1235    pub fn at(mut self, center: (f32, f32), in_pixels: bool) -> Self {
1236        self.params[0] = center.0;
1237        self.params[1] = center.1;
1238        set_flag(&mut self.flags, BG_CENTER_PX, in_pixels);
1239        self
1240    }
1241
1242    /// Gives a radial gradient explicit radii — a fraction of the box unless
1243    /// `in_pixels`. Replaces any [`Background::with_extent`].
1244    pub fn with_radii(mut self, radii: (f32, f32), in_pixels: bool) -> Self {
1245        self.params[2] = radii.0.max(0.0);
1246        self.params[3] = radii.1.max(0.0);
1247        set_flag(&mut self.flags, BG_RADIUS_PX, in_pixels);
1248        self
1249    }
1250
1251    /// Sizes a radial gradient by one of CSS's four extent keywords: `keyword`
1252    /// is 1 `closest-side`, 2 `farthest-side`, 3 `closest-corner`, 4
1253    /// `farthest-corner`. Replaces any [`Background::with_radii`].
1254    pub fn with_extent(mut self, keyword: u8, ellipse: bool) -> Self {
1255        self.params[2] = -(keyword.clamp(1, 4) as f32);
1256        self.params[3] = if ellipse { 1.0 } else { 0.0 };
1257        set_flag(&mut self.flags, BG_RADIUS_PX, false);
1258        self
1259    }
1260
1261    /// Replaces the colour stops, keeping every other property. Stops beyond
1262    /// [`GRADIENT_STOPS`] are thinned from the middle.
1263    pub fn with_stops(mut self, stops: &[LinearColorStop]) -> Self {
1264        let replacement = gradient_with_stops(self.tag, 0.0, stops);
1265        self.colors = replacement.colors;
1266        self.stop_count = replacement.stop_count;
1267        // A stop list is packed together with its units, so any previous
1268        // per-stop pixel flags belong to the list being replaced.
1269        self.flags &= !(0xffu32 << BG_STOP_PX_SHIFT) & !(0xffu32 << BG_STOP_CALC_SHIFT);
1270        self
1271    }
1272}
1273
1274fn set_flag(flags: &mut u32, bit: u32, on: bool) {
1275    if on {
1276        *flags |= bit;
1277    } else {
1278        *flags &= !bit;
1279    }
1280}
1281
1282impl From<Hsla> for Background {
1283    fn from(value: Hsla) -> Self {
1284        Background {
1285            tag: BackgroundTag::Solid,
1286            solid: value,
1287            ..Default::default()
1288        }
1289    }
1290}
1291
1292impl From<Rgba> for Background {
1293    fn from(value: Rgba) -> Self {
1294        Background {
1295            tag: BackgroundTag::Solid,
1296            solid: Hsla::from(value),
1297            ..Default::default()
1298        }
1299    }
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304    use serde_json::json;
1305
1306    use super::*;
1307
1308    #[test]
1309    fn f16_bits_rounds_to_nearest_and_clamps() {
1310        let cases = [
1311            (1.0, 0x3c00),
1312            (0.5, 0x3800),
1313            (1.0 / 3.0, 0x3555),
1314            (-200.0, 0xda40),
1315            (1e-6, 0x0011),
1316            (70000.0, 0x7bff),
1317            (-70000.0, 0xfbff),
1318        ];
1319        for (value, bits) in cases {
1320            assert_eq!(f16_bits(value), bits, "{value}");
1321        }
1322    }
1323
1324    #[test]
1325    fn test_deserialize_three_value_hex_to_rgba() {
1326        let actual: Rgba = serde_json::from_value(json!("#f09")).unwrap();
1327
1328        assert_eq!(actual, rgba(0xff0099ff))
1329    }
1330
1331    #[test]
1332    fn test_deserialize_four_value_hex_to_rgba() {
1333        let actual: Rgba = serde_json::from_value(json!("#f09f")).unwrap();
1334
1335        assert_eq!(actual, rgba(0xff0099ff))
1336    }
1337
1338    #[test]
1339    fn test_deserialize_six_value_hex_to_rgba() {
1340        let actual: Rgba = serde_json::from_value(json!("#ff0099")).unwrap();
1341
1342        assert_eq!(actual, rgba(0xff0099ff))
1343    }
1344
1345    #[test]
1346    fn test_deserialize_eight_value_hex_to_rgba() {
1347        let actual: Rgba = serde_json::from_value(json!("#ff0099ff")).unwrap();
1348
1349        assert_eq!(actual, rgba(0xff0099ff))
1350    }
1351
1352    #[test]
1353    fn test_deserialize_eight_value_hex_with_padding_to_rgba() {
1354        let actual: Rgba = serde_json::from_value(json!(" #f5f5f5ff   ")).unwrap();
1355
1356        assert_eq!(actual, rgba(0xf5f5f5ff))
1357    }
1358
1359    #[test]
1360    fn test_deserialize_eight_value_hex_with_mixed_case_to_rgba() {
1361        let actual: Rgba = serde_json::from_value(json!("#DeAdbEeF")).unwrap();
1362
1363        assert_eq!(actual, rgba(0xdeadbeef))
1364    }
1365
1366    #[test]
1367    fn test_background_solid() {
1368        let color = Hsla::from(rgba(0xff0099ff));
1369        let mut background = Background::from(color);
1370        assert_eq!(background.tag, BackgroundTag::Solid);
1371        assert_eq!(background.solid, color);
1372
1373        assert_eq!(background.opacity(0.5).solid, color.opacity(0.5));
1374        assert!(!background.is_transparent());
1375        background.solid = hsla(0.0, 0.0, 0.0, 0.0);
1376        assert!(background.is_transparent());
1377    }
1378
1379    #[test]
1380    fn test_background_linear_gradient() {
1381        let from = linear_color_stop(rgba(0xff0099ff), 0.0);
1382        let to = linear_color_stop(rgba(0x00ff99ff), 1.0);
1383        let background = linear_gradient(90.0, from, to);
1384        assert_eq!(background.tag, BackgroundTag::LinearGradient);
1385        assert_eq!(background.colors[0], from);
1386        assert_eq!(background.colors[1], to);
1387
1388        assert_eq!(background.opacity(0.5).colors[0], from.opacity(0.5));
1389        assert_eq!(background.opacity(0.5).colors[1], to.opacity(0.5));
1390        assert!(!background.is_transparent());
1391        assert!(background.opacity(0.0).is_transparent());
1392    }
1393
1394    #[test]
1395    fn test_rgba_alpha() {
1396        let color = Rgba {
1397            r: 0.2,
1398            g: 0.6,
1399            b: 1.0,
1400            a: 0.8,
1401        };
1402
1403        assert_eq!(color.alpha(0.25).a, 0.25);
1404        assert_eq!(color.alpha(1.5).a, 1.0);
1405    }
1406
1407    #[test]
1408    fn test_rgba_opacity() {
1409        let color = Rgba {
1410            r: 0.2,
1411            g: 0.6,
1412            b: 1.0,
1413            a: 0.8,
1414        };
1415        assert!((color.opacity(0.5).a - 0.4).abs() < 1e-6);
1416        assert_eq!(color.opacity(2.0).a, 0.8);
1417    }
1418}