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;
822pub(crate) const BG_STOP_CALC_SHIFT: u32 = 24;
826
827fn f16_bits(v: f32) -> u16 {
830 let x = v.to_bits();
831 let sign = ((x >> 16) & 0x8000) as u16;
832 let exp = ((x >> 23) & 0xff) as i32 - 127 + 15;
833 let man = x & 0x7f_ffff;
834 let round = |bits: u32, shift: u32| {
835 let kept = bits >> shift;
836 let rest = bits & ((1 << shift) - 1);
837 let mid = 1 << (shift - 1);
838 if rest > mid || (rest == mid && kept & 1 == 1) {
839 kept + 1
840 } else {
841 kept
842 }
843 };
844 if !v.is_finite() || exp >= 31 {
845 return sign | 0x7bff;
846 }
847 if exp <= 0 {
848 if exp < -10 {
849 return sign;
850 }
851 return sign | round(man | 0x80_0000, (14 - exp) as u32) as u16;
852 }
853 sign | round(((exp as u32) << 23) | man, 13).min(0x7bff) as u16
854}
855
856#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
862#[cfg_attr(feature = "schemars", derive(JsonSchema))]
863#[repr(C)]
864pub enum ColorSpace {
865 #[default]
866 Srgb = 0,
868 Oklab = 1,
870}
871
872impl Display for ColorSpace {
873 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
874 match self {
875 ColorSpace::Srgb => write!(f, "sRGB"),
876 ColorSpace::Oklab => write!(f, "Oklab"),
877 }
878 }
879}
880
881#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
889#[cfg_attr(feature = "schemars", derive(JsonSchema))]
890#[repr(C)]
891pub struct Background {
892 pub(crate) tag: BackgroundTag,
893 pub(crate) color_space: ColorSpace,
894 pub(crate) solid: Hsla,
895 pub(crate) gradient_angle_or_pattern_height: f32,
899 pub(crate) colors: [LinearColorStop; GRADIENT_STOPS],
900 pub(crate) stop_count: u32,
902 pub(crate) flags: u32,
904 pub(crate) params: [f32; 4],
910 pub(crate) tile: [f32; 4],
913}
914
915impl std::fmt::Debug for Background {
916 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
917 let stops = &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)];
918 match self.tag {
919 BackgroundTag::Solid => write!(f, "Solid({:?})", self.solid),
920 BackgroundTag::LinearGradient => write!(
921 f,
922 "LinearGradient({}, {:?}, flags {:#x}, tile {:?})",
923 self.gradient_angle_or_pattern_height, stops, self.flags, self.tile
924 ),
925 BackgroundTag::RadialGradient => write!(
926 f,
927 "RadialGradient({:?}, {:?}, flags {:#x}, tile {:?})",
928 self.params, stops, self.flags, self.tile
929 ),
930 BackgroundTag::ConicGradient => write!(
931 f,
932 "ConicGradient({}, {:?}, {:?}, flags {:#x}, tile {:?})",
933 self.gradient_angle_or_pattern_height, self.params, stops, self.flags, self.tile
934 ),
935 BackgroundTag::PatternSlash => write!(
936 f,
937 "PatternSlash({:?}, {})",
938 self.solid, self.gradient_angle_or_pattern_height
939 ),
940 BackgroundTag::Checkerboard => write!(
941 f,
942 "Checkerboard({:?}, {})",
943 self.solid, self.gradient_angle_or_pattern_height
944 ),
945 }
946 }
947}
948
949impl Eq for Background {}
950impl Default for Background {
951 fn default() -> Self {
952 Self {
953 tag: BackgroundTag::Solid,
954 solid: Hsla::default(),
955 color_space: ColorSpace::default(),
956 gradient_angle_or_pattern_height: 0.0,
957 colors: [LinearColorStop::default(); GRADIENT_STOPS],
958 stop_count: 0,
959 flags: 0,
960 params: [0.0; 4],
961 tile: [0.0; 4],
962 }
963 }
964}
965
966pub fn pattern_slash(color: impl Into<Hsla>, width: f32, interval: f32) -> Background {
968 let width_scaled = (width * 255.0) as u32;
969 let interval_scaled = (interval * 255.0) as u32;
970 let height = ((width_scaled * 0xFFFF) + interval_scaled) as f32;
971
972 Background {
973 tag: BackgroundTag::PatternSlash,
974 solid: color.into(),
975 gradient_angle_or_pattern_height: height,
976 ..Default::default()
977 }
978}
979
980pub fn checkerboard(color: impl Into<Hsla>, size: f32) -> Background {
982 Background {
983 tag: BackgroundTag::Checkerboard,
984 solid: color.into(),
985 gradient_angle_or_pattern_height: size,
986 ..Default::default()
987 }
988}
989
990pub fn solid_background(color: impl Into<Hsla>) -> Background {
992 Background {
993 solid: color.into(),
994 ..Default::default()
995 }
996}
997
998pub fn linear_gradient(
1006 angle: f32,
1007 from: impl Into<LinearColorStop>,
1008 to: impl Into<LinearColorStop>,
1009) -> Background {
1010 gradient_with_stops(
1011 BackgroundTag::LinearGradient,
1012 angle,
1013 &[from.into(), to.into()],
1014 )
1015}
1016
1017pub fn linear_gradient_stops(angle: f32, stops: &[LinearColorStop]) -> Background {
1021 gradient_with_stops(BackgroundTag::LinearGradient, angle, stops)
1022}
1023
1024pub fn radial_gradient(stops: &[LinearColorStop]) -> Background {
1028 let mut background = gradient_with_stops(BackgroundTag::RadialGradient, 0.0, stops);
1029 background.params = [0.5, 0.5, -4.0, 1.0];
1030 background
1031}
1032
1033pub fn conic_gradient(from_angle: f32, stops: &[LinearColorStop]) -> Background {
1036 let mut background = gradient_with_stops(BackgroundTag::ConicGradient, from_angle, stops);
1037 background.params = [0.5, 0.5, 0.0, 0.0];
1038 background
1039}
1040
1041fn gradient_with_stops(tag: BackgroundTag, angle: f32, stops: &[LinearColorStop]) -> Background {
1042 let mut colors = [LinearColorStop::default(); GRADIENT_STOPS];
1043 let n = stops.len().min(GRADIENT_STOPS);
1044 if stops.len() <= GRADIENT_STOPS {
1045 colors[..n].copy_from_slice(&stops[..n]);
1046 } else {
1047 colors[0] = stops[0];
1050 colors[GRADIENT_STOPS - 1] = stops[stops.len() - 1];
1051 for (i, slot) in colors[1..GRADIENT_STOPS - 1].iter_mut().enumerate() {
1052 let t = (i + 1) as f32 / (GRADIENT_STOPS - 1) as f32;
1053 *slot = stops[((t * (stops.len() - 1) as f32).round() as usize).min(stops.len() - 1)];
1054 }
1055 }
1056 Background {
1057 tag,
1058 gradient_angle_or_pattern_height: angle,
1059 colors,
1060 stop_count: n as u32,
1061 ..Default::default()
1062 }
1063}
1064
1065#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1069#[cfg_attr(feature = "schemars", derive(JsonSchema))]
1070#[repr(C)]
1071pub struct LinearColorStop {
1072 pub color: Hsla,
1074 pub percentage: f32,
1076}
1077
1078pub fn linear_color_stop(color: impl Into<Hsla>, percentage: f32) -> LinearColorStop {
1082 LinearColorStop {
1083 color: color.into(),
1084 percentage,
1085 }
1086}
1087
1088impl LinearColorStop {
1089 pub fn opacity(&self, factor: f32) -> Self {
1091 Self {
1092 percentage: self.percentage,
1093 color: self.color.opacity(factor),
1094 }
1095 }
1096}
1097
1098impl Background {
1099 pub fn as_solid(&self) -> Option<Hsla> {
1101 if self.tag == BackgroundTag::Solid {
1102 Some(self.solid)
1103 } else {
1104 None
1105 }
1106 }
1107
1108 pub(crate) fn ring(mut self) -> Self {
1111 self.flags |= BG_RING;
1112 self
1113 }
1114
1115 pub(crate) fn is_ring(&self) -> bool {
1117 self.flags & BG_RING != 0
1118 }
1119
1120 pub fn color_space(mut self, color_space: ColorSpace) -> Self {
1124 self.color_space = color_space;
1125 self
1126 }
1127
1128 pub fn opacity(&self, factor: f32) -> Self {
1130 let mut background = *self;
1131 background.solid = background.solid.opacity(factor);
1132 for stop in &mut background.colors {
1133 *stop = stop.opacity(factor);
1134 }
1135 background
1136 }
1137
1138 pub fn is_transparent(&self) -> bool {
1140 match self.tag {
1141 BackgroundTag::Solid | BackgroundTag::PatternSlash | BackgroundTag::Checkerboard => {
1142 self.solid.is_transparent()
1143 }
1144 BackgroundTag::LinearGradient
1145 | BackgroundTag::RadialGradient
1146 | BackgroundTag::ConicGradient => self.live_stops()
1147 .iter()
1148 .all(|c| c.color.is_transparent()),
1149 }
1150 }
1151
1152 pub fn live_stops(&self) -> &[LinearColorStop] {
1154 &self.colors[..(self.stop_count as usize).min(GRADIENT_STOPS)]
1155 }
1156
1157 pub fn repeating(mut self, on: bool) -> Self {
1160 set_flag(&mut self.flags, BG_REPEATING, on);
1161 self
1162 }
1163
1164 pub fn tiled(
1173 mut self,
1174 size: (f32, f32),
1175 size_fraction: (bool, bool),
1176 offset: (f32, f32),
1177 offset_fraction: (bool, bool),
1178 repeat: (bool, bool),
1179 ) -> Self {
1180 let on = size.0 > 0.0 && size.1 > 0.0;
1181 set_flag(&mut self.flags, BG_TILED, on);
1182 set_flag(&mut self.flags, BG_NO_REPEAT_X, on && !repeat.0);
1183 set_flag(&mut self.flags, BG_NO_REPEAT_Y, on && !repeat.1);
1184 set_flag(&mut self.flags, BG_TILE_W_FRACTION, on && size_fraction.0);
1185 set_flag(&mut self.flags, BG_TILE_H_FRACTION, on && size_fraction.1);
1186 set_flag(&mut self.flags, BG_TILE_X_FRACTION, on && offset_fraction.0);
1187 set_flag(&mut self.flags, BG_TILE_Y_FRACTION, on && offset_fraction.1);
1188 self.tile = if on {
1189 [size.0, size.1, offset.0, offset.1]
1190 } else {
1191 [0.0; 4]
1192 };
1193 self
1194 }
1195
1196 pub fn is_tiled(&self) -> bool {
1198 self.flags & BG_TILED != 0
1199 }
1200
1201 pub fn to_corner(mut self, corner: u8) -> Self {
1206 set_flag(&mut self.flags, BG_CORNER, true);
1207 self.gradient_angle_or_pattern_height = corner as f32;
1208 self
1209 }
1210
1211 pub fn stop_in_pixels(mut self, index: usize) -> Self {
1214 if index < GRADIENT_STOPS {
1215 self.flags |= 1 << (BG_STOP_PX_SHIFT + index as u32);
1216 }
1217 self
1218 }
1219
1220 pub fn stop_at_calc(mut self, index: usize, fraction: f32, pixels: f32) -> Self {
1223 if index < GRADIENT_STOPS {
1224 let bits = (u32::from(f16_bits(fraction)) << 16) | u32::from(f16_bits(pixels));
1225 self.colors[index].percentage = f32::from_bits(bits);
1226 self.flags &= !(1 << (BG_STOP_PX_SHIFT + index as u32));
1227 self.flags |= 1 << (BG_STOP_CALC_SHIFT + index as u32);
1228 }
1229 self
1230 }
1231
1232 pub fn at(mut self, center: (f32, f32), in_pixels: bool) -> Self {
1236 self.params[0] = center.0;
1237 self.params[1] = center.1;
1238 set_flag(&mut self.flags, BG_CENTER_PX, in_pixels);
1239 self
1240 }
1241
1242 pub fn with_radii(mut self, radii: (f32, f32), in_pixels: bool) -> Self {
1245 self.params[2] = radii.0.max(0.0);
1246 self.params[3] = radii.1.max(0.0);
1247 set_flag(&mut self.flags, BG_RADIUS_PX, in_pixels);
1248 self
1249 }
1250
1251 pub fn with_extent(mut self, keyword: u8, ellipse: bool) -> Self {
1255 self.params[2] = -(keyword.clamp(1, 4) as f32);
1256 self.params[3] = if ellipse { 1.0 } else { 0.0 };
1257 set_flag(&mut self.flags, BG_RADIUS_PX, false);
1258 self
1259 }
1260
1261 pub fn with_stops(mut self, stops: &[LinearColorStop]) -> Self {
1264 let replacement = gradient_with_stops(self.tag, 0.0, stops);
1265 self.colors = replacement.colors;
1266 self.stop_count = replacement.stop_count;
1267 self.flags &= !(0xffu32 << BG_STOP_PX_SHIFT) & !(0xffu32 << BG_STOP_CALC_SHIFT);
1270 self
1271 }
1272}
1273
1274fn set_flag(flags: &mut u32, bit: u32, on: bool) {
1275 if on {
1276 *flags |= bit;
1277 } else {
1278 *flags &= !bit;
1279 }
1280}
1281
1282impl From<Hsla> for Background {
1283 fn from(value: Hsla) -> Self {
1284 Background {
1285 tag: BackgroundTag::Solid,
1286 solid: value,
1287 ..Default::default()
1288 }
1289 }
1290}
1291
1292impl From<Rgba> for Background {
1293 fn from(value: Rgba) -> Self {
1294 Background {
1295 tag: BackgroundTag::Solid,
1296 solid: Hsla::from(value),
1297 ..Default::default()
1298 }
1299 }
1300}
1301
1302#[cfg(test)]
1303mod tests {
1304 use serde_json::json;
1305
1306 use super::*;
1307
1308 #[test]
1309 fn f16_bits_rounds_to_nearest_and_clamps() {
1310 let cases = [
1311 (1.0, 0x3c00),
1312 (0.5, 0x3800),
1313 (1.0 / 3.0, 0x3555),
1314 (-200.0, 0xda40),
1315 (1e-6, 0x0011),
1316 (70000.0, 0x7bff),
1317 (-70000.0, 0xfbff),
1318 ];
1319 for (value, bits) in cases {
1320 assert_eq!(f16_bits(value), bits, "{value}");
1321 }
1322 }
1323
1324 #[test]
1325 fn test_deserialize_three_value_hex_to_rgba() {
1326 let actual: Rgba = serde_json::from_value(json!("#f09")).unwrap();
1327
1328 assert_eq!(actual, rgba(0xff0099ff))
1329 }
1330
1331 #[test]
1332 fn test_deserialize_four_value_hex_to_rgba() {
1333 let actual: Rgba = serde_json::from_value(json!("#f09f")).unwrap();
1334
1335 assert_eq!(actual, rgba(0xff0099ff))
1336 }
1337
1338 #[test]
1339 fn test_deserialize_six_value_hex_to_rgba() {
1340 let actual: Rgba = serde_json::from_value(json!("#ff0099")).unwrap();
1341
1342 assert_eq!(actual, rgba(0xff0099ff))
1343 }
1344
1345 #[test]
1346 fn test_deserialize_eight_value_hex_to_rgba() {
1347 let actual: Rgba = serde_json::from_value(json!("#ff0099ff")).unwrap();
1348
1349 assert_eq!(actual, rgba(0xff0099ff))
1350 }
1351
1352 #[test]
1353 fn test_deserialize_eight_value_hex_with_padding_to_rgba() {
1354 let actual: Rgba = serde_json::from_value(json!(" #f5f5f5ff ")).unwrap();
1355
1356 assert_eq!(actual, rgba(0xf5f5f5ff))
1357 }
1358
1359 #[test]
1360 fn test_deserialize_eight_value_hex_with_mixed_case_to_rgba() {
1361 let actual: Rgba = serde_json::from_value(json!("#DeAdbEeF")).unwrap();
1362
1363 assert_eq!(actual, rgba(0xdeadbeef))
1364 }
1365
1366 #[test]
1367 fn test_background_solid() {
1368 let color = Hsla::from(rgba(0xff0099ff));
1369 let mut background = Background::from(color);
1370 assert_eq!(background.tag, BackgroundTag::Solid);
1371 assert_eq!(background.solid, color);
1372
1373 assert_eq!(background.opacity(0.5).solid, color.opacity(0.5));
1374 assert!(!background.is_transparent());
1375 background.solid = hsla(0.0, 0.0, 0.0, 0.0);
1376 assert!(background.is_transparent());
1377 }
1378
1379 #[test]
1380 fn test_background_linear_gradient() {
1381 let from = linear_color_stop(rgba(0xff0099ff), 0.0);
1382 let to = linear_color_stop(rgba(0x00ff99ff), 1.0);
1383 let background = linear_gradient(90.0, from, to);
1384 assert_eq!(background.tag, BackgroundTag::LinearGradient);
1385 assert_eq!(background.colors[0], from);
1386 assert_eq!(background.colors[1], to);
1387
1388 assert_eq!(background.opacity(0.5).colors[0], from.opacity(0.5));
1389 assert_eq!(background.opacity(0.5).colors[1], to.opacity(0.5));
1390 assert!(!background.is_transparent());
1391 assert!(background.opacity(0.0).is_transparent());
1392 }
1393
1394 #[test]
1395 fn test_rgba_alpha() {
1396 let color = Rgba {
1397 r: 0.2,
1398 g: 0.6,
1399 b: 1.0,
1400 a: 0.8,
1401 };
1402
1403 assert_eq!(color.alpha(0.25).a, 0.25);
1404 assert_eq!(color.alpha(1.5).a, 1.0);
1405 }
1406
1407 #[test]
1408 fn test_rgba_opacity() {
1409 let color = Rgba {
1410 r: 0.2,
1411 g: 0.6,
1412 b: 1.0,
1413 a: 0.8,
1414 };
1415 assert!((color.opacity(0.5).a - 0.4).abs() < 1e-6);
1416 assert_eq!(color.opacity(2.0).a, 0.8);
1417 }
1418}