1use std::sync::Arc;
6
7use crate::{
8 color::Hsla,
9 geometry::{
10 AbsoluteLength, Bounds, Corners, DefiniteLength, Edges, Percentage, Point, Points,
11 REM_SIZE, Radians, Size, deg, point, size,
12 },
13 style::{BorderStyle, Color, CornerRadii},
14};
15
16#[derive(Debug, Clone, Copy, PartialEq, Default)]
23#[non_exhaustive]
24pub struct ClipInset {
25 pub offsets: Edges<Points>,
28 pub fractions: Edges<Percentage>,
33 pub radii: Corners<Points>,
36}
37
38impl ClipInset {
39 pub const fn new() -> Self {
41 Self {
42 offsets: Edges {
43 top: Points::ZERO,
44 right: Points::ZERO,
45 bottom: Points::ZERO,
46 left: Points::ZERO,
47 },
48 fractions: Edges {
49 top: Percentage(0.0),
50 right: Percentage(0.0),
51 bottom: Percentage(0.0),
52 left: Percentage(0.0),
53 },
54 radii: Corners {
55 top_left: Points::ZERO,
56 top_right: Points::ZERO,
57 bottom_right: Points::ZERO,
58 bottom_left: Points::ZERO,
59 },
60 }
61 }
62
63 pub fn inset(self, length: impl Into<DefiniteLength>) -> Self {
65 let length = length.into();
66 self.top(length).right(length).bottom(length).left(length)
67 }
68
69 pub fn top(mut self, length: impl Into<DefiniteLength>) -> Self {
71 (self.offsets.top, self.fractions.top) = edge(length.into());
72 self
73 }
74
75 pub fn right(mut self, length: impl Into<DefiniteLength>) -> Self {
77 (self.offsets.right, self.fractions.right) = edge(length.into());
78 self
79 }
80
81 pub fn bottom(mut self, length: impl Into<DefiniteLength>) -> Self {
83 (self.offsets.bottom, self.fractions.bottom) = edge(length.into());
84 self
85 }
86
87 pub fn left(mut self, length: impl Into<DefiniteLength>) -> Self {
89 (self.offsets.left, self.fractions.left) = edge(length.into());
90 self
91 }
92
93 pub fn rounded(mut self, radius: impl Into<Points>) -> Self {
95 self.radii = Corners::all(radius.into());
96 self
97 }
98
99 pub fn corner_radii(mut self, radii: Corners<Points>) -> Self {
101 self.radii = radii;
102 self
103 }
104
105 pub fn resolve(&self, size: Size<Points>) -> (Bounds<Points>, CornerRadii) {
110 let (w, h) = (size.width.0.max(0.0), size.height.0.max(0.0));
111 let at = |o: Points, f: Percentage, len: f32| o.0 + f.0 * len;
112 let (mut top, mut bottom) = (
113 at(self.offsets.top, self.fractions.top, h),
114 at(self.offsets.bottom, self.fractions.bottom, h),
115 );
116 let (mut left, mut right) = (
117 at(self.offsets.left, self.fractions.left, w),
118 at(self.offsets.right, self.fractions.right, w),
119 );
120 let meet = |a: &mut f32, b: &mut f32, len: f32| {
121 let sum = *a + *b;
122 if sum > len && sum > 0.0 {
123 let k = len / sum;
124 *a *= k;
125 *b *= k;
126 }
127 };
128 meet(&mut top, &mut bottom, h);
129 meet(&mut left, &mut right, w);
130 let rect = Bounds::new(
131 point(Points(left), Points(top)),
132 size_of((w - left - right).max(0.0), (h - top - bottom).max(0.0)),
133 );
134 let radii = CornerRadii::circular(self.radii.map(|r| r.max(Points::ZERO))).fit(rect.size);
135 (rect, radii)
136 }
137
138 pub fn outline(&self, size: Size<Points>, out: &mut impl FnMut(crate::shape::Segment)) {
144 use crate::shape::Segment;
145 const K: f32 = 0.552_284_8;
148 let (rect, radii) = self.resolve(size);
149 let (x0, y0) = (rect.origin.x.0, rect.origin.y.0);
150 let (x1, y1) = (x0 + rect.size.width.0, y0 + rect.size.height.0);
151 let (tl, tr, br, bl) = (
152 radii.top_left.0,
153 radii.top_right.0,
154 radii.bottom_right.0,
155 radii.bottom_left.0,
156 );
157 let p = |x: f32, y: f32| point(Points(x), Points(y));
158 let c =
159 |c1: Point<Points>, c2: Point<Points>, to: Point<Points>| Segment::Cubic([c1, c2, to]);
160 out(Segment::Move(p(x0 + tl, y0)));
161 out(Segment::Line(p(x1 - tr, y0)));
162 out(c(
163 p(x1 - tr + K * tr, y0),
164 p(x1, y0 + tr - K * tr),
165 p(x1, y0 + tr),
166 ));
167 out(Segment::Line(p(x1, y1 - br)));
168 out(c(
169 p(x1, y1 - br + K * br),
170 p(x1 - br + K * br, y1),
171 p(x1 - br, y1),
172 ));
173 out(Segment::Line(p(x0 + bl, y1)));
174 out(c(
175 p(x0 + bl - K * bl, y1),
176 p(x0, y1 - bl + K * bl),
177 p(x0, y1 - bl),
178 ));
179 out(Segment::Line(p(x0, y0 + tl)));
180 out(c(
181 p(x0, y0 + tl - K * tl),
182 p(x0 + tl - K * tl, y0),
183 p(x0 + tl, y0),
184 ));
185 out(Segment::Close);
186 }
187
188 pub fn contains(&self, size: Size<Points>, p: Point<Points>) -> bool {
190 let (rect, radii) = self.resolve(size);
191 let (x0, y0) = (rect.origin.x.0, rect.origin.y.0);
192 let (x1, y1) = (x0 + rect.size.width.0, y0 + rect.size.height.0);
193 let (x, y) = (p.x.0, p.y.0);
194 if !(x >= x0 && y >= y0 && x < x1 && y < y1) {
195 return false;
196 }
197 let outside = |r: Points, cx: f32, cy: f32, beyond_x: bool, beyond_y: bool| {
199 let r = r.0;
200 r > 0.0 && beyond_x && beyond_y && {
201 let (dx, dy) = (x - cx, y - cy);
202 dx * dx + dy * dy > r * r
203 }
204 };
205 let (tl, tr, br, bl) = (
206 radii.top_left,
207 radii.top_right,
208 radii.bottom_right,
209 radii.bottom_left,
210 );
211 !(outside(tl, x0 + tl.0, y0 + tl.0, x < x0 + tl.0, y < y0 + tl.0)
212 || outside(tr, x1 - tr.0, y0 + tr.0, x > x1 - tr.0, y < y0 + tr.0)
213 || outside(br, x1 - br.0, y1 - br.0, x > x1 - br.0, y > y1 - br.0)
214 || outside(bl, x0 + bl.0, y1 - bl.0, x < x0 + bl.0, y > y1 - bl.0))
215 }
216
217 pub fn lerp(&self, to: &Self, t: f32) -> Self {
221 let l = |a: f32, b: f32| a + (b - a) * t;
222 let lp = |a: Points, b: Points| Points(l(a.0, b.0));
223 let lf = |a: Percentage, b: Percentage| Percentage(l(a.0, b.0));
224 Self {
225 offsets: Edges {
226 top: lp(self.offsets.top, to.offsets.top),
227 right: lp(self.offsets.right, to.offsets.right),
228 bottom: lp(self.offsets.bottom, to.offsets.bottom),
229 left: lp(self.offsets.left, to.offsets.left),
230 },
231 fractions: Edges {
232 top: lf(self.fractions.top, to.fractions.top),
233 right: lf(self.fractions.right, to.fractions.right),
234 bottom: lf(self.fractions.bottom, to.fractions.bottom),
235 left: lf(self.fractions.left, to.fractions.left),
236 },
237 radii: Corners {
238 top_left: lp(self.radii.top_left, to.radii.top_left).max(Points::ZERO),
239 top_right: lp(self.radii.top_right, to.radii.top_right).max(Points::ZERO),
240 bottom_right: lp(self.radii.bottom_right, to.radii.bottom_right).max(Points::ZERO),
241 bottom_left: lp(self.radii.bottom_left, to.radii.bottom_left).max(Points::ZERO),
242 },
243 }
244 }
245}
246
247fn edge(length: DefiniteLength) -> (Points, Percentage) {
249 match length {
250 DefiniteLength::Absolute(a) => (a.to_points(REM_SIZE), Percentage(0.0)),
251 DefiniteLength::Fraction(f) => (Points::ZERO, f),
252 }
253}
254
255fn size_of(width: f32, height: f32) -> Size<Points> {
256 size(Points(width), Points(height))
257}
258
259#[derive(Debug, Clone, Copy, PartialEq, Default)]
261pub struct BoxShadow {
262 pub offset_x: Points,
264 pub offset_y: Points,
266 pub blur: Points,
268 pub spread: Points,
270 pub color: Color,
272 pub inset: bool,
274}
275
276impl BoxShadow {
277 pub fn is_visible(&self) -> bool {
279 !self.color.is_transparent()
280 }
281}
282
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub enum GradientSize {
286 ClosestSide,
288 ClosestCorner,
290 FarthestSide,
292 FarthestCorner,
294}
295
296#[derive(Debug, Clone, Copy, PartialEq)]
298pub enum GradientKind {
299 Linear {
301 angle: Radians,
303 },
304 LinearCorner {
307 right: bool,
309 bottom: bool,
311 },
312 Radial {
314 circle: bool,
316 size: GradientSize,
318 x: Percentage,
320 y: Percentage,
322 },
323 Conic {
325 from: Radians,
327 x: Percentage,
329 y: Percentage,
331 },
332}
333
334impl GradientKind {
335 pub fn linear_angle(&self, size: Size<Points>) -> Option<Radians> {
337 match *self {
338 GradientKind::Linear { angle } => Some(angle),
339 GradientKind::LinearCorner { right, bottom } => {
340 let a = (size.height.0.max(f32::EPSILON) / size.width.0.max(f32::EPSILON))
343 .atan()
344 .to_degrees();
345 Some(deg(match (right, bottom) {
346 (true, false) => 90.0 - a,
347 (true, true) => 90.0 + a,
348 (false, true) => 270.0 - a,
349 (false, false) => 270.0 + a,
350 }))
351 }
352 _ => None,
353 }
354 }
355}
356
357fn stop_fraction(position: DefiniteLength, line: Points) -> f32 {
360 match position {
361 DefiniteLength::Fraction(f) => f.0,
362 DefiniteLength::Absolute(a) => {
363 let p = a.to_points(REM_SIZE);
364 if line.0 > 0.0 {
365 p / line
366 } else if p.0 > 0.0 {
367 1.0
370 } else {
371 0.0
372 }
373 }
374 }
375}
376
377#[derive(Debug, Clone, Copy, PartialEq)]
379pub struct ColorStop {
380 pub color: Color,
382 pub position: Option<DefiniteLength>,
388}
389
390#[derive(Debug, Clone, PartialEq)]
392pub struct Gradient {
393 pub kind: GradientKind,
395 pub stops: Vec<ColorStop>,
397 pub repeating: bool,
399}
400
401impl From<Hsla> for ColorStop {
403 fn from(color: Hsla) -> Self {
404 ColorStop {
405 color: color.into(),
406 position: None,
407 }
408 }
409}
410
411impl<P: Into<DefiniteLength>> From<(Hsla, P)> for ColorStop {
414 fn from((color, position): (Hsla, P)) -> Self {
415 ColorStop {
416 color: color.into(),
417 position: Some(position.into()),
418 }
419 }
420}
421
422impl<T: Into<ColorStop>, const N: usize> crate::element::IntoReactive<Vec<ColorStop>> for [T; N] {
423 fn into_reactive(self) -> crate::element::Reactive<Vec<ColorStop>> {
424 crate::element::Reactive::Static(self.into_iter().map(Into::into).collect())
425 }
426}
427
428impl<T: Into<ColorStop>> crate::element::IntoReactive<Vec<ColorStop>> for Vec<T> {
429 fn into_reactive(self) -> crate::element::Reactive<Vec<ColorStop>> {
430 crate::element::Reactive::Static(self.into_iter().map(Into::into).collect())
431 }
432}
433
434impl Gradient {
435 pub fn lerp(&self, to: &Self, t: f32) -> Option<Self> {
444 if self.repeating != to.repeating || self.stops.len() != to.stops.len() {
445 return None;
446 }
447 let l = |a: f32, b: f32| a + (b - a) * t;
448 let kind = match (self.kind, to.kind) {
449 (GradientKind::Linear { angle: a }, GradientKind::Linear { angle: b }) => {
450 GradientKind::Linear {
451 angle: Radians(l(a.0, b.0)),
452 }
453 }
454 (a @ GradientKind::LinearCorner { .. }, b) if a == b => a,
455 (
456 GradientKind::Radial {
457 circle,
458 size,
459 x: ax,
460 y: ay,
461 },
462 GradientKind::Radial {
463 circle: bc,
464 size: bs,
465 x: bx,
466 y: by,
467 },
468 ) if circle == bc && size == bs => GradientKind::Radial {
469 circle,
470 size,
471 x: Percentage(l(ax.0, bx.0)),
472 y: Percentage(l(ay.0, by.0)),
473 },
474 (
475 GradientKind::Conic {
476 from: af,
477 x: ax,
478 y: ay,
479 },
480 GradientKind::Conic {
481 from: bf,
482 x: bx,
483 y: by,
484 },
485 ) => GradientKind::Conic {
486 from: Radians(l(af.0, bf.0)),
487 x: Percentage(l(ax.0, bx.0)),
488 y: Percentage(l(ay.0, by.0)),
489 },
490 _ => return None,
491 };
492 let stops = self
493 .stops
494 .iter()
495 .zip(&to.stops)
496 .map(|(a, b)| {
497 let position = match (a.position, b.position) {
498 (None, None) => None,
499 (Some(DefiniteLength::Fraction(pa)), Some(DefiniteLength::Fraction(pb))) => {
500 Some(DefiniteLength::Fraction(Percentage(l(pa.0, pb.0))))
501 }
502 (Some(DefiniteLength::Absolute(pa)), Some(DefiniteLength::Absolute(pb))) => {
503 let (pa, pb) = (pa.to_points(REM_SIZE), pb.to_points(REM_SIZE));
504 Some(DefiniteLength::Absolute(AbsoluteLength::Points(Points(l(
505 pa.0, pb.0,
506 )))))
507 }
508 _ => return None,
509 };
510 Some(ColorStop {
511 color: crate::transition::lerp_color(a.color, b.color, t),
512 position,
513 })
514 })
515 .collect::<Option<Vec<_>>>()?;
516 Some(Gradient {
517 kind,
518 stops,
519 repeating: self.repeating,
520 })
521 }
522
523 pub fn has_lengths(&self) -> bool {
526 self.stops
527 .iter()
528 .any(|s| matches!(s.position, Some(DefiniteLength::Absolute(_))))
529 }
530
531 pub fn line_length(&self, size: Size<Points>) -> Points {
538 let (w, h) = (size.width.0, size.height.0);
539 Points(match self.kind {
540 GradientKind::Radial {
541 circle,
542 size: shape,
543 x,
544 y,
545 } => radial_radii(circle, shape, x.0 * w, y.0 * h, w, h).0,
546 GradientKind::Conic { .. } => 0.0,
547 kind => {
548 let angle = kind.linear_angle(size).unwrap_or(deg(180.0));
549 let (s, c) = angle.sin_cos();
550 (w * s).abs() + (h * c).abs()
551 }
552 })
553 }
554
555 pub fn resolved_stops(&self, size: Size<Points>) -> Vec<(Color, Percentage)> {
559 let mut out = Vec::with_capacity(self.stops.len());
560 self.resolve_stops(size, &mut out);
561 out
562 }
563
564 pub fn resolve_stops(&self, size: Size<Points>, out: &mut Vec<(Color, Percentage)>) {
566 let line = if self.has_lengths() {
567 self.line_length(size)
568 } else {
569 Points::ZERO
570 };
571 out.clear();
572 out.extend(self.stops.iter().map(|s| {
573 let at = s.position.map_or(f32::NAN, |p| stop_fraction(p, line));
574 (s.color, Percentage(at))
575 }));
576 let n = out.len();
577 if n == 0 {
578 return;
579 }
580 if out[0].1.is_nan() {
581 out[0].1 = Percentage(0.0);
582 }
583 if out[n - 1].1.is_nan() {
584 out[n - 1].1 = Percentage(1.0);
585 }
586 let mut max = Percentage(0.0);
589 for s in out.iter_mut().filter(|s| !s.1.is_nan()) {
590 max = max.max(s.1);
591 s.1 = max;
592 }
593 let mut i = 1;
594 while i < n {
595 if !out[i].1.is_nan() {
596 i += 1;
597 continue;
598 }
599 let start = i - 1;
600 let mut end = i;
601 while out[end].1.is_nan() {
602 end += 1;
603 }
604 let (a, b) = (out[start].1, out[end].1);
605 for (k, s) in out[i..end].iter_mut().enumerate() {
606 s.1 = Percentage(a.0 + (b.0 - a.0) * (k + 1) as f32 / (end - start) as f32);
607 }
608 i = end;
609 }
610 }
611
612 pub fn unrolled_stops(
623 &self,
624 size: Size<Points>,
625 reach: Percentage,
626 ) -> Vec<(Color, Percentage)> {
627 let stops = self.resolved_stops(size);
628 let reach = reach.0.max(f32::EPSILON);
629 let mut out = match self
630 .repeating
631 .then(|| repeat_stops(&stops, reach))
632 .flatten()
633 {
634 Some(tiled) => cut_stops(&tiled, Percentage(reach)),
635 None => stops,
636 };
637 if reach != 1.0 {
638 for s in &mut out {
639 s.1 = Percentage(s.1.0 / reach);
640 }
641 }
642 out
643 }
644}
645
646const MAX_UNROLLED_STOPS: usize = 16_384;
649
650fn repeat_stops(stops: &[(Color, Percentage)], reach: f32) -> Option<Vec<(Color, Percentage)>> {
655 let (first, last) = (stops.first()?.1.0, stops.last()?.1.0);
656 let period = last - first;
657 if period <= 1e-4 {
658 return None;
659 }
660 let start = ((0.0 - last) / period).floor();
661 let end = ((reach - first) / period).ceil();
662 let copies = end - start + 1.0;
663 if copies * stops.len() as f32 > MAX_UNROLLED_STOPS as f32 {
664 return None;
665 }
666 let mut out: Vec<(Color, Percentage)> = (start as i32..=end as i32)
667 .flat_map(|k| {
668 let shift = k as f32 * period;
669 stops
670 .iter()
671 .map(move |&(c, p)| (c, Percentage(p.0 + shift)))
672 })
673 .collect();
674 let mut max = Percentage(f32::NEG_INFINITY);
676 for s in &mut out {
677 max = max.max(s.1);
678 s.1 = max;
679 }
680 Some(out)
681}
682
683pub(crate) fn cut_stops(
687 stops: &[(Color, Percentage)],
688 reach: Percentage,
689) -> Vec<(Color, Percentage)> {
690 let color_at = |t: f32| {
691 let Some(i) = stops.iter().rposition(|s| s.1.0 <= t) else {
692 return stops.first().map_or(Color::TRANSPARENT, |s| s.0);
693 };
694 match stops.get(i + 1) {
695 Some(&(c, p)) if p.0 > stops[i].1.0 => {
696 mix(stops[i].0, c, (t - stops[i].1.0) / (p.0 - stops[i].1.0))
697 }
698 _ => stops[i].0,
699 }
700 };
701 let mut out = Vec::with_capacity(stops.len() + 2);
702 out.push((color_at(0.0), Percentage(0.0)));
703 out.extend(stops.iter().copied().filter(|s| s.1.0 > 0.0 && s.1 < reach));
704 out.push((color_at(reach.0), reach));
705 out
706}
707
708fn mix(a: Color, b: Color, t: f32) -> Color {
711 let channel = |c: Color, shift: u32| ((c.0 >> shift) & 0xff) as f32;
712 let (alpha_a, alpha_b) = (channel(a, 0), channel(b, 0));
713 let alpha = alpha_a + (alpha_b - alpha_a) * t;
714 let color = |shift: u32| {
715 if alpha <= 0.0 {
716 return 0;
717 }
718 let (x, y) = (channel(a, shift) * alpha_a, channel(b, shift) * alpha_b);
719 ((x + (y - x) * t) / alpha).round().clamp(0.0, 255.0) as u32
720 };
721 let alpha_byte = alpha.round().clamp(0.0, 255.0) as u32;
722 Color((color(24) << 24) | (color(16) << 16) | (color(8) << 8) | alpha_byte)
723}
724
725fn radial_radii(circle: bool, size: GradientSize, cx: f32, cy: f32, w: f32, h: f32) -> (f32, f32) {
728 let near = (cx.min(w - cx).abs(), cy.min(h - cy).abs());
729 let far = (cx.max(w - cx).abs(), cy.max(h - cy).abs());
730 if circle {
731 let r = match size {
732 GradientSize::ClosestSide => near.0.min(near.1),
733 GradientSize::FarthestSide => far.0.max(far.1),
734 GradientSize::ClosestCorner => near.0.hypot(near.1),
735 GradientSize::FarthestCorner => far.0.hypot(far.1),
736 };
737 return (r, r);
738 }
739 let s = std::f32::consts::SQRT_2;
741 match size {
742 GradientSize::ClosestSide => near,
743 GradientSize::FarthestSide => far,
744 GradientSize::ClosestCorner => (near.0 * s, near.1 * s),
745 GradientSize::FarthestCorner => (far.0 * s, far.1 * s),
746 }
747}
748
749#[derive(Debug, Clone, Copy, PartialEq)]
751pub enum Filter {
752 Blur(Points),
754 Brightness(f32),
756 Contrast(f32),
758 Grayscale(f32),
760 HueRotate(Radians),
762 Invert(f32),
764 Opacity(f32),
766 Saturate(f32),
768 Sepia(f32),
770 DropShadow {
772 offset_x: Points,
774 offset_y: Points,
776 blur: Points,
778 color: Color,
780 },
781}
782
783impl Filter {
784 pub fn color_matrix(&self) -> Option<[f32; 20]> {
787 let id = |r: [f32; 3], g: [f32; 3], b: [f32; 3]| {
788 [
789 r[0], r[1], r[2], 0.0, 0.0, g[0], g[1], g[2], 0.0, 0.0, b[0], b[1], b[2], 0.0, 0.0,
790 0.0, 0.0, 0.0, 1.0, 0.0,
791 ]
792 };
793 Some(match *self {
794 Filter::Brightness(v) => id([v, 0.0, 0.0], [0.0, v, 0.0], [0.0, 0.0, v]),
795 Filter::Contrast(v) => {
796 let t = (1.0 - v) / 2.0;
797 [
798 v, 0.0, 0.0, 0.0, t, 0.0, v, 0.0, 0.0, t, 0.0, 0.0, v, 0.0, t, 0.0, 0.0, 0.0,
799 1.0, 0.0,
800 ]
801 }
802 Filter::Grayscale(v) => {
803 let a = 1.0 - v;
804 id(
805 [
806 0.2126 + 0.7874 * a,
807 0.7152 - 0.7152 * a,
808 0.0722 - 0.0722 * a,
809 ],
810 [
811 0.2126 - 0.2126 * a,
812 0.7152 + 0.2848 * a,
813 0.0722 - 0.0722 * a,
814 ],
815 [
816 0.2126 - 0.2126 * a,
817 0.7152 - 0.7152 * a,
818 0.0722 + 0.9278 * a,
819 ],
820 )
821 }
822 Filter::Sepia(v) => {
823 let a = 1.0 - v;
824 id(
825 [0.393 + 0.607 * a, 0.769 - 0.769 * a, 0.189 - 0.189 * a],
826 [0.349 - 0.349 * a, 0.686 + 0.314 * a, 0.168 - 0.168 * a],
827 [0.272 - 0.272 * a, 0.534 - 0.534 * a, 0.131 + 0.869 * a],
828 )
829 }
830 Filter::Saturate(s) => id(
831 [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s],
832 [0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s],
833 [0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s],
834 ),
835 Filter::HueRotate(angle) => {
836 let (s, c) = angle.sin_cos();
837 id(
838 [
839 0.213 + c * 0.787 - s * 0.213,
840 0.715 - c * 0.715 - s * 0.715,
841 0.072 - c * 0.072 + s * 0.928,
842 ],
843 [
844 0.213 - c * 0.213 + s * 0.143,
845 0.715 + c * 0.285 + s * 0.140,
846 0.072 - c * 0.072 - s * 0.283,
847 ],
848 [
849 0.213 - c * 0.213 - s * 0.787,
850 0.715 - c * 0.715 + s * 0.715,
851 0.072 + c * 0.928 + s * 0.072,
852 ],
853 )
854 }
855 Filter::Invert(v) => {
856 let m = 1.0 - 2.0 * v;
857 [
858 m, 0.0, 0.0, 0.0, v, 0.0, m, 0.0, 0.0, v, 0.0, 0.0, m, 0.0, v, 0.0, 0.0, 0.0,
859 1.0, 0.0,
860 ]
861 }
862 Filter::Opacity(v) => [
863 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
864 0.0, 0.0, v, 0.0,
865 ],
866 Filter::Blur(_) | Filter::DropShadow { .. } => return None,
867 })
868 }
869}
870
871pub fn compose_color_matrices(filters: &[Filter]) -> Option<[f32; 20]> {
874 let mut out: Option<[f32; 20]> = None;
875 for m in filters.iter().filter_map(Filter::color_matrix) {
876 out = Some(match out {
877 None => m,
878 Some(prev) => {
879 let mut r = [0.0; 20];
882 for row in 0..4 {
883 for col in 0..5 {
884 let mut v = if col == 4 { m[row * 5 + 4] } else { 0.0 };
885 for k in 0..4 {
886 v += m[row * 5 + k] * prev[k * 5 + col];
887 }
888 r[row * 5 + col] = v;
889 }
890 }
891 r
892 }
893 });
894 }
895 out
896}
897
898pub fn blur_radius(filters: &[Filter]) -> Points {
900 filters
901 .iter()
902 .map(|f| match f {
903 Filter::Blur(r) => *r,
904 _ => Points::ZERO,
905 })
906 .sum()
907}
908
909#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
923pub enum BackdropMaterial {
924 #[default]
926 UltraThin,
927 Thin,
929 Regular,
931 Thick,
933 Chrome,
935}
936
937impl BackdropMaterial {
938 pub fn name(self) -> &'static str {
940 match self {
941 BackdropMaterial::UltraThin => "ultraThin",
942 BackdropMaterial::Thin => "thin",
943 BackdropMaterial::Regular => "regular",
944 BackdropMaterial::Thick => "thick",
945 BackdropMaterial::Chrome => "chrome",
946 }
947 }
948
949 pub fn parse(s: &str) -> Option<BackdropMaterial> {
951 Some(match s {
952 "ultraThin" => BackdropMaterial::UltraThin,
953 "thin" => BackdropMaterial::Thin,
954 "regular" => BackdropMaterial::Regular,
955 "thick" => BackdropMaterial::Thick,
956 "chrome" => BackdropMaterial::Chrome,
957 _ => return None,
958 })
959 }
960}
961
962#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
978#[non_exhaustive]
979pub struct MacOsBackdrop {
980 pub material: MacOsBackdropMaterial,
982 pub blending: MacOsBackdropBlending,
984 pub state: MacOsBackdropState,
987}
988
989#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
995pub enum MacOsBackdropMaterial {
996 Titlebar,
998 Selection,
1000 Menu,
1002 #[default]
1004 Popover,
1005 Sidebar,
1007 HeaderView,
1009 Sheet,
1011 WindowBackground,
1013 HudWindow,
1015 FullScreenUI,
1017 ToolTip,
1019 ContentBackground,
1021 UnderWindowBackground,
1023 UnderPageBackground,
1025}
1026
1027#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
1029pub enum MacOsBackdropBlending {
1030 #[default]
1032 WithinWindow,
1033 BehindWindow,
1036}
1037
1038#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
1041pub enum MacOsBackdropState {
1042 FollowsWindowActiveState,
1044 #[default]
1046 Active,
1047 Inactive,
1049}
1050
1051#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1056#[non_exhaustive]
1057pub struct WindowsBackdrop {
1058 pub material: WindowsBackdropMaterial,
1060}
1061
1062#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, crate::element::PropEnum)]
1064#[non_exhaustive]
1065pub enum WindowsBackdropMaterial {
1066 #[default]
1069 Blur,
1070}
1071
1072#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1083pub enum GlassEffect {
1084 #[default]
1086 None,
1087 Regular,
1089 Clear,
1091}
1092
1093impl GlassEffect {
1094 pub fn name(self) -> &'static str {
1096 match self {
1097 GlassEffect::None => "none",
1098 GlassEffect::Regular => "regular",
1099 GlassEffect::Clear => "clear",
1100 }
1101 }
1102
1103 pub fn parse(s: &str) -> Option<GlassEffect> {
1105 Some(match s {
1106 "none" => GlassEffect::None,
1107 "regular" => GlassEffect::Regular,
1108 "clear" => GlassEffect::Clear,
1109 _ => return None,
1110 })
1111 }
1112}
1113
1114#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1116#[allow(missing_docs)]
1117pub enum BlendMode {
1118 #[default]
1119 Normal,
1120 Multiply,
1121 Screen,
1122 Overlay,
1123 Darken,
1124 Lighten,
1125 ColorDodge,
1126 ColorBurn,
1127 HardLight,
1128 SoftLight,
1129 Difference,
1130 Exclusion,
1131 Hue,
1132 Saturation,
1133 Color,
1134 Luminosity,
1135 PlusDarker,
1136 PlusLighter,
1137}
1138
1139impl BlendMode {
1140 pub fn name(self) -> &'static str {
1142 match self {
1143 BlendMode::Normal => "normal",
1144 BlendMode::Multiply => "multiply",
1145 BlendMode::Screen => "screen",
1146 BlendMode::Overlay => "overlay",
1147 BlendMode::Darken => "darken",
1148 BlendMode::Lighten => "lighten",
1149 BlendMode::ColorDodge => "color-dodge",
1150 BlendMode::ColorBurn => "color-burn",
1151 BlendMode::HardLight => "hard-light",
1152 BlendMode::SoftLight => "soft-light",
1153 BlendMode::Difference => "difference",
1154 BlendMode::Exclusion => "exclusion",
1155 BlendMode::Hue => "hue",
1156 BlendMode::Saturation => "saturation",
1157 BlendMode::Color => "color",
1158 BlendMode::Luminosity => "luminosity",
1159 BlendMode::PlusDarker => "plus-darker",
1160 BlendMode::PlusLighter => "plus-lighter",
1161 }
1162 }
1163
1164 pub fn parse(s: &str) -> Option<BlendMode> {
1166 Some(match s {
1167 "normal" => BlendMode::Normal,
1168 "multiply" => BlendMode::Multiply,
1169 "screen" => BlendMode::Screen,
1170 "overlay" => BlendMode::Overlay,
1171 "darken" => BlendMode::Darken,
1172 "lighten" => BlendMode::Lighten,
1173 "color-dodge" => BlendMode::ColorDodge,
1174 "color-burn" => BlendMode::ColorBurn,
1175 "hard-light" => BlendMode::HardLight,
1176 "soft-light" => BlendMode::SoftLight,
1177 "difference" => BlendMode::Difference,
1178 "exclusion" => BlendMode::Exclusion,
1179 "hue" => BlendMode::Hue,
1180 "saturation" => BlendMode::Saturation,
1181 "color" => BlendMode::Color,
1182 "luminosity" => BlendMode::Luminosity,
1183 "plus-darker" => BlendMode::PlusDarker,
1184 "plus-lighter" => BlendMode::PlusLighter,
1185 _ => return None,
1186 })
1187 }
1188}
1189
1190#[derive(Debug, Clone, Copy, PartialEq)]
1192pub struct Outline {
1193 pub width: Points,
1195 pub color: Color,
1197 pub style: BorderStyle,
1199 pub offset: Points,
1201}
1202
1203impl Outline {
1204 pub const NONE: Outline = Outline {
1206 width: Points::ZERO,
1207 color: Color::BLACK,
1208 style: BorderStyle::Solid,
1209 offset: Points::ZERO,
1210 };
1211
1212 pub fn is_visible(&self) -> bool {
1214 self.width > Points::ZERO && !self.color.is_transparent()
1215 }
1216}
1217
1218impl Default for Outline {
1219 fn default() -> Self {
1220 Self::NONE
1221 }
1222}
1223
1224#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1227#[allow(missing_docs)]
1228pub enum Cursor {
1229 #[default]
1230 Auto,
1231 Default,
1232 Pointer,
1233 Text,
1234 Wait,
1235 Progress,
1236 Help,
1237 Crosshair,
1238 Move,
1239 Grab,
1240 Grabbing,
1241 NotAllowed,
1242 ZoomIn,
1243 ZoomOut,
1244 ColResize,
1245 RowResize,
1246 None,
1247 NwseResize,
1249 NeswResize,
1251}
1252
1253impl Cursor {
1254 pub fn name(self) -> &'static str {
1256 match self {
1257 Cursor::Auto => "auto",
1258 Cursor::Default => "default",
1259 Cursor::Pointer => "pointer",
1260 Cursor::Text => "text",
1261 Cursor::Wait => "wait",
1262 Cursor::Progress => "progress",
1263 Cursor::Help => "help",
1264 Cursor::Crosshair => "crosshair",
1265 Cursor::Move => "move",
1266 Cursor::Grab => "grab",
1267 Cursor::Grabbing => "grabbing",
1268 Cursor::NotAllowed => "not-allowed",
1269 Cursor::ZoomIn => "zoom-in",
1270 Cursor::ZoomOut => "zoom-out",
1271 Cursor::ColResize => "col-resize",
1272 Cursor::RowResize => "row-resize",
1273 Cursor::None => "none",
1274 Cursor::NwseResize => "nwse-resize",
1275 Cursor::NeswResize => "nesw-resize",
1276 }
1277 }
1278
1279 pub fn parse(s: &str) -> Option<Cursor> {
1281 Some(match s {
1282 "auto" => Cursor::Auto,
1283 "default" | "context-menu" | "alias" | "copy" | "cell" => Cursor::Default,
1284 "pointer" => Cursor::Pointer,
1285 "text" | "vertical-text" => Cursor::Text,
1286 "wait" => Cursor::Wait,
1287 "progress" => Cursor::Progress,
1288 "help" => Cursor::Help,
1289 "crosshair" => Cursor::Crosshair,
1290 "move" | "all-scroll" => Cursor::Move,
1291 "grab" => Cursor::Grab,
1292 "grabbing" => Cursor::Grabbing,
1293 "not-allowed" | "no-drop" => Cursor::NotAllowed,
1294 "zoom-in" => Cursor::ZoomIn,
1295 "zoom-out" => Cursor::ZoomOut,
1296 "col-resize" | "e-resize" | "w-resize" | "ew-resize" => Cursor::ColResize,
1297 "row-resize" | "n-resize" | "s-resize" | "ns-resize" => Cursor::RowResize,
1298 "nw-resize" | "se-resize" | "nwse-resize" => Cursor::NwseResize,
1299 "ne-resize" | "sw-resize" | "nesw-resize" => Cursor::NeswResize,
1300 "none" => Cursor::None,
1301 _ => return None,
1302 })
1303 }
1304}
1305
1306#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1308pub struct TransitionProps(pub u8);
1309
1310impl TransitionProps {
1311 pub const COLORS: u8 = 1;
1313 pub const OPACITY: u8 = 2;
1315 pub const TRANSFORM: u8 = 4;
1317 pub const SHADOW: u8 = 8;
1319 pub const SHAPE: u8 = 16;
1321 pub const CLIP_PATH: u8 = 32;
1323 pub const MASK: u8 = 64;
1326 pub const ALL: u8 = 0x7f;
1328
1329 #[inline]
1331 pub fn has(self, group: u8) -> bool {
1332 self.0 & group != 0
1333 }
1334}
1335
1336#[derive(Debug, Clone, Copy, PartialEq)]
1338#[non_exhaustive]
1339pub struct Transition {
1340 pub properties: TransitionProps,
1342 pub duration: f32,
1344 pub delay: f32,
1346 pub easing: [f32; 4],
1348 pub spring: Option<crate::element::Spring>,
1356}
1357
1358impl Default for Transition {
1359 fn default() -> Self {
1361 Self {
1362 properties: TransitionProps(TransitionProps::ALL),
1363 duration: 0.0,
1364 delay: 0.0,
1365 easing: Self::EASE,
1366 spring: None,
1367 }
1368 }
1369}
1370
1371impl Transition {
1372 pub const EASE: [f32; 4] = [0.25, 0.1, 0.25, 1.0];
1374
1375 pub fn run_ms(&self) -> f32 {
1378 match self.spring {
1379 Some(spring) => spring.settle_ms(),
1380 None => self.duration.max(0.0),
1381 }
1382 }
1383}
1384
1385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1387pub enum Keyframes {
1388 Spin,
1390 Ping,
1392 Pulse,
1394 Bounce,
1396}
1397
1398#[derive(Debug, Clone, Copy, PartialEq)]
1400pub struct KeyframeAnimation {
1401 pub keyframes: Keyframes,
1403 pub duration: f32,
1405 pub delay: f32,
1407 pub easing: [f32; 4],
1409 pub iterations: Option<u32>,
1411 pub frame_rate: Option<f32>,
1415}
1416
1417impl KeyframeAnimation {
1418 pub const fn new(keyframes: Keyframes) -> Self {
1421 Self {
1422 keyframes,
1423 duration: 1000.0,
1424 delay: 0.0,
1425 easing: [0.0, 0.0, 1.0, 1.0],
1426 iterations: None,
1427 frame_rate: None,
1428 }
1429 }
1430
1431 pub const fn duration(mut self, ms: f32) -> Self {
1433 self.duration = ms;
1434 self
1435 }
1436
1437 pub const fn delay(mut self, ms: f32) -> Self {
1439 self.delay = ms;
1440 self
1441 }
1442
1443 pub const fn easing(mut self, curve: [f32; 4]) -> Self {
1445 self.easing = curve;
1446 self
1447 }
1448
1449 pub const fn iterations(mut self, count: u32) -> Self {
1451 self.iterations = Some(count);
1452 self
1453 }
1454
1455 pub const fn frame_rate(mut self, hz: f32) -> Self {
1458 self.frame_rate = Some(hz);
1459 self
1460 }
1461}
1462
1463#[derive(Debug, Clone, PartialEq, Default)]
1465pub struct Effects {
1466 pub box_shadows: Vec<BoxShadow>,
1468 pub background_images: Vec<Gradient>,
1470 pub filters: Vec<Filter>,
1472 pub backdrop_filters: Vec<Filter>,
1474 pub mask_images: Vec<Gradient>,
1478 pub clip_path: Option<ClipInset>,
1481}
1482
1483impl Effects {
1484 pub fn is_empty(&self) -> bool {
1486 self.box_shadows.is_empty()
1487 && self.background_images.is_empty()
1488 && self.filters.is_empty()
1489 && self.backdrop_filters.is_empty()
1490 && self.mask_images.is_empty()
1491 && self.clip_path.is_none()
1492 }
1493}
1494
1495pub(crate) fn shared(effects: Effects) -> Option<Arc<Effects>> {
1497 (!effects.is_empty()).then(|| Arc::new(effects))
1498}
1499
1500#[cfg(test)]
1501mod tests {
1502 use super::*;
1503 use crate::geometry::{percentage, px, size};
1504
1505 #[test]
1506 fn a_clip_inset_resolves_as_css_does() {
1507 let at =
1508 |x: f32, y: f32, w: f32, h: f32| Bounds::new(point(px(x), px(y)), size(px(w), px(h)));
1509 let box_ = size(px(200.0), px(100.0));
1510 let clip = ClipInset::new()
1512 .top(percentage(0.1))
1513 .right(px(20.0))
1514 .bottom(px(30.0))
1515 .left(percentage(0.25));
1516 assert_eq!(clip.resolve(box_).0, at(50.0, 10.0, 130.0, 60.0));
1517 let past = ClipInset::new()
1519 .left(percentage(0.75))
1520 .right(percentage(0.75));
1521 assert_eq!(past.resolve(box_).0, at(100.0, 0.0, 0.0, 100.0));
1522 assert_eq!(
1524 ClipInset::new().inset(px(-8.0)).resolve(box_).0,
1525 at(-8.0, -8.0, 216.0, 116.0)
1526 );
1527 let pill = ClipInset::new().top(px(40.0)).rounded(px(100.0));
1529 let (rect, radii) = pill.resolve(box_);
1530 assert_eq!(rect, at(0.0, 40.0, 200.0, 60.0));
1531 assert!(
1532 radii.to_array().iter().all(|r| (r.0 - 30.0).abs() < 1e-4),
1533 "{radii:?}"
1534 );
1535 }
1536
1537 #[test]
1538 fn a_clip_inset_contains_what_its_rounded_corners_leave() {
1539 let box_ = size(px(100.0), px(100.0));
1540 let clip = ClipInset::new().inset(px(10.0)).rounded(px(20.0));
1541 assert!(clip.contains(box_, point(px(50.0), px(50.0))));
1542 assert!(!clip.contains(box_, point(px(5.0), px(50.0))));
1544 assert!(!clip.contains(box_, point(px(50.0), px(95.0))));
1545 for (out, inside) in [
1547 ((12.0, 12.0), (18.0, 18.0)),
1548 ((88.0, 12.0), (82.0, 18.0)),
1549 ((88.0, 88.0), (82.0, 82.0)),
1550 ((12.0, 88.0), (18.0, 82.0)),
1551 ] {
1552 assert!(!clip.contains(box_, point(px(out.0), px(out.1))), "{out:?}");
1553 assert!(
1554 clip.contains(box_, point(px(inside.0), px(inside.1))),
1555 "{inside:?}"
1556 );
1557 }
1558 let shut = ClipInset::new()
1560 .bottom(percentage(1.0))
1561 .left(percentage(1.0));
1562 assert!(!shut.contains(box_, point(px(99.0), px(0.0))));
1563 }
1564
1565 #[test]
1566 fn a_clip_inset_outline_keeps_its_segments() {
1567 use crate::shape::Segment;
1568 let kinds = |clip: ClipInset| {
1569 let mut out = Vec::new();
1570 clip.outline(size(px(100.0), px(50.0)), &mut |s| {
1571 out.push(std::mem::discriminant(&s));
1572 });
1573 out
1574 };
1575 let shut = ClipInset::new()
1578 .bottom(percentage(1.0))
1579 .left(percentage(1.0));
1580 let open = ClipInset::new().rounded(px(12.0));
1581 assert_eq!(kinds(shut), kinds(open));
1582 assert_eq!(kinds(open).len(), 10);
1583 let mut last = None;
1584 open.outline(size(px(100.0), px(50.0)), &mut |s| {
1585 if let Segment::Cubic([_, _, to]) = s {
1586 last = Some(to);
1587 }
1588 });
1589 assert_eq!(last, Some(point(px(12.0), px(0.0))));
1591 }
1592
1593 #[test]
1594 fn a_clip_inset_interpolates_lengths_and_percentages_together() {
1595 let from = ClipInset::new()
1596 .bottom(percentage(1.0))
1597 .left(px(40.0))
1598 .rounded(px(0.0));
1599 let to = ClipInset::new().bottom(px(10.0)).rounded(px(16.0));
1600 let half = from.lerp(&to, 0.5);
1601 assert_eq!(
1603 (half.offsets.bottom, half.fractions.bottom),
1604 (px(5.0), percentage(0.5))
1605 );
1606 assert_eq!(
1607 (half.offsets.left, half.fractions.left),
1608 (px(20.0), percentage(0.0))
1609 );
1610 assert_eq!(half.radii, Corners::all(px(8.0)));
1611 assert_eq!(
1612 half.resolve(size(px(100.0), px(100.0))).0.size.height,
1613 px(45.0)
1614 );
1615 assert_eq!(from.lerp(&to, -0.5).radii, Corners::all(px(0.0)));
1617 assert_eq!(from.lerp(&to, 1.0), to);
1618 }
1619
1620 #[test]
1621 fn stops_spread_evenly() {
1622 let c = Color::BLACK;
1623 let g = Gradient {
1624 kind: GradientKind::Linear { angle: deg(90.0) },
1625 stops: vec![
1626 ColorStop {
1627 color: c,
1628 position: None,
1629 },
1630 ColorStop {
1631 color: c,
1632 position: None,
1633 },
1634 ColorStop {
1635 color: c,
1636 position: Some(DefiniteLength::from(percentage(0.8))),
1637 },
1638 ColorStop {
1639 color: c,
1640 position: Some(DefiniteLength::from(percentage(0.5))),
1641 },
1642 ],
1643 repeating: false,
1644 };
1645 let p: Vec<f32> = g
1646 .resolved_stops(size(px(100.0), px(100.0)))
1647 .into_iter()
1648 .map(|(_, p)| p.0)
1649 .collect();
1650 assert_eq!(p, [0.0, 0.4, 0.8, 0.8]);
1651 }
1652
1653 #[test]
1654 fn negative_stops_resolve_to_zero() {
1655 let stop = |p: f32| ColorStop {
1656 color: Color::BLACK,
1657 position: Some(DefiniteLength::from(percentage(p))),
1658 };
1659 let mut g = Gradient {
1660 kind: GradientKind::Linear { angle: deg(180.0) },
1661 stops: vec![stop(-0.5), stop(1.0)],
1662 repeating: false,
1663 };
1664 let positions = |g: &Gradient| -> Vec<f32> {
1665 g.resolved_stops(size(px(100.0), px(40.0)))
1666 .into_iter()
1667 .map(|(_, p)| p.0)
1668 .collect()
1669 };
1670 assert_eq!(positions(&g), [0.0, 1.0]);
1671 g.stops = vec![
1672 stop(-0.5),
1673 ColorStop {
1674 color: Color::BLACK,
1675 position: Some(DefiniteLength::from(px(-20.0))),
1676 },
1677 stop(1.0),
1678 ];
1679 assert_eq!(positions(&g), [0.0, 0.0, 1.0]);
1680 }
1681
1682 #[test]
1683 fn lengths_resolve_against_the_line() {
1684 let c = Color::BLACK;
1685 let stop = |p: Option<DefiniteLength>| ColorStop {
1686 color: c,
1687 position: p,
1688 };
1689 let mut g = Gradient {
1690 kind: GradientKind::Linear { angle: deg(90.0) },
1691 stops: vec![
1692 stop(Some(DefiniteLength::from(px(0.0)))),
1693 stop(Some(DefiniteLength::from(px(10.0)))),
1694 stop(None),
1695 stop(Some(DefiniteLength::from(percentage(0.5)))),
1696 ],
1697 repeating: true,
1698 };
1699 assert!(g.has_lengths());
1700 let p: Vec<f32> = g
1702 .resolved_stops(size(px(200.0), px(50.0)))
1703 .into_iter()
1704 .map(|(_, p)| p.0)
1705 .collect();
1706 assert_eq!(p, [0.0, 0.05, 0.275, 0.5]);
1707 g.kind = GradientKind::Linear { angle: deg(180.0) };
1709 assert!((g.resolved_stops(size(px(200.0), px(50.0)))[1].1.0 - 0.2).abs() < 1e-6);
1710 g.kind = GradientKind::Linear { angle: deg(45.0) };
1712 let line = g.line_length(size(px(100.0), px(100.0)));
1713 assert!((line.0 - 100.0 * std::f32::consts::SQRT_2).abs() < 1e-3);
1714 g.kind = GradientKind::Radial {
1717 circle: true,
1718 size: GradientSize::FarthestSide,
1719 x: percentage(0.5),
1720 y: percentage(0.5),
1721 };
1722 assert!((g.line_length(size(px(200.0), px(100.0))).0 - 100.0).abs() < 1e-4);
1723 assert!((g.resolved_stops(size(px(200.0), px(100.0)))[1].1.0 - 0.1).abs() < 1e-6);
1724 g.kind = GradientKind::Linear { angle: deg(90.0) };
1727 let p: Vec<f32> = g
1728 .resolved_stops(size(px(0.0), px(0.0)))
1729 .into_iter()
1730 .map(|(_, p)| p.0)
1731 .collect();
1732 assert_eq!(p[0], 0.0);
1733 assert!(p.windows(2).all(|w| w[0] <= w[1]));
1734 }
1735
1736 fn bands(stops: &[(Color, f32)], repeating: bool) -> Gradient {
1739 Gradient {
1740 kind: GradientKind::Linear { angle: deg(90.0) },
1741 stops: stops
1742 .iter()
1743 .map(|&(color, p)| ColorStop {
1744 color,
1745 position: Some(DefiniteLength::from(percentage(p))),
1746 })
1747 .collect(),
1748 repeating,
1749 }
1750 }
1751
1752 #[test]
1757 fn repeating_stops_unroll_over_the_line() {
1758 let (red, blue) = (Color(0xff00_00ff), Color(0x0000_ffff));
1759 let box_size = size(px(100.0), px(100.0));
1760 let g = bands(&[(red, 0.0), (blue, 0.1)], true);
1761 let stops = g.unrolled_stops(box_size, percentage(1.0));
1762 assert!(stops.iter().all(|s| (0.0..=1.0).contains(&s.1.0)));
1763 assert!(stops.windows(2).all(|w| w[0].1 <= w[1].1));
1764 assert_eq!(stops[0], (red, percentage(0.0)));
1765 assert_eq!(stops[stops.len() - 1].1, percentage(1.0));
1766 for k in 1..10 {
1767 let at = |c: Color| {
1768 stops
1769 .iter()
1770 .any(|s| s.0 == c && (s.1.0 - k as f32 * 0.1).abs() < 1e-4)
1771 };
1772 assert!(at(red) && at(blue), "{k}: {stops:?}");
1773 }
1774 let g = bands(&[(red, 0.125), (blue, 0.375)], true);
1777 let stops = g.unrolled_stops(box_size, percentage(1.0));
1778 let purple = Color(0x8000_80ff);
1779 assert_eq!(stops[0], (purple, percentage(0.0)));
1780 assert_eq!(stops[stops.len() - 1], (purple, percentage(1.0)));
1781 assert!(stops.windows(2).all(|w| w[0].1 <= w[1].1));
1782 let g = bands(&[(red, 0.0), (Color::TRANSPARENT, 0.3)], true);
1784 let stops = g.unrolled_stops(box_size, percentage(1.0));
1785 assert_eq!(stops[stops.len() - 1].0.0 & 0xffff_ff00, 0xff00_0000);
1786 let g = bands(&[(red, 0.0), (blue, 0.1)], true);
1788 let stops = g.unrolled_stops(box_size, percentage(2.0));
1789 assert_eq!(stops[stops.len() - 1].1, percentage(1.0));
1790 let blue_at = |p: f32| {
1791 stops
1792 .iter()
1793 .any(|s| s.0 == blue && (s.1.0 - p).abs() < 1e-4)
1794 };
1795 assert!(blue_at(0.05) && blue_at(0.95), "{stops:?}");
1796 }
1797
1798 #[test]
1803 fn repeating_stops_stay_in_order() {
1804 let (red, clear) = (Color(0xff00_004d), Color::TRANSPARENT);
1805 let stop = |color, at: f32| ColorStop {
1806 color,
1807 position: Some(DefiniteLength::from(px(at))),
1808 };
1809 let hatch = Gradient {
1810 kind: GradientKind::Linear { angle: deg(-45.0) },
1811 stops: vec![
1812 stop(red, 0.0),
1813 stop(red, 1.0),
1814 stop(clear, 1.0),
1815 stop(clear, 6.0),
1816 ],
1817 repeating: true,
1818 };
1819 for width in 100..400 {
1820 let box_size = size(px(width as f32 * 0.75), px(140.0));
1821 let stops = hatch.unrolled_stops(box_size, percentage(1.0));
1822 assert!(
1823 stops.windows(2).all(|w| w[0].1 <= w[1].1),
1824 "{width}: {stops:?}"
1825 );
1826 }
1827 }
1828
1829 #[test]
1833 fn other_stops_unroll_as_resolved() {
1834 let (red, blue) = (Color(0xff00_00ff), Color(0x0000_ffff));
1835 let box_size = size(px(100.0), px(100.0));
1836 for g in [
1837 bands(&[(red, 0.0), (blue, 0.1)], false),
1838 bands(&[(red, 0.0), (blue, 1.5)], false),
1839 bands(&[(red, 0.5), (blue, 0.5)], true),
1840 ] {
1841 assert_eq!(
1842 g.unrolled_stops(box_size, percentage(1.0)),
1843 g.resolved_stops(box_size)
1844 );
1845 }
1846 let hatch = Gradient {
1847 stops: vec![
1848 ColorStop {
1849 color: red,
1850 position: Some(DefiniteLength::from(px(0.0))),
1851 },
1852 ColorStop {
1853 color: blue,
1854 position: Some(DefiniteLength::from(px(1.0))),
1855 },
1856 ],
1857 ..bands(&[], true)
1858 };
1859 let stops = hatch.unrolled_stops(size(px(4000.0), px(10.0)), percentage(1.0));
1860 assert!(stops.len() > 4000, "{}", stops.len());
1861 }
1862
1863 #[test]
1864 fn matrices_compose_in_order() {
1865 let m = compose_color_matrices(&[Filter::Invert(1.0), Filter::Brightness(0.5)]).unwrap();
1866 let apply = |c: f32| m[0] * c + m[4];
1868 assert!((apply(1.0) - 0.0).abs() < 1e-6);
1869 assert!((apply(0.0) - 0.5).abs() < 1e-6);
1870 assert!(compose_color_matrices(&[Filter::Blur(px(2.0))]).is_none());
1871 }
1872
1873 #[test]
1874 fn corner_angles() {
1875 let k = GradientKind::LinearCorner {
1876 right: true,
1877 bottom: false,
1878 };
1879 assert!(
1880 (k.linear_angle(size(px(100.0), px(100.0)))
1881 .unwrap()
1882 .to_degrees()
1883 - 45.0)
1884 .abs()
1885 < 1e-4
1886 );
1887 let k = GradientKind::LinearCorner {
1888 right: true,
1889 bottom: true,
1890 };
1891 assert!(
1892 (k.linear_angle(size(px(100.0), px(100.0)))
1893 .unwrap()
1894 .to_degrees()
1895 - 135.0)
1896 .abs()
1897 < 1e-4
1898 );
1899 }
1900}