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
823/// A color space for color interpolation.
824///
825/// References:
826/// - <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
827/// - <https://www.w3.org/TR/css-color-4/#typedef-color-space>
828#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
829#[cfg_attr(feature = "schemars", derive(JsonSchema))]
830#[repr(C)]
831pub enum ColorSpace {
832    #[default]
833    /// The sRGB color space.
834    Srgb = 0,
835    /// The Oklab color space.
836    Oklab = 1,
837}
838
839impl Display for ColorSpace {
840    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
841        match self {
842            ColorSpace::Srgb => write!(f, "sRGB"),
843            ColorSpace::Oklab => write!(f, "Oklab"),
844        }
845    }
846}
847
848/// A background: a solid colour, one of the two procedural patterns, or a
849/// linear / radial / conic gradient of up to [`GRADIENT_STOPS`] stops,
850/// optionally repeating and optionally tiled across the box.
851///
852/// The layout is the GPU layout — see the `Quad` word map in `scene.rs` and the
853/// hand-mirrored `struct Background` in each backend's shader. Adding a field
854/// here is a six-file change; the checklist is on `Quad`.
855#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
856#[cfg_attr(feature = "schemars", derive(JsonSchema))]
857#[repr(C)]
858pub struct Background {
859    pub(crate) tag: BackgroundTag,
860    pub(crate) color_space: ColorSpace,
861    pub(crate) solid: Hsla,
862    /// The gradient line's angle in degrees for a linear gradient (or a corner
863    /// index when [`BG_CORNER`] is set), the start angle for a conic gradient,
864    /// and the pattern period for the two procedural tags.
865    pub(crate) gradient_angle_or_pattern_height: f32,
866    pub(crate) colors: [LinearColorStop; GRADIENT_STOPS],
867    /// How many of `colors` are live. Zero for a non-gradient tag.
868    pub(crate) stop_count: u32,
869    /// `BG_*` bits above.
870    pub(crate) flags: u32,
871    /// Radial: `[cx, cy, rx, ry]`. The centre is a FRACTION of the box; the
872    /// radii are fractions too when `rx >= 0`, and when `rx < 0` the pair is an
873    /// extent keyword instead — `-rx` is 1 `closest-side`, 2 `farthest-side`,
874    /// 3 `closest-corner`, 4 `farthest-corner`, and `ry` is 0 for a circle and
875    /// 1 for an ellipse. Conic: `[cx, cy, _, _]`. Unused otherwise.
876    pub(crate) params: [f32; 4],
877    /// `[width, height, offset_x, offset_y]` in pixels when [`BG_TILED`] is
878    /// set: `background-size` and `background-position`.
879    pub(crate) tile: [f32; 4],
880}
881
882impl std::fmt::Debug for Background {
883    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
884        let stops = &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)];
885        match self.tag {
886            BackgroundTag::Solid => write!(f, "Solid({:?})", self.solid),
887            BackgroundTag::LinearGradient => write!(
888                f,
889                "LinearGradient({}, {:?}, flags {:#x}, tile {:?})",
890                self.gradient_angle_or_pattern_height, stops, self.flags, self.tile
891            ),
892            BackgroundTag::RadialGradient => write!(
893                f,
894                "RadialGradient({:?}, {:?}, flags {:#x}, tile {:?})",
895                self.params, stops, self.flags, self.tile
896            ),
897            BackgroundTag::ConicGradient => write!(
898                f,
899                "ConicGradient({}, {:?}, {:?}, flags {:#x}, tile {:?})",
900                self.gradient_angle_or_pattern_height, self.params, stops, self.flags, self.tile
901            ),
902            BackgroundTag::PatternSlash => write!(
903                f,
904                "PatternSlash({:?}, {})",
905                self.solid, self.gradient_angle_or_pattern_height
906            ),
907            BackgroundTag::Checkerboard => write!(
908                f,
909                "Checkerboard({:?}, {})",
910                self.solid, self.gradient_angle_or_pattern_height
911            ),
912        }
913    }
914}
915
916impl Eq for Background {}
917impl Default for Background {
918    fn default() -> Self {
919        Self {
920            tag: BackgroundTag::Solid,
921            solid: Hsla::default(),
922            color_space: ColorSpace::default(),
923            gradient_angle_or_pattern_height: 0.0,
924            colors: [LinearColorStop::default(); GRADIENT_STOPS],
925            stop_count: 0,
926            flags: 0,
927            params: [0.0; 4],
928            tile: [0.0; 4],
929        }
930    }
931}
932
933/// Creates a hash pattern background
934pub fn pattern_slash(color: impl Into<Hsla>, width: f32, interval: f32) -> Background {
935    let width_scaled = (width * 255.0) as u32;
936    let interval_scaled = (interval * 255.0) as u32;
937    let height = ((width_scaled * 0xFFFF) + interval_scaled) as f32;
938
939    Background {
940        tag: BackgroundTag::PatternSlash,
941        solid: color.into(),
942        gradient_angle_or_pattern_height: height,
943        ..Default::default()
944    }
945}
946
947/// Creates a checkerboard pattern background
948pub fn checkerboard(color: impl Into<Hsla>, size: f32) -> Background {
949    Background {
950        tag: BackgroundTag::Checkerboard,
951        solid: color.into(),
952        gradient_angle_or_pattern_height: size,
953        ..Default::default()
954    }
955}
956
957/// Creates a solid background color.
958pub fn solid_background(color: impl Into<Hsla>) -> Background {
959    Background {
960        solid: color.into(),
961        ..Default::default()
962    }
963}
964
965/// Creates a LinearGradient background color.
966///
967/// The gradient line's angle of direction. A value of `0.` is equivalent to top; increasing values rotate clockwise from there.
968///
969/// The `angle` is in degrees value in the range 0.0 to 360.0.
970///
971/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient>
972pub fn linear_gradient(
973    angle: f32,
974    from: impl Into<LinearColorStop>,
975    to: impl Into<LinearColorStop>,
976) -> Background {
977    gradient_with_stops(
978        BackgroundTag::LinearGradient,
979        angle,
980        &[from.into(), to.into()],
981    )
982}
983
984/// A linear gradient with up to [`GRADIENT_STOPS`] stops. Extra stops are
985/// dropped from the middle rather than the ends, so the ramp always starts and
986/// finishes on the colours the caller asked for.
987pub fn linear_gradient_stops(angle: f32, stops: &[LinearColorStop]) -> Background {
988    gradient_with_stops(BackgroundTag::LinearGradient, angle, stops)
989}
990
991/// A radial gradient, centred on the box and reaching its farthest corner —
992/// CSS's defaults. [`Background::at`], [`Background::with_radii`] and
993/// [`Background::with_extent`] change each of those.
994pub fn radial_gradient(stops: &[LinearColorStop]) -> Background {
995    let mut background = gradient_with_stops(BackgroundTag::RadialGradient, 0.0, stops);
996    background.params = [0.5, 0.5, -4.0, 1.0];
997    background
998}
999
1000/// A conic gradient. `from_angle` is in degrees clockwise from twelve o'clock;
1001/// the centre defaults to the middle of the box.
1002pub fn conic_gradient(from_angle: f32, stops: &[LinearColorStop]) -> Background {
1003    let mut background = gradient_with_stops(BackgroundTag::ConicGradient, from_angle, stops);
1004    background.params = [0.5, 0.5, 0.0, 0.0];
1005    background
1006}
1007
1008fn gradient_with_stops(tag: BackgroundTag, angle: f32, stops: &[LinearColorStop]) -> Background {
1009    let mut colors = [LinearColorStop::default(); GRADIENT_STOPS];
1010    let n = stops.len().min(GRADIENT_STOPS);
1011    if stops.len() <= GRADIENT_STOPS {
1012        colors[..n].copy_from_slice(&stops[..n]);
1013    } else {
1014        // Keep both ends and spread the rest evenly through the middle. A
1015        // caller that cannot afford the loss splits into bands instead.
1016        colors[0] = stops[0];
1017        colors[GRADIENT_STOPS - 1] = stops[stops.len() - 1];
1018        for (i, slot) in colors[1..GRADIENT_STOPS - 1].iter_mut().enumerate() {
1019            let t = (i + 1) as f32 / (GRADIENT_STOPS - 1) as f32;
1020            *slot = stops[((t * (stops.len() - 1) as f32).round() as usize).min(stops.len() - 1)];
1021        }
1022    }
1023    Background {
1024        tag,
1025        gradient_angle_or_pattern_height: angle,
1026        colors,
1027        stop_count: n as u32,
1028        ..Default::default()
1029    }
1030}
1031
1032/// A color stop in a linear gradient.
1033///
1034/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#linear-color-stop>
1035#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1036#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1037#[repr(C)]
1038pub struct LinearColorStop {
1039    /// The color of the color stop.
1040    pub color: Hsla,
1041    /// The percentage of the gradient, in the range 0.0 to 1.0.
1042    pub percentage: f32,
1043}
1044
1045/// Creates a new linear color stop.
1046///
1047/// The percentage of the gradient, in the range 0.0 to 1.0.
1048pub fn linear_color_stop(color: impl Into<Hsla>, percentage: f32) -> LinearColorStop {
1049    LinearColorStop {
1050        color: color.into(),
1051        percentage,
1052    }
1053}
1054
1055impl LinearColorStop {
1056    /// Returns a new color stop with the same color, but with a modified alpha value.
1057    pub fn opacity(&self, factor: f32) -> Self {
1058        Self {
1059            percentage: self.percentage,
1060            color: self.color.opacity(factor),
1061        }
1062    }
1063}
1064
1065impl Background {
1066    /// Returns the solid color if this is a solid background, None otherwise.
1067    pub fn as_solid(&self) -> Option<Hsla> {
1068        if self.tag == BackgroundTag::Solid {
1069            Some(self.solid)
1070        } else {
1071            None
1072        }
1073    }
1074
1075    /// vue-native fork: this background, painted only in the border area of
1076    /// the quad it fills ([`BG_RING`]).
1077    pub(crate) fn ring(mut self) -> Self {
1078        self.flags |= BG_RING;
1079        self
1080    }
1081
1082    /// vue-native fork: whether this is a [`Self::ring`] background.
1083    pub(crate) fn is_ring(&self) -> bool {
1084        self.flags & BG_RING != 0
1085    }
1086
1087    /// Use specified color space for color interpolation.
1088    ///
1089    /// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
1090    pub fn color_space(mut self, color_space: ColorSpace) -> Self {
1091        self.color_space = color_space;
1092        self
1093    }
1094
1095    /// Returns a new background color with the same hue, saturation, and lightness, but with a modified alpha value.
1096    pub fn opacity(&self, factor: f32) -> Self {
1097        let mut background = *self;
1098        background.solid = background.solid.opacity(factor);
1099        for stop in &mut background.colors {
1100            *stop = stop.opacity(factor);
1101        }
1102        background
1103    }
1104
1105    /// Returns whether the background color is transparent.
1106    pub fn is_transparent(&self) -> bool {
1107        match self.tag {
1108            BackgroundTag::Solid | BackgroundTag::PatternSlash | BackgroundTag::Checkerboard => {
1109                self.solid.is_transparent()
1110            }
1111            BackgroundTag::LinearGradient
1112            | BackgroundTag::RadialGradient
1113            | BackgroundTag::ConicGradient => self.live_stops()
1114                .iter()
1115                .all(|c| c.color.is_transparent()),
1116        }
1117    }
1118
1119    /// The stops that actually take part in the ramp.
1120    pub fn live_stops(&self) -> &[LinearColorStop] {
1121        &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)]
1122    }
1123
1124    /// Restarts the ramp every period instead of clamping at the ends —
1125    /// `repeating-linear-gradient()` and its radial and conic siblings.
1126    pub fn repeating(mut self, on: bool) -> Self {
1127        set_flag(&mut self.flags, BG_REPEATING, on);
1128        self
1129    }
1130
1131    /// Evaluates the gradient inside one tile and paves the box with copies of
1132    /// it — CSS's `background-size` + `background-position` +
1133    /// `background-repeat`.
1134    ///
1135    /// Each of the four numbers is a length in pixels unless its `*_fraction`
1136    /// flag is set, when a SIZE is a fraction of the box and an OFFSET is a
1137    /// fraction of the space the tile leaves in it (which is what a percentage
1138    /// `background-position` means). A zero or negative size clears the tiling.
1139    pub fn tiled(
1140        mut self,
1141        size: (f32, f32),
1142        size_fraction: (bool, bool),
1143        offset: (f32, f32),
1144        offset_fraction: (bool, bool),
1145        repeat: (bool, bool),
1146    ) -> Self {
1147        let on = size.0 > 0.0 && size.1 > 0.0;
1148        set_flag(&mut self.flags, BG_TILED, on);
1149        set_flag(&mut self.flags, BG_NO_REPEAT_X, on && !repeat.0);
1150        set_flag(&mut self.flags, BG_NO_REPEAT_Y, on && !repeat.1);
1151        set_flag(&mut self.flags, BG_TILE_W_FRACTION, on && size_fraction.0);
1152        set_flag(&mut self.flags, BG_TILE_H_FRACTION, on && size_fraction.1);
1153        set_flag(&mut self.flags, BG_TILE_X_FRACTION, on && offset_fraction.0);
1154        set_flag(&mut self.flags, BG_TILE_Y_FRACTION, on && offset_fraction.1);
1155        self.tile = if on {
1156            [size.0, size.1, offset.0, offset.1]
1157        } else {
1158            [0.0; 4]
1159        };
1160        self
1161    }
1162
1163    /// Whether this background is painted as a repeated tile.
1164    pub fn is_tiled(&self) -> bool {
1165        self.flags & BG_TILED != 0
1166    }
1167
1168    /// Aims a linear gradient's line at one of the box's corners the way CSS
1169    /// does — `0` top right, `1` bottom right, `2` bottom left, `3` top left.
1170    /// The angle then depends on the box's aspect ratio, so it is resolved in
1171    /// the shader rather than here.
1172    pub fn to_corner(mut self, corner: u8) -> Self {
1173        set_flag(&mut self.flags, BG_CORNER, true);
1174        self.gradient_angle_or_pattern_height = corner as f32;
1175        self
1176    }
1177
1178    /// Marks stop `index`'s position as an absolute length in pixels along the
1179    /// gradient line rather than a fraction of it.
1180    pub fn stop_in_pixels(mut self, index: usize) -> Self {
1181        if index < GRADIENT_STOPS {
1182            self.flags |= 1 << (BG_STOP_PX_SHIFT + index as u32);
1183        }
1184        self
1185    }
1186
1187    /// Moves a radial or conic gradient's centre — `at <position>`. The pair is
1188    /// a fraction of the box unless `in_pixels`, when it is an offset from the
1189    /// box's top left corner.
1190    pub fn at(mut self, center: (f32, f32), in_pixels: bool) -> Self {
1191        self.params[0] = center.0;
1192        self.params[1] = center.1;
1193        set_flag(&mut self.flags, BG_CENTER_PX, in_pixels);
1194        self
1195    }
1196
1197    /// Gives a radial gradient explicit radii — a fraction of the box unless
1198    /// `in_pixels`. Replaces any [`Background::with_extent`].
1199    pub fn with_radii(mut self, radii: (f32, f32), in_pixels: bool) -> Self {
1200        self.params[2] = radii.0.max(0.0);
1201        self.params[3] = radii.1.max(0.0);
1202        set_flag(&mut self.flags, BG_RADIUS_PX, in_pixels);
1203        self
1204    }
1205
1206    /// Sizes a radial gradient by one of CSS's four extent keywords: `keyword`
1207    /// is 1 `closest-side`, 2 `farthest-side`, 3 `closest-corner`, 4
1208    /// `farthest-corner`. Replaces any [`Background::with_radii`].
1209    pub fn with_extent(mut self, keyword: u8, ellipse: bool) -> Self {
1210        self.params[2] = -(keyword.clamp(1, 4) as f32);
1211        self.params[3] = if ellipse { 1.0 } else { 0.0 };
1212        set_flag(&mut self.flags, BG_RADIUS_PX, false);
1213        self
1214    }
1215
1216    /// Replaces the colour stops, keeping every other property. Stops beyond
1217    /// [`GRADIENT_STOPS`] are thinned from the middle.
1218    pub fn with_stops(mut self, stops: &[LinearColorStop]) -> Self {
1219        let replacement = gradient_with_stops(self.tag, 0.0, stops);
1220        self.colors = replacement.colors;
1221        self.stop_count = replacement.stop_count;
1222        // A stop list is packed together with its units, so any previous
1223        // per-stop pixel flags belong to the list being replaced.
1224        self.flags &= !(0xffu32 << BG_STOP_PX_SHIFT);
1225        self
1226    }
1227}
1228
1229fn set_flag(flags: &mut u32, bit: u32, on: bool) {
1230    if on {
1231        *flags |= bit;
1232    } else {
1233        *flags &= !bit;
1234    }
1235}
1236
1237impl From<Hsla> for Background {
1238    fn from(value: Hsla) -> Self {
1239        Background {
1240            tag: BackgroundTag::Solid,
1241            solid: value,
1242            ..Default::default()
1243        }
1244    }
1245}
1246
1247impl From<Rgba> for Background {
1248    fn from(value: Rgba) -> Self {
1249        Background {
1250            tag: BackgroundTag::Solid,
1251            solid: Hsla::from(value),
1252            ..Default::default()
1253        }
1254    }
1255}
1256
1257#[cfg(test)]
1258mod tests {
1259    use serde_json::json;
1260
1261    use super::*;
1262
1263    #[test]
1264    fn test_deserialize_three_value_hex_to_rgba() {
1265        let actual: Rgba = serde_json::from_value(json!("#f09")).unwrap();
1266
1267        assert_eq!(actual, rgba(0xff0099ff))
1268    }
1269
1270    #[test]
1271    fn test_deserialize_four_value_hex_to_rgba() {
1272        let actual: Rgba = serde_json::from_value(json!("#f09f")).unwrap();
1273
1274        assert_eq!(actual, rgba(0xff0099ff))
1275    }
1276
1277    #[test]
1278    fn test_deserialize_six_value_hex_to_rgba() {
1279        let actual: Rgba = serde_json::from_value(json!("#ff0099")).unwrap();
1280
1281        assert_eq!(actual, rgba(0xff0099ff))
1282    }
1283
1284    #[test]
1285    fn test_deserialize_eight_value_hex_to_rgba() {
1286        let actual: Rgba = serde_json::from_value(json!("#ff0099ff")).unwrap();
1287
1288        assert_eq!(actual, rgba(0xff0099ff))
1289    }
1290
1291    #[test]
1292    fn test_deserialize_eight_value_hex_with_padding_to_rgba() {
1293        let actual: Rgba = serde_json::from_value(json!(" #f5f5f5ff   ")).unwrap();
1294
1295        assert_eq!(actual, rgba(0xf5f5f5ff))
1296    }
1297
1298    #[test]
1299    fn test_deserialize_eight_value_hex_with_mixed_case_to_rgba() {
1300        let actual: Rgba = serde_json::from_value(json!("#DeAdbEeF")).unwrap();
1301
1302        assert_eq!(actual, rgba(0xdeadbeef))
1303    }
1304
1305    #[test]
1306    fn test_background_solid() {
1307        let color = Hsla::from(rgba(0xff0099ff));
1308        let mut background = Background::from(color);
1309        assert_eq!(background.tag, BackgroundTag::Solid);
1310        assert_eq!(background.solid, color);
1311
1312        assert_eq!(background.opacity(0.5).solid, color.opacity(0.5));
1313        assert!(!background.is_transparent());
1314        background.solid = hsla(0.0, 0.0, 0.0, 0.0);
1315        assert!(background.is_transparent());
1316    }
1317
1318    #[test]
1319    fn test_background_linear_gradient() {
1320        let from = linear_color_stop(rgba(0xff0099ff), 0.0);
1321        let to = linear_color_stop(rgba(0x00ff99ff), 1.0);
1322        let background = linear_gradient(90.0, from, to);
1323        assert_eq!(background.tag, BackgroundTag::LinearGradient);
1324        assert_eq!(background.colors[0], from);
1325        assert_eq!(background.colors[1], to);
1326
1327        assert_eq!(background.opacity(0.5).colors[0], from.opacity(0.5));
1328        assert_eq!(background.opacity(0.5).colors[1], to.opacity(0.5));
1329        assert!(!background.is_transparent());
1330        assert!(background.opacity(0.0).is_transparent());
1331    }
1332
1333    #[test]
1334    fn test_rgba_alpha() {
1335        let color = Rgba {
1336            r: 0.2,
1337            g: 0.6,
1338            b: 1.0,
1339            a: 0.8,
1340        };
1341
1342        assert_eq!(color.alpha(0.25).a, 0.25);
1343        assert_eq!(color.alpha(1.5).a, 1.0);
1344    }
1345
1346    #[test]
1347    fn test_rgba_opacity() {
1348        let color = Rgba {
1349            r: 0.2,
1350            g: 0.6,
1351            b: 1.0,
1352            a: 0.8,
1353        };
1354        assert!((color.opacity(0.5).a - 0.4).abs() < 1e-6);
1355        assert_eq!(color.opacity(2.0).a, 0.8);
1356    }
1357}