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
15pub 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
21pub 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
27pub 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#[derive(PartialEq, Clone, Copy, Default)]
40#[repr(C)]
41pub struct Rgba {
42 pub r: f32,
44 pub g: f32,
46 pub b: f32,
48 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 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 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 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 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#[derive(Default, Copy, Clone, Debug)]
336#[repr(C)]
337pub struct Hsla {
338 pub h: f32,
340
341 pub s: f32,
343
344 pub l: f32,
346
347 pub a: f32,
349}
350
351#[cfg(feature = "proptest")]
352mod property {
353 use super::Hsla;
354 use proptest::prelude::*;
355
356 impl Hsla {
357 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
426pub 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
436pub const fn black() -> Hsla {
438 Hsla {
439 h: 0.,
440 s: 0.,
441 l: 0.,
442 a: 1.,
443 }
444}
445
446pub const fn transparent_black() -> Hsla {
448 Hsla {
449 h: 0.,
450 s: 0.,
451 l: 0.,
452 a: 0.,
453 }
454}
455
456pub const fn transparent_white() -> Hsla {
458 Hsla {
459 h: 0.,
460 s: 0.,
461 l: 1.,
462 a: 0.,
463 }
464}
465
466pub 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
476pub const fn white() -> Hsla {
478 Hsla {
479 h: 0.,
480 s: 0.,
481 l: 1.,
482 a: 1.,
483 }
484}
485
486pub const fn red() -> Hsla {
488 Hsla {
489 h: 0.,
490 s: 1.,
491 l: 0.5,
492 a: 1.,
493 }
494}
495
496pub const fn blue() -> Hsla {
498 Hsla {
499 h: 0.6666666667,
500 s: 1.,
501 l: 0.5,
502 a: 1.,
503 }
504}
505
506pub const fn green() -> Hsla {
508 Hsla {
509 h: 0.3333333333,
510 s: 1.,
511 l: 0.25,
512 a: 1.,
513 }
514}
515
516pub 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 pub fn to_rgb(self) -> Rgba {
529 self.into()
530 }
531
532 pub const fn red() -> Self {
534 red()
535 }
536
537 pub const fn green() -> Self {
539 green()
540 }
541
542 pub const fn blue() -> Self {
544 blue()
545 }
546
547 pub const fn black() -> Self {
549 black()
550 }
551
552 pub const fn white() -> Self {
554 white()
555 }
556
557 pub const fn transparent_black() -> Self {
559 transparent_black()
560 }
561
562 pub fn is_transparent(&self) -> bool {
564 self.a == 0.0
565 }
566
567 pub fn is_opaque(&self) -> bool {
569 self.a == 1.0
570 }
571
572 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 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 pub fn fade_out(&mut self, factor: f32) {
611 self.a *= 1.0 - factor.clamp(0., 1.);
612 }
613
614 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 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
759pub const GRADIENT_STOPS: usize = 8;
770
771pub(crate) const BG_REPEATING: u32 = 1 << 0;
774pub(crate) const BG_TILED: u32 = 1 << 1;
777pub(crate) const BG_CORNER: u32 = 1 << 2;
782pub(crate) const BG_NO_REPEAT_X: u32 = 1 << 3;
786pub(crate) const BG_NO_REPEAT_Y: u32 = 1 << 4;
788pub(crate) const BG_CENTER_PX: u32 = 1 << 5;
791pub(crate) const BG_RADIUS_PX: u32 = 1 << 6;
794pub(crate) const BG_TILE_W_FRACTION: u32 = 1 << 7;
797pub(crate) const BG_TILE_H_FRACTION: u32 = 1 << 8;
799pub(crate) const BG_TILE_X_FRACTION: u32 = 1 << 9;
804pub(crate) const BG_TILE_Y_FRACTION: u32 = 1 << 10;
806pub(crate) const BG_RING: u32 = 1 << 11;
816pub(crate) const BG_STOP_PX_SHIFT: u32 = 16;
822
823#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
829#[cfg_attr(feature = "schemars", derive(JsonSchema))]
830#[repr(C)]
831pub enum ColorSpace {
832 #[default]
833 Srgb = 0,
835 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#[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 pub(crate) gradient_angle_or_pattern_height: f32,
866 pub(crate) colors: [LinearColorStop; GRADIENT_STOPS],
867 pub(crate) stop_count: u32,
869 pub(crate) flags: u32,
871 pub(crate) params: [f32; 4],
877 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
933pub 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
947pub 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
957pub fn solid_background(color: impl Into<Hsla>) -> Background {
959 Background {
960 solid: color.into(),
961 ..Default::default()
962 }
963}
964
965pub 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
984pub fn linear_gradient_stops(angle: f32, stops: &[LinearColorStop]) -> Background {
988 gradient_with_stops(BackgroundTag::LinearGradient, angle, stops)
989}
990
991pub 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
1000pub 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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1036#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1037#[repr(C)]
1038pub struct LinearColorStop {
1039 pub color: Hsla,
1041 pub percentage: f32,
1043}
1044
1045pub 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 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 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 pub(crate) fn ring(mut self) -> Self {
1078 self.flags |= BG_RING;
1079 self
1080 }
1081
1082 pub(crate) fn is_ring(&self) -> bool {
1084 self.flags & BG_RING != 0
1085 }
1086
1087 pub fn color_space(mut self, color_space: ColorSpace) -> Self {
1091 self.color_space = color_space;
1092 self
1093 }
1094
1095 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 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 pub fn live_stops(&self) -> &[LinearColorStop] {
1121 &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)]
1122 }
1123
1124 pub fn repeating(mut self, on: bool) -> Self {
1127 set_flag(&mut self.flags, BG_REPEATING, on);
1128 self
1129 }
1130
1131 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 pub fn is_tiled(&self) -> bool {
1165 self.flags & BG_TILED != 0
1166 }
1167
1168 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 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 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 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 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 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 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}