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 PatternSlash = 2,
557}
558
559/// A color space for color interpolation.
560///
561/// References:
562/// - <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
563/// - <https://www.w3.org/TR/css-color-4/#typedef-color-space>
564#[derive(Debug, Clone, Copy, PartialEq, Default)]
565#[repr(C)]
566pub enum ColorSpace {
567 #[default]
568 /// The sRGB color space.
569 Srgb = 0,
570 /// The Oklab color space.
571 Oklab = 1,
572}
573
574impl Display for ColorSpace {
575 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
576 match self {
577 ColorSpace::Srgb => write!(f, "sRGB"),
578 ColorSpace::Oklab => write!(f, "Oklab"),
579 }
580 }
581}
582
583/// A background color, which can be either a solid color or a linear gradient.
584#[derive(Debug, Clone, Copy, PartialEq)]
585#[repr(C)]
586pub struct Background {
587 pub(crate) tag: BackgroundTag,
588 pub(crate) color_space: ColorSpace,
589 pub(crate) solid: Hsla,
590 pub(crate) gradient_angle_or_pattern_height: f32,
591 pub(crate) colors: [LinearColorStop; 2],
592 /// Padding for alignment for repr(C) layout.
593 pad: u32,
594}
595
596impl Eq for Background {}
597impl Default for Background {
598 fn default() -> Self {
599 Self {
600 tag: BackgroundTag::Solid,
601 solid: Hsla::default(),
602 color_space: ColorSpace::default(),
603 gradient_angle_or_pattern_height: 0.0,
604 colors: [LinearColorStop::default(), LinearColorStop::default()],
605 pad: 0,
606 }
607 }
608}
609
610/// Creates a hash pattern background
611pub fn pattern_slash(color: Hsla, thickness: f32) -> Background {
612 Background {
613 tag: BackgroundTag::PatternSlash,
614 solid: color,
615 gradient_angle_or_pattern_height: thickness,
616 ..Default::default()
617 }
618}
619
620/// Creates a LinearGradient background color.
621///
622/// The gradient line's angle of direction. A value of `0.` is equivalent to to top; increasing values rotate clockwise from there.
623///
624/// The `angle` is in degrees value in the range 0.0 to 360.0.
625///
626/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient>
627pub fn linear_gradient(
628 angle: f32,
629 from: impl Into<LinearColorStop>,
630 to: impl Into<LinearColorStop>,
631) -> Background {
632 Background {
633 tag: BackgroundTag::LinearGradient,
634 gradient_angle_or_pattern_height: angle,
635 colors: [from.into(), to.into()],
636 ..Default::default()
637 }
638}
639
640/// A color stop in a linear gradient.
641///
642/// <https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#linear-color-stop>
643#[derive(Debug, Clone, Copy, Default, PartialEq)]
644#[repr(C)]
645pub struct LinearColorStop {
646 /// The color of the color stop.
647 pub color: Hsla,
648 /// The percentage of the gradient, in the range 0.0 to 1.0.
649 pub percentage: f32,
650}
651
652/// Creates a new linear color stop.
653///
654/// The percentage of the gradient, in the range 0.0 to 1.0.
655pub fn linear_color_stop(color: impl Into<Hsla>, percentage: f32) -> LinearColorStop {
656 LinearColorStop {
657 color: color.into(),
658 percentage,
659 }
660}
661
662impl LinearColorStop {
663 /// Returns a new color stop with the same color, but with a modified alpha value.
664 pub fn opacity(&self, factor: f32) -> Self {
665 Self {
666 percentage: self.percentage,
667 color: self.color.opacity(factor),
668 }
669 }
670}
671
672impl Background {
673 /// Use specified color space for color interpolation.
674 ///
675 /// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-method>
676 pub fn color_space(mut self, color_space: ColorSpace) -> Self {
677 self.color_space = color_space;
678 self
679 }
680
681 /// Returns a new background color with the same hue, saturation, and lightness, but with a modified alpha value.
682 pub fn opacity(&self, factor: f32) -> Self {
683 let mut background = *self;
684 background.solid = background.solid.opacity(factor);
685 background.colors = [
686 self.colors[0].opacity(factor),
687 self.colors[1].opacity(factor),
688 ];
689 background
690 }
691
692 /// Returns whether the background color is transparent.
693 pub fn is_transparent(&self) -> bool {
694 match self.tag {
695 BackgroundTag::Solid => self.solid.is_transparent(),
696 BackgroundTag::LinearGradient => self.colors.iter().all(|c| c.color.is_transparent()),
697 BackgroundTag::PatternSlash => self.solid.is_transparent(),
698 }
699 }
700}
701
702impl From<Hsla> for Background {
703 fn from(value: Hsla) -> Self {
704 Background {
705 tag: BackgroundTag::Solid,
706 solid: value,
707 ..Default::default()
708 }
709 }
710}
711impl From<Rgba> for Background {
712 fn from(value: Rgba) -> Self {
713 Background {
714 tag: BackgroundTag::Solid,
715 solid: Hsla::from(value),
716 ..Default::default()
717 }
718 }
719}
720
721#[cfg(test)]
722mod tests {
723 use serde_json::json;
724
725 use super::*;
726
727 #[test]
728 fn test_deserialize_three_value_hex_to_rgba() {
729 let actual: Rgba = serde_json::from_value(json!("#f09")).unwrap();
730
731 assert_eq!(actual, rgba(0xff0099ff))
732 }
733
734 #[test]
735 fn test_deserialize_four_value_hex_to_rgba() {
736 let actual: Rgba = serde_json::from_value(json!("#f09f")).unwrap();
737
738 assert_eq!(actual, rgba(0xff0099ff))
739 }
740
741 #[test]
742 fn test_deserialize_six_value_hex_to_rgba() {
743 let actual: Rgba = serde_json::from_value(json!("#ff0099")).unwrap();
744
745 assert_eq!(actual, rgba(0xff0099ff))
746 }
747
748 #[test]
749 fn test_deserialize_eight_value_hex_to_rgba() {
750 let actual: Rgba = serde_json::from_value(json!("#ff0099ff")).unwrap();
751
752 assert_eq!(actual, rgba(0xff0099ff))
753 }
754
755 #[test]
756 fn test_deserialize_eight_value_hex_with_padding_to_rgba() {
757 let actual: Rgba = serde_json::from_value(json!(" #f5f5f5ff ")).unwrap();
758
759 assert_eq!(actual, rgba(0xf5f5f5ff))
760 }
761
762 #[test]
763 fn test_deserialize_eight_value_hex_with_mixed_case_to_rgba() {
764 let actual: Rgba = serde_json::from_value(json!("#DeAdbEeF")).unwrap();
765
766 assert_eq!(actual, rgba(0xdeadbeef))
767 }
768
769 #[test]
770 fn test_background_solid() {
771 let color = Hsla::from(rgba(0xff0099ff));
772 let mut background = Background::from(color);
773 assert_eq!(background.tag, BackgroundTag::Solid);
774 assert_eq!(background.solid, color);
775
776 assert_eq!(background.opacity(0.5).solid, color.opacity(0.5));
777 assert_eq!(background.is_transparent(), false);
778 background.solid = hsla(0.0, 0.0, 0.0, 0.0);
779 assert_eq!(background.is_transparent(), true);
780 }
781
782 #[test]
783 fn test_background_linear_gradient() {
784 let from = linear_color_stop(rgba(0xff0099ff), 0.0);
785 let to = linear_color_stop(rgba(0x00ff99ff), 1.0);
786 let background = linear_gradient(90.0, from, to);
787 assert_eq!(background.tag, BackgroundTag::LinearGradient);
788 assert_eq!(background.colors[0], from);
789 assert_eq!(background.colors[1], to);
790
791 assert_eq!(background.opacity(0.5).colors[0], from.opacity(0.5));
792 assert_eq!(background.opacity(0.5).colors[1], to.opacity(0.5));
793 assert_eq!(background.is_transparent(), false);
794 assert_eq!(background.opacity(0.0).is_transparent(), true);
795 }
796}