color.rs

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