Skip to main content

waft_painting/
gradient.rs

1//! Flutter counterpart: `painting/gradient.dart`.
2//!
3//! A gradient is a value: [`Gradient`] is Dart's abstract class as a trait, held as a
4//! [`GradientRef`] the way [`ShapeBorder`](crate::ShapeBorder) is held as a `ShapeBorderRef`,
5//! and its transform is a shared [`GradientTransformRef`] so that every copy a gradient makes of
6//! itself (`scale`, `with_opacity`, `lerp`) holds the same transform object, as Dart's copies do.
7//!
8//! `create_shader` builds Valo's [`Shader`] through the dart:ui `Gradient.linear`, `.radial` and
9//! `.sweep` constructors at the bottom of this file; what Valo's shader has no room for is said
10//! there.
11
12use std::any::Any;
13use std::f64::consts::PI;
14use std::fmt::{self, Debug, Formatter};
15use std::rc::Rc;
16
17use waft_embedder::valo::{FocalCircle, GradientStop, Shader, SpreadMode, TileMode};
18use waft_embedder::{Color, Matrix4, Offset, Rect, lerp_double};
19
20use crate::alignment::AlignmentGeometry;
21use crate::basic_types::TextDirection;
22
23struct ColorsAndStops {
24    colors: Vec<Color>,
25    stops: Vec<f64>,
26}
27
28/// Calculate the color at position `t` of the gradient defined by `colors` and `stops`.
29fn sample(colors: &[Color], stops: &[f64], t: f64) -> Color {
30    debug_assert!(!colors.is_empty());
31    debug_assert!(!stops.is_empty());
32    if t <= stops[0] {
33        return colors[0];
34    }
35    if t >= stops[stops.len() - 1] {
36        return colors[colors.len() - 1];
37    }
38    let index = stops.iter().rposition(|&s| s <= t);
39    debug_assert!(index.is_some());
40    let index = index.unwrap();
41    Color::lerp(
42        Some(colors[index]),
43        Some(colors[index + 1]),
44        (t - stops[index]) / (stops[index + 1] - stops[index]),
45    )
46    .unwrap()
47}
48
49fn interpolate_colors_and_stops(
50    a_colors: &[Color],
51    a_stops: &[f64],
52    b_colors: &[Color],
53    b_stops: &[f64],
54    t: f64,
55) -> ColorsAndStops {
56    debug_assert!(a_colors.len() >= 2);
57    debug_assert!(b_colors.len() >= 2);
58    debug_assert!(a_stops.len() == a_colors.len());
59    debug_assert!(b_stops.len() == b_colors.len());
60    // Dart's `SplayTreeSet<double>`: sorted by `compareTo`, which `total_cmp` matches, duplicates
61    // dropped.
62    let mut interpolated_stops: Vec<f64> = a_stops.iter().chain(b_stops).copied().collect();
63    interpolated_stops.sort_by(f64::total_cmp);
64    interpolated_stops.dedup_by(|a, b| a.total_cmp(b).is_eq());
65    let interpolated_colors = interpolated_stops
66        .iter()
67        .map(|&stop| {
68            Color::lerp(
69                Some(sample(a_colors, a_stops, stop)),
70                Some(sample(b_colors, b_stops, stop)),
71                t,
72            )
73            .unwrap()
74        })
75        .collect();
76    ColorsAndStops {
77        colors: interpolated_colors,
78        stops: interpolated_stops,
79    }
80}
81
82/// A shared, immutable [`GradientTransform`] (Dart's `GradientTransform` reference).
83pub type GradientTransformRef = Rc<dyn GradientTransform>;
84
85/// Base class for transforming gradient shaders without applying the same
86/// transform to the entire canvas.
87///
88/// For example, a [`SweepGradient`] normally starts its gradation at 3 o'clock
89/// and draws clockwise. To have the sweep appear to start at 6 o'clock, supply
90/// a [`GradientRotation`] of `pi/4` radians (i.e. 45 degrees).
91pub trait GradientTransform: Any + Debug {
92    /// When a [`Gradient`] creates its [`Shader`], it will call this method to
93    /// determine what transform to apply to the shader for the given [`Rect`] and
94    /// [`TextDirection`].
95    ///
96    /// Implementers may return None from this method, which achieves the same
97    /// final effect as returning [`Matrix4::IDENTITY`].
98    fn transform(&self, bounds: Rect, text_direction: Option<TextDirection>) -> Option<Matrix4>;
99
100    /// Downcast support for `is` / `as` in Dart.
101    fn as_any(&self) -> &dyn Any;
102
103    /// Field equality. Dart's default `==` is identity; subclasses that override
104    /// `==` implement this.
105    fn eq_transform(&self, other: &dyn GradientTransform) -> bool {
106        std::ptr::addr_eq(self.as_any(), other.as_any())
107    }
108}
109
110impl PartialEq for dyn GradientTransform {
111    fn eq(&self, other: &dyn GradientTransform) -> bool {
112        self.eq_transform(other)
113    }
114}
115
116/// A [`GradientTransform`] that rotates the gradient around the center-point of
117/// its bounding box.
118///
119/// This sample would rotate a sweep gradient by a quarter turn clockwise:
120///
121/// ```ignore
122/// SweepGradient::new(vec![Color::new(0xFFFFFFFF), Color::new(0xFF009900)])
123///     .transform(GradientRotation::new(PI / 4.0));
124/// ```
125#[derive(Clone, Copy, PartialEq)]
126pub struct GradientRotation {
127    /// The angle of rotation in radians in the clockwise direction.
128    pub radians: f64,
129}
130
131impl GradientRotation {
132    /// Constructs a [`GradientRotation`] for the specified angle.
133    ///
134    /// The angle is in radians in the clockwise direction.
135    pub const fn new(radians: f64) -> GradientRotation {
136        GradientRotation { radians }
137    }
138}
139
140impl GradientTransform for GradientRotation {
141    fn transform(&self, bounds: Rect, _text_direction: Option<TextDirection>) -> Option<Matrix4> {
142        let sin_radians = self.radians.sin();
143        let one_minus_cos_radians = 1.0 - self.radians.cos();
144        let center = bounds.center();
145        let origin_x = sin_radians * center.dy() + one_minus_cos_radians * center.dx();
146        let origin_y = -sin_radians * center.dx() + one_minus_cos_radians * center.dy();
147
148        Some(
149            Matrix4::translation(origin_x as f32, origin_y as f32)
150                .then(&Matrix4::rotation(self.radians as f32)),
151        )
152    }
153
154    fn as_any(&self) -> &dyn Any {
155        self
156    }
157
158    fn eq_transform(&self, other: &dyn GradientTransform) -> bool {
159        other
160            .as_any()
161            .downcast_ref::<GradientRotation>()
162            .is_some_and(|other| other == self)
163    }
164}
165
166impl From<GradientRotation> for GradientTransformRef {
167    fn from(rotation: GradientRotation) -> GradientTransformRef {
168        Rc::new(rotation)
169    }
170}
171
172impl Debug for GradientRotation {
173    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
174        write!(f, "GradientRotation(radians: {:.1})", self.radians)
175    }
176}
177
178/// A 2D gradient.
179///
180/// This is an interface that allows [`LinearGradient`], [`RadialGradient`], and
181/// [`SweepGradient`] classes to be used interchangeably in `BoxDecoration`s.
182pub trait Gradient: Any + Debug {
183    /// The colors the gradient should obtain at each of the stops.
184    ///
185    /// If [`stops`](Self::stops) is non-null, this list must have the same length as
186    /// [`stops`](Self::stops).
187    ///
188    /// This list must have at least two colors in it (otherwise, it's not a
189    /// gradient!).
190    fn colors(&self) -> &[Color];
191
192    /// A list of values from 0.0 to 1.0 that denote fractions along the gradient.
193    ///
194    /// If non-null, this list must have the same length as [`colors`](Self::colors).
195    ///
196    /// If the first value is not 0.0, then a stop with position 0.0 and a color
197    /// equal to the first color in [`colors`](Self::colors) is implied.
198    ///
199    /// If the last value is not 1.0, then a stop with position 1.0 and a color
200    /// equal to the last color in [`colors`](Self::colors) is implied.
201    ///
202    /// The values in the [`stops`](Self::stops) list must be in ascending order. If a value in
203    /// the [`stops`](Self::stops) list is less than an earlier value in the list, then its value
204    /// is assumed to equal the previous value.
205    ///
206    /// If stops is null, then a set of uniformly distributed stops is implied,
207    /// with the first stop at 0.0 and the last stop at 1.0.
208    fn stops(&self) -> Option<&[f64]>;
209
210    /// The transform, if any, to apply to the gradient.
211    ///
212    /// This transform is in addition to any other transformations applied to the
213    /// canvas, but does not add any transformations to the canvas.
214    fn transform(&self) -> Option<&GradientTransformRef>;
215
216    /// Creates a [`Shader`] for this gradient to fill the given rect.
217    ///
218    /// If the gradient's configuration is text-direction-dependent, for example
219    /// it uses `AlignmentDirectional` objects instead of `Alignment`
220    /// objects, then the `text_direction` argument must not be null.
221    ///
222    /// The shader's transform will be resolved from the [`transform`](Self::transform) of this
223    /// gradient.
224    fn create_shader(&self, rect: Rect, text_direction: Option<TextDirection>) -> Shader;
225
226    /// Returns a new gradient with its properties scaled by the given factor.
227    ///
228    /// A factor of 0.0 (or less) should result in a variant of the gradient that
229    /// is invisible; any two factors epsilon apart should be unnoticeably
230    /// different from each other at first glance. From this it follows that
231    /// scaling a gradient with values from 1.0 to 0.0 over time should cause the
232    /// gradient to smoothly disappear.
233    ///
234    /// Typically this is the same as interpolating from null (with [`lerp`](GradientRef::lerp)).
235    fn scale(&self, factor: f64) -> GradientRef;
236
237    /// Returns a new [`Gradient`] with each color set to the given opacity.
238    fn with_opacity(&self, opacity: f64) -> GradientRef;
239
240    /// Returns a copy of this gradient with all of its [`colors`](Self::colors) replaced by the
241    /// given `color`.
242    ///
243    /// The geometry of the gradient (such as its [`stops`](Self::stops) and the
244    /// subclass-specific positioning) is preserved, so the result paints as a
245    /// uniform `color`. This is useful to represent a solid color as a gradient,
246    /// for example when interpolating between a color and a gradient with
247    /// [`lerp`](GradientRef::lerp).
248    ///
249    /// Subclasses should override this method to preserve their own geometry. The
250    /// base implementation returns a [`LinearGradient`]; this is sufficient because
251    /// a gradient with uniform colors paints as a solid color regardless of its
252    /// geometry.
253    #[allow(clippy::wrong_self_convention)]
254    fn from_color(&self, color: Color) -> GradientRef {
255        GradientRef::new(LinearGradient {
256            stops: self.stops().map(<[f64]>::to_vec),
257            transform: self.transform().cloned(),
258            ..LinearGradient::new(vec![color; self.colors().len()])
259        })
260    }
261
262    /// Linearly interpolates from another [`Gradient`] to `this`.
263    ///
264    /// When implementing this method in subclasses, return None if this class
265    /// cannot interpolate from `a`. In that case, [`lerp`](GradientRef::lerp) will try `a`'s
266    /// [`lerp_to`](Self::lerp_to) method instead.
267    ///
268    /// If `a` is None, this must not return None. The base class implements this
269    /// by deferring to [`scale`](Self::scale).
270    ///
271    /// Instead of calling this directly, use [`lerp`](GradientRef::lerp).
272    fn lerp_from(&self, a: Option<&dyn Gradient>, t: f64) -> Option<GradientRef> {
273        if a.is_none() {
274            return Some(self.scale(t));
275        }
276        None
277    }
278
279    /// Linearly interpolates from `this` to another [`Gradient`].
280    ///
281    /// This is called if `b`'s [`lerp_to`](Self::lerp_to) did not know how to handle this class.
282    ///
283    /// When implementing this method in subclasses, return None if this class
284    /// cannot interpolate from `b`. In that case, [`lerp`](GradientRef::lerp) will apply a
285    /// default behavior instead.
286    ///
287    /// If `b` is None, this must not return None. The base class implements this
288    /// by deferring to [`scale`](Self::scale).
289    ///
290    /// Instead of calling this directly, use [`lerp`](GradientRef::lerp).
291    fn lerp_to(&self, b: Option<&dyn Gradient>, t: f64) -> Option<GradientRef> {
292        if b.is_none() {
293            return Some(self.scale(1.0 - t));
294        }
295        None
296    }
297
298    /// Downcast support for `is` / `as` in Dart.
299    fn as_any(&self) -> &dyn Any;
300
301    /// Field equality. Dart's default `==` is identity; subclasses that override
302    /// `==` implement this.
303    fn eq_gradient(&self, other: &dyn Gradient) -> bool {
304        std::ptr::addr_eq(self.as_any(), other.as_any())
305    }
306}
307
308impl dyn Gradient {
309    fn implied_stops(&self) -> Vec<f64> {
310        if let Some(stops) = self.stops() {
311            return stops.to_vec();
312        }
313        let colors = self.colors();
314        debug_assert!(
315            colors.len() >= 2,
316            "colors list must have at least two colors"
317        );
318        let separation = 1.0 / (colors.len() as f64 - 1.0);
319        (0..colors.len())
320            .map(|index| index as f64 * separation)
321            .collect()
322    }
323
324    fn resolve_transform(
325        &self,
326        bounds: Rect,
327        text_direction: Option<TextDirection>,
328    ) -> Option<Matrix4> {
329        self.transform()
330            .and_then(|transform| transform.transform(bounds, text_direction))
331    }
332}
333
334/// A [`Gradient`] held by value: what a Dart field or parameter typed `Gradient` becomes.
335///
336/// Clones share one gradient, as Dart's references do, so a gradient handed on keeps its
337/// identity. Two refs are equal when they share a gradient or when
338/// [`eq_gradient`](Gradient::eq_gradient) says so, Dart's `==`.
339#[derive(Clone)]
340pub struct GradientRef(Rc<dyn Gradient>);
341
342impl GradientRef {
343    /// Erases a [`Gradient`].
344    pub fn new(gradient: impl Gradient) -> GradientRef {
345        GradientRef(Rc::new(gradient))
346    }
347
348    /// Linearly interpolates between two [`Gradient`]s.
349    ///
350    /// This defers to `b`'s [`lerp_to`](Gradient::lerp_to) function if `b` is not None. If `b` is
351    /// None or if its [`lerp_to`](Gradient::lerp_to) returns None, it uses `a`'s
352    /// [`lerp_from`](Gradient::lerp_from) function instead. If both return None, it returns `a`
353    /// before `t == 0.5` and `b` after `t == 0.5`.
354    pub fn lerp(a: Option<&GradientRef>, b: Option<&GradientRef>, t: f64) -> Option<GradientRef> {
355        match (a, b) {
356            (None, None) => return None,
357            (Some(a), Some(b)) if Rc::ptr_eq(&a.0, &b.0) => return Some(a.clone()),
358            _ => {}
359        }
360        let (a_gradient, b_gradient) = (a.map(|a| &*a.0), b.map(|b| &*b.0));
361        let mut result = None;
362        if let Some(b) = b_gradient {
363            result = b.lerp_from(a_gradient, t); // if a is None, this must return Some
364        }
365        if result.is_none()
366            && let Some(a) = a_gradient
367        {
368            result = a.lerp_to(b_gradient, t); // if b is None, this must return Some
369        }
370        if result.is_some() {
371            return result;
372        }
373        debug_assert!(a.is_some() && b.is_some());
374        Some(if t < 0.5 {
375            a.unwrap().scale(1.0 - (t * 2.0))
376        } else {
377            b.unwrap().scale((t - 0.5) * 2.0)
378        })
379    }
380}
381
382impl<T: Gradient> From<T> for GradientRef {
383    fn from(gradient: T) -> GradientRef {
384        GradientRef::new(gradient)
385    }
386}
387
388impl std::ops::Deref for GradientRef {
389    type Target = dyn Gradient;
390
391    fn deref(&self) -> &dyn Gradient {
392        &*self.0
393    }
394}
395
396impl PartialEq for GradientRef {
397    fn eq(&self, other: &GradientRef) -> bool {
398        Rc::ptr_eq(&self.0, &other.0) || self.0.eq_gradient(&*other.0)
399    }
400}
401
402impl Debug for GradientRef {
403    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
404        Debug::fmt(&*self.0, f)
405    }
406}
407
408/// Dart's `Gradient.toString`, which the inner gradient's [`Debug`] already renders.
409impl fmt::Display for GradientRef {
410    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
411        Debug::fmt(self, f)
412    }
413}
414
415impl PartialEq for dyn Gradient {
416    fn eq(&self, other: &dyn Gradient) -> bool {
417        self.eq_gradient(other)
418    }
419}
420
421fn boxed<T: Gradient>(gradient: Option<T>) -> Option<GradientRef> {
422    gradient.map(GradientRef::new)
423}
424
425/// Dart's `TileMode.toString()`.
426fn tile_mode_name(tile_mode: TileMode) -> &'static str {
427    match tile_mode {
428        TileMode::Clamp => "TileMode.clamp",
429        TileMode::Repeat => "TileMode.repeated",
430        TileMode::Mirror => "TileMode.mirror",
431        TileMode::Decal => "TileMode.decal",
432    }
433}
434
435/// A 2D linear gradient.
436///
437/// This class is used by `BoxDecoration` to represent linear gradients. This
438/// abstracts out the arguments to the dart:ui `Gradient.linear` constructor.
439///
440/// A gradient has two anchor points, [`begin`](Self::begin) and [`end`](Self::end). The
441/// [`begin`](Self::begin) point corresponds to 0.0, and the [`end`](Self::end) point corresponds
442/// to 1.0. These points are expressed in fractions, so that the same gradient can be reused with
443/// varying sized boxes without changing the parameters. (This contrasts with dart:ui
444/// `Gradient.linear`, whose arguments are expressed in logical pixels.)
445///
446/// The [`colors`](Self::colors) are described by a list of [`Color`] objects. There must be at
447/// least two colors. The [`stops`](Self::stops) list, if specified, must have the same length
448/// as [`colors`](Self::colors). It specifies fractions of the vector from start to end, between
449/// 0.0 and 1.0, for each color. If it is null, a uniform distribution is
450/// assumed.
451///
452/// The region of the canvas before [`begin`](Self::begin) and after [`end`](Self::end) is
453/// colored according to [`tile_mode`](Self::tile_mode).
454///
455/// Typically this class is used with `BoxDecoration`, which does the painting.
456/// To use a [`LinearGradient`] to paint on a canvas directly, see
457/// [`create_shader`](Gradient::create_shader).
458#[derive(Clone, PartialEq)]
459pub struct LinearGradient {
460    /// The offset at which stop 0.0 of the gradient is placed.
461    ///
462    /// If this is an `Alignment`, then it is expressed as a vector from
463    /// coordinate (0.0, 0.0), in a coordinate space that maps the center of the
464    /// paint box at (0.0, 0.0) and the bottom right at (1.0, 1.0).
465    ///
466    /// It can also be an `AlignmentDirectional`, where the start is the
467    /// left in left-to-right contexts and the right in right-to-left contexts. If
468    /// a text-direction-dependent value is provided here, then the
469    /// [`create_shader`](Gradient::create_shader) method will need to be given a
470    /// [`TextDirection`].
471    pub begin: AlignmentGeometry,
472    /// The offset at which stop 1.0 of the gradient is placed.
473    ///
474    /// See [`begin`](Self::begin) for how the coordinates are mapped.
475    pub end: AlignmentGeometry,
476    /// The colors the gradient should obtain at each of the stops.
477    pub colors: Vec<Color>,
478    /// A list of values from 0.0 to 1.0 that denote fractions along the gradient.
479    pub stops: Option<Vec<f64>>,
480    /// How this gradient should tile the plane beyond in the region before
481    /// [`begin`](Self::begin) and after [`end`](Self::end).
482    pub tile_mode: TileMode,
483    /// The transform, if any, to apply to the gradient.
484    pub transform: Option<GradientTransformRef>,
485}
486
487impl LinearGradient {
488    /// Creates a linear gradient.
489    ///
490    /// If [`stops`](Self::stops) is non-null, it must have the same length as
491    /// [`colors`](Self::colors).
492    pub fn new(colors: Vec<Color>) -> LinearGradient {
493        LinearGradient {
494            begin: AlignmentGeometry::CENTER_LEFT,
495            end: AlignmentGeometry::CENTER_RIGHT,
496            colors,
497            stops: None,
498            tile_mode: TileMode::Clamp,
499            transform: None,
500        }
501    }
502
503    /// Dart `LinearGradient(begin:)`.
504    pub fn begin(mut self, begin: impl Into<AlignmentGeometry>) -> LinearGradient {
505        self.begin = begin.into();
506        self
507    }
508
509    /// Dart `LinearGradient(end:)`.
510    pub fn end(mut self, end: impl Into<AlignmentGeometry>) -> LinearGradient {
511        self.end = end.into();
512        self
513    }
514
515    /// Dart `LinearGradient(stops:)`.
516    pub fn stops(mut self, stops: Vec<f64>) -> LinearGradient {
517        self.stops = Some(stops);
518        self
519    }
520
521    /// Dart `LinearGradient(tileMode:)`.
522    pub fn tile_mode(mut self, tile_mode: TileMode) -> LinearGradient {
523        self.tile_mode = tile_mode;
524        self
525    }
526
527    /// Dart `LinearGradient(transform:)`.
528    pub fn transform(mut self, transform: impl Into<GradientTransformRef>) -> LinearGradient {
529        self.transform = Some(transform.into());
530        self
531    }
532
533    /// Returns a new [`LinearGradient`] with its colors scaled by the given factor.
534    ///
535    /// Since the alpha component of the Color is what is scaled, a factor
536    /// of 0.0 or less results in a gradient that is fully transparent.
537    pub fn scale(&self, factor: f64) -> LinearGradient {
538        LinearGradient {
539            colors: self
540                .colors
541                .iter()
542                .map(|&color| Color::lerp(None, Some(color), factor).unwrap())
543                .collect(),
544            ..self.clone()
545        }
546    }
547
548    /// Dart's `LinearGradient.fromColor`: the geometry kept, every color replaced by `color`.
549    pub fn from_color(&self, color: Color) -> LinearGradient {
550        LinearGradient {
551            colors: vec![color; self.colors.len()],
552            ..self.clone()
553        }
554    }
555
556    /// Linearly interpolate between two [`LinearGradient`]s.
557    ///
558    /// If either gradient is None, this function linearly interpolates from
559    /// a gradient that matches the other gradient in [`begin`](Self::begin),
560    /// [`end`](Self::end), [`stops`](Self::stops) and [`tile_mode`](Self::tile_mode) and with the
561    /// same [`colors`](Self::colors) but transparent (using [`scale`](Self::scale)).
562    ///
563    /// If neither gradient is None, they must have the same number of [`colors`](Self::colors).
564    pub fn lerp(
565        a: Option<&LinearGradient>,
566        b: Option<&LinearGradient>,
567        t: f64,
568    ) -> Option<LinearGradient> {
569        let (a, b) = match (a, b) {
570            (None, None) => return None,
571            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
572            (None, Some(b)) => return Some(b.scale(t)),
573            (Some(a), None) => return Some(a.scale(1.0 - t)),
574            (Some(a), Some(b)) => (a, b),
575        };
576        let interpolated = interpolate_colors_and_stops(
577            &a.colors,
578            &<dyn Gradient>::implied_stops(a),
579            &b.colors,
580            &<dyn Gradient>::implied_stops(b),
581            t,
582        );
583        Some(LinearGradient {
584            begin: AlignmentGeometry::lerp(Some(a.begin), Some(b.begin), t).unwrap(),
585            end: AlignmentGeometry::lerp(Some(a.end), Some(b.end), t).unwrap(),
586            colors: interpolated.colors,
587            stops: Some(interpolated.stops),
588            // TODO(ianh): interpolate tile mode
589            tile_mode: if t < 0.5 { a.tile_mode } else { b.tile_mode },
590            transform: if t < 0.5 {
591                a.transform.clone()
592            } else {
593                b.transform.clone()
594            },
595        })
596    }
597
598    /// Returns a new [`LinearGradient`] with each color set to the given opacity.
599    #[allow(deprecated)]
600    pub fn with_opacity(&self, opacity: f64) -> LinearGradient {
601        LinearGradient {
602            colors: self
603                .colors
604                .iter()
605                .map(|color| color.with_opacity(opacity))
606                .collect(),
607            ..self.clone()
608        }
609    }
610}
611
612impl Gradient for LinearGradient {
613    fn colors(&self) -> &[Color] {
614        &self.colors
615    }
616
617    fn stops(&self) -> Option<&[f64]> {
618        self.stops.as_deref()
619    }
620
621    fn transform(&self) -> Option<&GradientTransformRef> {
622        self.transform.as_ref()
623    }
624
625    fn create_shader(&self, rect: Rect, text_direction: Option<TextDirection>) -> Shader {
626        gradient_linear(
627            self.begin.resolve(text_direction).within_rect(rect),
628            self.end.resolve(text_direction).within_rect(rect),
629            &self.colors,
630            Some(&<dyn Gradient>::implied_stops(self)),
631            self.tile_mode,
632            <dyn Gradient>::resolve_transform(self, rect, text_direction),
633        )
634    }
635
636    fn scale(&self, factor: f64) -> GradientRef {
637        GradientRef::new(LinearGradient::scale(self, factor))
638    }
639
640    fn with_opacity(&self, opacity: f64) -> GradientRef {
641        GradientRef::new(LinearGradient::with_opacity(self, opacity))
642    }
643
644    fn from_color(&self, color: Color) -> GradientRef {
645        GradientRef::new(LinearGradient::from_color(self, color))
646    }
647
648    fn lerp_from(&self, a: Option<&dyn Gradient>, t: f64) -> Option<GradientRef> {
649        match a {
650            None => boxed(LinearGradient::lerp(None, Some(self), t)),
651            Some(a) => {
652                let a = a.as_any().downcast_ref::<LinearGradient>()?;
653                boxed(LinearGradient::lerp(Some(a), Some(self), t))
654            }
655        }
656    }
657
658    fn lerp_to(&self, b: Option<&dyn Gradient>, t: f64) -> Option<GradientRef> {
659        match b {
660            None => boxed(LinearGradient::lerp(Some(self), None, t)),
661            Some(b) => {
662                let b = b.as_any().downcast_ref::<LinearGradient>()?;
663                boxed(LinearGradient::lerp(Some(self), Some(b), t))
664            }
665        }
666    }
667
668    fn as_any(&self) -> &dyn Any {
669        self
670    }
671
672    fn eq_gradient(&self, other: &dyn Gradient) -> bool {
673        other
674            .as_any()
675            .downcast_ref::<LinearGradient>()
676            .is_some_and(|other| other == self)
677    }
678}
679
680impl Debug for LinearGradient {
681    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
682        write!(
683            f,
684            "LinearGradient(begin: {:?}, end: {:?}, colors: {:?}",
685            self.begin, self.end, self.colors
686        )?;
687        if let Some(stops) = &self.stops {
688            write!(f, ", stops: {stops:?}")?;
689        }
690        write!(f, ", tileMode: {}", tile_mode_name(self.tile_mode))?;
691        if let Some(transform) = &self.transform {
692            write!(f, ", transform: {transform:?}")?;
693        }
694        write!(f, ")")
695    }
696}
697
698/// A 2D radial gradient.
699///
700/// This class is used by `BoxDecoration` to represent radial gradients. This
701/// abstracts out the arguments to the dart:ui `Gradient.radial` constructor.
702///
703/// A normal radial gradient has a [`center`](Self::center) and a [`radius`](Self::radius). The
704/// [`center`](Self::center) point corresponds to 0.0, and the ring at [`radius`](Self::radius)
705/// from the center corresponds to 1.0. These lengths are expressed in fractions, so that the
706/// same gradient can be reused with varying sized boxes without changing the parameters.
707/// (This contrasts with dart:ui `Gradient.radial`, whose arguments are expressed in logical
708/// pixels.)
709///
710/// It is also possible to create a two-point (or focal pointed) radial gradient
711/// (which is sometimes referred to as a two point conic gradient, but is not the
712/// same as a CSS conic gradient which corresponds to a [`SweepGradient`]). A
713/// [`focal`](Self::focal) point and [`focal_radius`](Self::focal_radius) can be specified
714/// similarly to [`center`](Self::center) and [`radius`](Self::radius), which will make the
715/// rendered gradient appear to be pointed or directed in the direction of the
716/// [`focal`](Self::focal) point. This is only important if [`focal`](Self::focal) and
717/// [`center`](Self::center) are not equal or [`focal_radius`](Self::focal_radius) > 0.0 (as this
718/// case is visually identical to a normal radial gradient). One important case to avoid is
719/// having [`focal`](Self::focal) and [`center`](Self::center) both resolve to
720/// [`Offset::ZERO`] when [`focal_radius`](Self::focal_radius) > 0.0. In such a case, a valid
721/// shader cannot be created by the framework.
722///
723/// The [`colors`](Self::colors) are described by a list of [`Color`] objects. There must be at
724/// least two colors. The [`stops`](Self::stops) list, if specified, must have the same length
725/// as [`colors`](Self::colors). It specifies fractions of the radius between 0.0 and 1.0,
726/// giving concentric rings for each color stop. If it is null, a uniform
727/// distribution is assumed.
728///
729/// The region of the canvas beyond [`radius`](Self::radius) from the [`center`](Self::center)
730/// is colored according to [`tile_mode`](Self::tile_mode).
731#[derive(Clone, PartialEq)]
732pub struct RadialGradient {
733    /// The center of the gradient, as an offset into the (-1.0, -1.0) x (1.0, 1.0)
734    /// square describing the gradient which will be mapped onto the paint box.
735    ///
736    /// For example, an alignment of (0.0, 0.0) will place the radial
737    /// gradient in the center of the box.
738    ///
739    /// It can also be an `AlignmentDirectional`, where the start is the left in
740    /// left-to-right contexts and the right in right-to-left contexts. If a
741    /// text-direction-dependent value is provided here, then the
742    /// [`create_shader`](Gradient::create_shader) method will need to be given a
743    /// [`TextDirection`].
744    pub center: AlignmentGeometry,
745    /// The radius of the gradient, as a fraction of the shortest side
746    /// of the paint box.
747    ///
748    /// For example, if a radial gradient is painted on a box that is
749    /// 100.0 pixels wide and 200.0 pixels tall, then a radius of 1.0
750    /// will place the 1.0 stop at 100.0 pixels from the [`center`](Self::center).
751    pub radius: f64,
752    /// The colors the gradient should obtain at each of the stops.
753    pub colors: Vec<Color>,
754    /// A list of values from 0.0 to 1.0 that denote fractions along the gradient.
755    pub stops: Option<Vec<f64>>,
756    /// How this gradient should tile the plane beyond the outer ring at
757    /// [`radius`](Self::radius) pixels from the [`center`](Self::center).
758    pub tile_mode: TileMode,
759    /// The focal point of the gradient. If specified, the gradient will appear
760    /// to be focused along the vector from [`center`](Self::center) to focal.
761    ///
762    /// See [`center`](Self::center) for a description of how the coordinates are mapped.
763    ///
764    /// If this value is specified and [`focal_radius`](Self::focal_radius) > 0.0, care should
765    /// be taken to ensure that either this value or [`center`](Self::center) will not both
766    /// resolve to [`Offset::ZERO`], which would fail to create a valid gradient.
767    pub focal: Option<AlignmentGeometry>,
768    /// The radius of the focal point of gradient, as a fraction of the shortest
769    /// side of the paint box.
770    ///
771    /// For example, if a radial gradient is painted on a box that is
772    /// 100.0 pixels wide and 200.0 pixels tall, then a radius of 1.0
773    /// will place the 1.0 stop at 100.0 pixels from the [`focal`](Self::focal) point.
774    ///
775    /// If this value is specified and is greater than 0.0, either [`focal`](Self::focal) or
776    /// [`center`](Self::center) must not resolve to [`Offset::ZERO`], which would fail to
777    /// create a valid gradient.
778    pub focal_radius: f64,
779    /// The transform, if any, to apply to the gradient.
780    pub transform: Option<GradientTransformRef>,
781}
782
783impl RadialGradient {
784    /// Creates a radial gradient.
785    ///
786    /// If [`stops`](Self::stops) is non-null, it must have the same length as
787    /// [`colors`](Self::colors).
788    pub fn new(colors: Vec<Color>) -> RadialGradient {
789        RadialGradient {
790            center: AlignmentGeometry::CENTER,
791            radius: 0.5,
792            colors,
793            stops: None,
794            tile_mode: TileMode::Clamp,
795            focal: None,
796            focal_radius: 0.0,
797            transform: None,
798        }
799    }
800
801    /// Dart `RadialGradient(center:)`.
802    pub fn center(mut self, center: impl Into<AlignmentGeometry>) -> RadialGradient {
803        self.center = center.into();
804        self
805    }
806
807    /// Dart `RadialGradient(radius:)`.
808    pub fn radius(mut self, radius: f64) -> RadialGradient {
809        self.radius = radius;
810        self
811    }
812
813    /// Dart `RadialGradient(stops:)`.
814    pub fn stops(mut self, stops: Vec<f64>) -> RadialGradient {
815        self.stops = Some(stops);
816        self
817    }
818
819    /// Dart `RadialGradient(tileMode:)`.
820    pub fn tile_mode(mut self, tile_mode: TileMode) -> RadialGradient {
821        self.tile_mode = tile_mode;
822        self
823    }
824
825    /// Dart `RadialGradient(focal:)`.
826    pub fn focal(mut self, focal: impl Into<AlignmentGeometry>) -> RadialGradient {
827        self.focal = Some(focal.into());
828        self
829    }
830
831    /// Dart `RadialGradient(focalRadius:)`.
832    pub fn focal_radius(mut self, focal_radius: f64) -> RadialGradient {
833        self.focal_radius = focal_radius;
834        self
835    }
836
837    /// Dart `RadialGradient(transform:)`.
838    pub fn transform(mut self, transform: impl Into<GradientTransformRef>) -> RadialGradient {
839        self.transform = Some(transform.into());
840        self
841    }
842
843    /// Returns a new [`RadialGradient`] with its colors scaled by the given factor.
844    ///
845    /// Since the alpha component of the Color is what is scaled, a factor
846    /// of 0.0 or less results in a gradient that is fully transparent.
847    pub fn scale(&self, factor: f64) -> RadialGradient {
848        RadialGradient {
849            colors: self
850                .colors
851                .iter()
852                .map(|&color| Color::lerp(None, Some(color), factor).unwrap())
853                .collect(),
854            ..self.clone()
855        }
856    }
857
858    /// Dart's `RadialGradient.fromColor`: the geometry kept, every color replaced by `color`.
859    pub fn from_color(&self, color: Color) -> RadialGradient {
860        RadialGradient {
861            colors: vec![color; self.colors.len()],
862            ..self.clone()
863        }
864    }
865
866    /// Linearly interpolate between two [`RadialGradient`]s.
867    ///
868    /// If either gradient is None, this function linearly interpolates from
869    /// a gradient that matches the other gradient in [`center`](Self::center),
870    /// [`radius`](Self::radius), [`stops`](Self::stops) and [`tile_mode`](Self::tile_mode) and
871    /// with the same [`colors`](Self::colors) but transparent (using [`scale`](Self::scale)).
872    ///
873    /// If neither gradient is None, they must have the same number of [`colors`](Self::colors).
874    pub fn lerp(
875        a: Option<&RadialGradient>,
876        b: Option<&RadialGradient>,
877        t: f64,
878    ) -> Option<RadialGradient> {
879        let (a, b) = match (a, b) {
880            (None, None) => return None,
881            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
882            (None, Some(b)) => return Some(b.scale(t)),
883            (Some(a), None) => return Some(a.scale(1.0 - t)),
884            (Some(a), Some(b)) => (a, b),
885        };
886        let interpolated = interpolate_colors_and_stops(
887            &a.colors,
888            &<dyn Gradient>::implied_stops(a),
889            &b.colors,
890            &<dyn Gradient>::implied_stops(b),
891            t,
892        );
893        Some(RadialGradient {
894            center: AlignmentGeometry::lerp(Some(a.center), Some(b.center), t).unwrap(),
895            radius: lerp_double(Some(a.radius), Some(b.radius), t)
896                .unwrap()
897                .max(0.0),
898            colors: interpolated.colors,
899            stops: Some(interpolated.stops),
900            // TODO(ianh): interpolate tile mode
901            tile_mode: if t < 0.5 { a.tile_mode } else { b.tile_mode },
902            focal: AlignmentGeometry::lerp(a.focal, b.focal, t),
903            focal_radius: lerp_double(Some(a.focal_radius), Some(b.focal_radius), t)
904                .unwrap()
905                .max(0.0),
906            transform: if t < 0.5 {
907                a.transform.clone()
908            } else {
909                b.transform.clone()
910            },
911        })
912    }
913
914    /// Returns a new [`RadialGradient`] with each color set to the given opacity.
915    #[allow(deprecated)]
916    pub fn with_opacity(&self, opacity: f64) -> RadialGradient {
917        RadialGradient {
918            colors: self
919                .colors
920                .iter()
921                .map(|color| color.with_opacity(opacity))
922                .collect(),
923            ..self.clone()
924        }
925    }
926}
927
928impl Gradient for RadialGradient {
929    fn colors(&self) -> &[Color] {
930        &self.colors
931    }
932
933    fn stops(&self) -> Option<&[f64]> {
934        self.stops.as_deref()
935    }
936
937    fn transform(&self) -> Option<&GradientTransformRef> {
938        self.transform.as_ref()
939    }
940
941    fn create_shader(&self, rect: Rect, text_direction: Option<TextDirection>) -> Shader {
942        gradient_radial(
943            self.center.resolve(text_direction).within_rect(rect),
944            self.radius * rect.shortest_side(),
945            &self.colors,
946            Some(&<dyn Gradient>::implied_stops(self)),
947            self.tile_mode,
948            <dyn Gradient>::resolve_transform(self, rect, text_direction),
949            self.focal
950                .map(|focal| focal.resolve(text_direction).within_rect(rect)),
951            self.focal_radius * rect.shortest_side(),
952        )
953    }
954
955    fn scale(&self, factor: f64) -> GradientRef {
956        GradientRef::new(RadialGradient::scale(self, factor))
957    }
958
959    fn with_opacity(&self, opacity: f64) -> GradientRef {
960        GradientRef::new(RadialGradient::with_opacity(self, opacity))
961    }
962
963    fn from_color(&self, color: Color) -> GradientRef {
964        GradientRef::new(RadialGradient::from_color(self, color))
965    }
966
967    fn lerp_from(&self, a: Option<&dyn Gradient>, t: f64) -> Option<GradientRef> {
968        match a {
969            None => boxed(RadialGradient::lerp(None, Some(self), t)),
970            Some(a) => {
971                let a = a.as_any().downcast_ref::<RadialGradient>()?;
972                boxed(RadialGradient::lerp(Some(a), Some(self), t))
973            }
974        }
975    }
976
977    fn lerp_to(&self, b: Option<&dyn Gradient>, t: f64) -> Option<GradientRef> {
978        match b {
979            None => boxed(RadialGradient::lerp(Some(self), None, t)),
980            Some(b) => {
981                let b = b.as_any().downcast_ref::<RadialGradient>()?;
982                boxed(RadialGradient::lerp(Some(self), Some(b), t))
983            }
984        }
985    }
986
987    fn as_any(&self) -> &dyn Any {
988        self
989    }
990
991    fn eq_gradient(&self, other: &dyn Gradient) -> bool {
992        other
993            .as_any()
994            .downcast_ref::<RadialGradient>()
995            .is_some_and(|other| other == self)
996    }
997}
998
999impl Debug for RadialGradient {
1000    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1001        write!(
1002            f,
1003            "RadialGradient(center: {:?}, radius: {:.1}, colors: {:?}",
1004            self.center, self.radius, self.colors
1005        )?;
1006        if let Some(stops) = &self.stops {
1007            write!(f, ", stops: {stops:?}")?;
1008        }
1009        write!(f, ", tileMode: {}", tile_mode_name(self.tile_mode))?;
1010        if let Some(focal) = &self.focal {
1011            write!(f, ", focal: {focal:?}")?;
1012        }
1013        write!(f, ", focalRadius: {:.1}", self.focal_radius)?;
1014        if let Some(transform) = &self.transform {
1015            write!(f, ", transform: {transform:?}")?;
1016        }
1017        write!(f, ")")
1018    }
1019}
1020
1021/// A 2D sweep gradient.
1022///
1023/// This class is used by `BoxDecoration` to represent sweep gradients. This
1024/// abstracts out the arguments to the dart:ui `Gradient.sweep` constructor.
1025///
1026/// A gradient has a [`center`](Self::center), a [`start_angle`](Self::start_angle), and an
1027/// [`end_angle`](Self::end_angle). The [`start_angle`](Self::start_angle) corresponds to 0.0,
1028/// and the [`end_angle`](Self::end_angle) corresponds to 1.0. These angles are expressed in
1029/// radians.
1030///
1031/// The [`colors`](Self::colors) are described by a list of [`Color`] objects. There must be at
1032/// least two colors. The [`stops`](Self::stops) list, if specified, must have the same length
1033/// as [`colors`](Self::colors). It specifies fractions of the vector from start to end, between
1034/// 0.0 and 1.0, for each color. If it is null, a uniform distribution is
1035/// assumed.
1036///
1037/// The region of the canvas before [`start_angle`](Self::start_angle) and after
1038/// [`end_angle`](Self::end_angle) is colored according to [`tile_mode`](Self::tile_mode).
1039#[derive(Clone, PartialEq)]
1040pub struct SweepGradient {
1041    /// The center of the gradient, as an offset into the (-1.0, -1.0) x (1.0, 1.0)
1042    /// square describing the gradient which will be mapped onto the paint box.
1043    ///
1044    /// For example, an alignment of (0.0, 0.0) will place the sweep
1045    /// gradient in the center of the box.
1046    ///
1047    /// It can also be an `AlignmentDirectional`, where the start is the left in
1048    /// left-to-right contexts and the right in right-to-left contexts. If a
1049    /// text-direction-dependent value is provided here, then the
1050    /// [`create_shader`](Gradient::create_shader) method will need to be given a
1051    /// [`TextDirection`].
1052    pub center: AlignmentGeometry,
1053    /// The angle in radians at which stop 0.0 of the gradient is placed.
1054    ///
1055    /// The angle is measured in radians clockwise from the positive x-axis.
1056    ///
1057    /// Values outside the range `[0, 2Ï€]` are normalized to the equivalent angle
1058    /// within this range using modulo arithmetic.
1059    ///
1060    /// The gradient will be painted in the sector between [`start_angle`](Self::start_angle)
1061    /// and [`end_angle`](Self::end_angle). The behavior outside this sector is determined by
1062    /// [`tile_mode`](Self::tile_mode).
1063    ///
1064    /// Defaults to 0.0.
1065    pub start_angle: f64,
1066    /// The angle in radians at which stop 1.0 of the gradient is placed.
1067    ///
1068    /// The angle is measured in radians clockwise from the positive x-axis.
1069    ///
1070    /// Values outside the range `[0, 2Ï€]` are normalized to the equivalent angle
1071    /// within this range using modulo arithmetic.
1072    ///
1073    /// Defaults to `PI * 2` (2Ï€ = a full circle).
1074    pub end_angle: f64,
1075    /// The colors the gradient should obtain at each of the stops.
1076    pub colors: Vec<Color>,
1077    /// A list of values from 0.0 to 1.0 that denote fractions along the gradient.
1078    pub stops: Option<Vec<f64>>,
1079    /// How this gradient should tile the plane in the region before
1080    /// [`start_angle`](Self::start_angle) and after [`end_angle`](Self::end_angle).
1081    ///
1082    /// * [`TileMode::Clamp`]: The edge colors are extended to fill the remaining area.
1083    /// * [`TileMode::Repeat`]: The gradient is repeated in the angular direction.
1084    /// * [`TileMode::Mirror`]: The gradient is mirrored in the angular direction.
1085    /// * [`TileMode::Decal`]: Only the gradient is drawn, leaving the remaining area
1086    ///   transparent.
1087    pub tile_mode: TileMode,
1088    /// The transform, if any, to apply to the gradient.
1089    pub transform: Option<GradientTransformRef>,
1090}
1091
1092impl SweepGradient {
1093    /// Creates a sweep gradient.
1094    ///
1095    /// If [`stops`](Self::stops) is non-null, it must have the same length as
1096    /// [`colors`](Self::colors).
1097    pub fn new(colors: Vec<Color>) -> SweepGradient {
1098        SweepGradient {
1099            center: AlignmentGeometry::CENTER,
1100            start_angle: 0.0,
1101            end_angle: PI * 2.0,
1102            colors,
1103            stops: None,
1104            tile_mode: TileMode::Clamp,
1105            transform: None,
1106        }
1107    }
1108
1109    /// Dart `SweepGradient(center:)`.
1110    pub fn center(mut self, center: impl Into<AlignmentGeometry>) -> SweepGradient {
1111        self.center = center.into();
1112        self
1113    }
1114
1115    /// Dart `SweepGradient(startAngle:)`.
1116    pub fn start_angle(mut self, start_angle: f64) -> SweepGradient {
1117        self.start_angle = start_angle;
1118        self
1119    }
1120
1121    /// Dart `SweepGradient(endAngle:)`.
1122    pub fn end_angle(mut self, end_angle: f64) -> SweepGradient {
1123        self.end_angle = end_angle;
1124        self
1125    }
1126
1127    /// Dart `SweepGradient(stops:)`.
1128    pub fn stops(mut self, stops: Vec<f64>) -> SweepGradient {
1129        self.stops = Some(stops);
1130        self
1131    }
1132
1133    /// Dart `SweepGradient(tileMode:)`.
1134    pub fn tile_mode(mut self, tile_mode: TileMode) -> SweepGradient {
1135        self.tile_mode = tile_mode;
1136        self
1137    }
1138
1139    /// Dart `SweepGradient(transform:)`.
1140    pub fn transform(mut self, transform: impl Into<GradientTransformRef>) -> SweepGradient {
1141        self.transform = Some(transform.into());
1142        self
1143    }
1144
1145    /// Returns a new [`SweepGradient`] with its colors scaled by the given factor.
1146    ///
1147    /// Since the alpha component of the Color is what is scaled, a factor
1148    /// of 0.0 or less results in a gradient that is fully transparent.
1149    pub fn scale(&self, factor: f64) -> SweepGradient {
1150        SweepGradient {
1151            colors: self
1152                .colors
1153                .iter()
1154                .map(|&color| Color::lerp(None, Some(color), factor).unwrap())
1155                .collect(),
1156            ..self.clone()
1157        }
1158    }
1159
1160    /// Dart's `SweepGradient.fromColor`: the geometry kept, every color replaced by `color`.
1161    pub fn from_color(&self, color: Color) -> SweepGradient {
1162        SweepGradient {
1163            colors: vec![color; self.colors.len()],
1164            ..self.clone()
1165        }
1166    }
1167
1168    /// Linearly interpolate between two [`SweepGradient`]s.
1169    ///
1170    /// If either gradient is None, then the non-null gradient is returned with
1171    /// its color scaled in the same way as the [`scale`](Self::scale) function.
1172    ///
1173    /// If neither gradient is None, they must have the same number of [`colors`](Self::colors).
1174    pub fn lerp(
1175        a: Option<&SweepGradient>,
1176        b: Option<&SweepGradient>,
1177        t: f64,
1178    ) -> Option<SweepGradient> {
1179        let (a, b) = match (a, b) {
1180            (None, None) => return None,
1181            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
1182            (None, Some(b)) => return Some(b.scale(t)),
1183            (Some(a), None) => return Some(a.scale(1.0 - t)),
1184            (Some(a), Some(b)) => (a, b),
1185        };
1186        let interpolated = interpolate_colors_and_stops(
1187            &a.colors,
1188            &<dyn Gradient>::implied_stops(a),
1189            &b.colors,
1190            &<dyn Gradient>::implied_stops(b),
1191            t,
1192        );
1193        Some(SweepGradient {
1194            center: AlignmentGeometry::lerp(Some(a.center), Some(b.center), t).unwrap(),
1195            start_angle: lerp_double(Some(a.start_angle), Some(b.start_angle), t)
1196                .unwrap()
1197                .max(0.0),
1198            end_angle: lerp_double(Some(a.end_angle), Some(b.end_angle), t)
1199                .unwrap()
1200                .max(0.0),
1201            colors: interpolated.colors,
1202            stops: Some(interpolated.stops),
1203            // TODO(ianh): interpolate tile mode
1204            tile_mode: if t < 0.5 { a.tile_mode } else { b.tile_mode },
1205            transform: if t < 0.5 {
1206                a.transform.clone()
1207            } else {
1208                b.transform.clone()
1209            },
1210        })
1211    }
1212
1213    /// Returns a new [`SweepGradient`] with each color set to the given opacity.
1214    #[allow(deprecated)]
1215    pub fn with_opacity(&self, opacity: f64) -> SweepGradient {
1216        SweepGradient {
1217            colors: self
1218                .colors
1219                .iter()
1220                .map(|color| color.with_opacity(opacity))
1221                .collect(),
1222            ..self.clone()
1223        }
1224    }
1225}
1226
1227impl Gradient for SweepGradient {
1228    fn colors(&self) -> &[Color] {
1229        &self.colors
1230    }
1231
1232    fn stops(&self) -> Option<&[f64]> {
1233        self.stops.as_deref()
1234    }
1235
1236    fn transform(&self) -> Option<&GradientTransformRef> {
1237        self.transform.as_ref()
1238    }
1239
1240    fn create_shader(&self, rect: Rect, text_direction: Option<TextDirection>) -> Shader {
1241        gradient_sweep(
1242            self.center.resolve(text_direction).within_rect(rect),
1243            &self.colors,
1244            Some(&<dyn Gradient>::implied_stops(self)),
1245            self.tile_mode,
1246            self.start_angle,
1247            self.end_angle,
1248            <dyn Gradient>::resolve_transform(self, rect, text_direction),
1249        )
1250    }
1251
1252    fn scale(&self, factor: f64) -> GradientRef {
1253        GradientRef::new(SweepGradient::scale(self, factor))
1254    }
1255
1256    fn with_opacity(&self, opacity: f64) -> GradientRef {
1257        GradientRef::new(SweepGradient::with_opacity(self, opacity))
1258    }
1259
1260    fn from_color(&self, color: Color) -> GradientRef {
1261        GradientRef::new(SweepGradient::from_color(self, color))
1262    }
1263
1264    fn lerp_from(&self, a: Option<&dyn Gradient>, t: f64) -> Option<GradientRef> {
1265        match a {
1266            None => boxed(SweepGradient::lerp(None, Some(self), t)),
1267            Some(a) => {
1268                let a = a.as_any().downcast_ref::<SweepGradient>()?;
1269                boxed(SweepGradient::lerp(Some(a), Some(self), t))
1270            }
1271        }
1272    }
1273
1274    fn lerp_to(&self, b: Option<&dyn Gradient>, t: f64) -> Option<GradientRef> {
1275        match b {
1276            None => boxed(SweepGradient::lerp(Some(self), None, t)),
1277            Some(b) => {
1278                let b = b.as_any().downcast_ref::<SweepGradient>()?;
1279                boxed(SweepGradient::lerp(Some(self), Some(b), t))
1280            }
1281        }
1282    }
1283
1284    fn as_any(&self) -> &dyn Any {
1285        self
1286    }
1287
1288    fn eq_gradient(&self, other: &dyn Gradient) -> bool {
1289        other
1290            .as_any()
1291            .downcast_ref::<SweepGradient>()
1292            .is_some_and(|other| other == self)
1293    }
1294}
1295
1296impl Debug for SweepGradient {
1297    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1298        write!(
1299            f,
1300            "SweepGradient(center: {:?}, startAngle: {:.1}, endAngle: {:.1}, colors: {:?}",
1301            self.center, self.start_angle, self.end_angle, self.colors
1302        )?;
1303        if let Some(stops) = &self.stops {
1304            write!(f, ", stops: {stops:?}")?;
1305        }
1306        write!(f, ", tileMode: {}", tile_mode_name(self.tile_mode))?;
1307        if let Some(transform) = &self.transform {
1308            write!(f, ", transform: {transform:?}")?;
1309        }
1310        write!(f, ")")
1311    }
1312}
1313
1314// The dart:ui `Gradient` constructors the three `create_shader`s call, building Valo's shader.
1315
1316fn offset_is_valid(offset: Offset) -> bool {
1317    debug_assert!(
1318        !offset.dx().is_nan() && !offset.dy().is_nan(),
1319        "Offset argument contained a NaN value."
1320    );
1321    true
1322}
1323
1324/// dart:ui `Gradient._validateColorStops`, which throws an `ArgumentError` in release too.
1325fn validate_color_stops(colors: &[Color], color_stops: Option<&[f64]>) {
1326    match color_stops {
1327        None => assert!(
1328            colors.len() == 2,
1329            "\"colors\" must have length 2 if \"colorStops\" is omitted."
1330        ),
1331        Some(color_stops) => assert!(
1332            colors.len() == color_stops.len(),
1333            "\"colors\" and \"colorStops\" arguments must have equal length."
1334        ),
1335    }
1336}
1337
1338/// The engine's color and stop buffers as Valo's stops: without `color_stops`, the colors
1339/// are spread evenly.
1340fn encode_stops(colors: &[Color], color_stops: Option<&[f64]>) -> Vec<GradientStop> {
1341    colors
1342        .iter()
1343        .enumerate()
1344        .map(|(index, &color)| GradientStop {
1345            offset: match color_stops {
1346                Some(color_stops) => color_stops[index] as f32,
1347                None => index as f32 / (colors.len() - 1) as f32,
1348            },
1349            color: color.into(),
1350        })
1351        .collect()
1352}
1353
1354/// dart:ui `TileMode` as Valo's spread.
1355fn spread_mode(tile_mode: TileMode) -> SpreadMode {
1356    match tile_mode {
1357        TileMode::Clamp => SpreadMode::Pad,
1358        TileMode::Repeat => SpreadMode::Repeat,
1359        TileMode::Mirror => SpreadMode::Reflect,
1360        TileMode::Decal => SpreadMode::Decal,
1361    }
1362}
1363
1364/// dart:ui `Gradient.linear`.
1365fn gradient_linear(
1366    from: Offset,
1367    to: Offset,
1368    colors: &[Color],
1369    color_stops: Option<&[f64]>,
1370    tile_mode: TileMode,
1371    matrix4: Option<Matrix4>,
1372) -> Shader {
1373    debug_assert!(offset_is_valid(from));
1374    debug_assert!(offset_is_valid(to));
1375    validate_color_stops(colors, color_stops);
1376    Shader::Linear {
1377        start: from.into(),
1378        end: to.into(),
1379        stops: encode_stops(colors, color_stops),
1380        spread: spread_mode(tile_mode),
1381        local: matrix4.unwrap_or(Matrix4::IDENTITY),
1382    }
1383}
1384
1385/// dart:ui `Gradient.radial`.
1386#[allow(clippy::too_many_arguments)]
1387fn gradient_radial(
1388    center: Offset,
1389    radius: f64,
1390    colors: &[Color],
1391    color_stops: Option<&[f64]>,
1392    tile_mode: TileMode,
1393    matrix4: Option<Matrix4>,
1394    focal: Option<Offset>,
1395    focal_radius: f64,
1396) -> Shader {
1397    debug_assert!(offset_is_valid(center));
1398    validate_color_stops(colors, color_stops);
1399    // If focal is null or focal radius is null, this should be treated as a regular radial gradient
1400    // If focal == center and the focal radius is 0.0, it's still a regular radial gradient
1401    let focus = match focal {
1402        Some(focal) if !(focal == center && focal_radius == 0.0) => {
1403            // will result in exception(s) in Skia side
1404            debug_assert!(center != Offset::ZERO || focal != Offset::ZERO);
1405            Some(FocalCircle {
1406                center: focal.into(),
1407                radius: focal_radius as f32,
1408            })
1409        }
1410        _ => None,
1411    };
1412    Shader::Radial {
1413        center: center.into(),
1414        radius: radius as f32,
1415        stops: encode_stops(colors, color_stops),
1416        spread: spread_mode(tile_mode),
1417        focus,
1418        local: matrix4.unwrap_or(Matrix4::IDENTITY),
1419    }
1420}
1421
1422/// dart:ui `Gradient.sweep`.
1423fn gradient_sweep(
1424    center: Offset,
1425    colors: &[Color],
1426    color_stops: Option<&[f64]>,
1427    tile_mode: TileMode,
1428    start_angle: f64,
1429    end_angle: f64,
1430    matrix4: Option<Matrix4>,
1431) -> Shader {
1432    debug_assert!(offset_is_valid(center));
1433    debug_assert!(start_angle < end_angle);
1434    validate_color_stops(colors, color_stops);
1435    Shader::Sweep {
1436        center: center.into(),
1437        start_angle: start_angle as f32,
1438        end_angle: end_angle as f32,
1439        stops: encode_stops(colors, color_stops),
1440        spread: spread_mode(tile_mode),
1441        local: matrix4.unwrap_or(Matrix4::IDENTITY),
1442    }
1443}
1444
1445#[cfg(test)]
1446mod tests {
1447    use std::panic::{AssertUnwindSafe, catch_unwind};
1448
1449    use waft_embedder::valo::Point;
1450
1451    use super::*;
1452
1453    fn list_double_matches(x: Option<&[f64]>, y: Option<&[f64]>) -> bool {
1454        match (x, y) {
1455            (None, None) => true,
1456            (Some(x), Some(y)) => {
1457                x.len() == y.len() && x.iter().zip(y).all(|(x, y)| (x - y).abs() < 0.0001)
1458            }
1459            _ => false,
1460        }
1461    }
1462
1463    fn list_color_matches(x: &[Color], y: &[Color]) -> bool {
1464        const LIMIT: f64 = 1.0 / 255.0;
1465        x.len() == y.len()
1466            && x.iter().zip(y).all(|(x, y)| {
1467                (x.a - y.a).abs() < LIMIT
1468                    && (x.r - y.r).abs() < LIMIT
1469                    && (x.g - y.g).abs() < LIMIT
1470                    && (x.b - y.b).abs() < LIMIT
1471            })
1472    }
1473
1474    /// Dart's `_matchesLinearGradient`.
1475    fn assert_matches_linear(item: &dyn Gradient, target: &LinearGradient) {
1476        let matches = item
1477            .as_any()
1478            .downcast_ref::<LinearGradient>()
1479            .is_some_and(|item| {
1480                item.begin == target.begin
1481                    && item.end == target.end
1482                    && item.tile_mode == target.tile_mode
1483                    && item.transform == target.transform
1484                    && list_color_matches(&item.colors, &target.colors)
1485                    && list_double_matches(item.stops.as_deref(), target.stops.as_deref())
1486            });
1487        assert!(matches, "expected {target:?}, got {item:?}");
1488    }
1489
1490    /// Dart's `_matchesRadialGradient`.
1491    fn assert_matches_radial(item: &dyn Gradient, target: &RadialGradient) {
1492        let matches = item
1493            .as_any()
1494            .downcast_ref::<RadialGradient>()
1495            .is_some_and(|item| {
1496                item.center == target.center
1497                    && item.radius == target.radius
1498                    && item.tile_mode == target.tile_mode
1499                    && item.transform == target.transform
1500                    && item.focal == target.focal
1501                    && item.focal_radius == target.focal_radius
1502                    && list_color_matches(&item.colors, &target.colors)
1503                    && list_double_matches(item.stops.as_deref(), target.stops.as_deref())
1504            });
1505        assert!(matches, "expected {target:?}, got {item:?}");
1506    }
1507
1508    /// Dart's `_matchesSweepGradient`.
1509    fn assert_matches_sweep(item: &dyn Gradient, target: &SweepGradient) {
1510        let matches = item
1511            .as_any()
1512            .downcast_ref::<SweepGradient>()
1513            .is_some_and(|item| {
1514                item.center == target.center
1515                    && item.start_angle == target.start_angle
1516                    && item.end_angle == target.end_angle
1517                    && item.tile_mode == target.tile_mode
1518                    && item.transform == target.transform
1519                    && list_color_matches(&item.colors, &target.colors)
1520                    && list_double_matches(item.stops.as_deref(), target.stops.as_deref())
1521            });
1522        assert!(matches, "expected {target:?}, got {item:?}");
1523    }
1524
1525    fn colors(values: &[u32]) -> Vec<Color> {
1526        values.iter().map(|&value| Color::new(value)).collect()
1527    }
1528
1529    #[test]
1530    fn a_linear_gradient_lerped_from_null_scales_its_colours() {
1531        let test_gradient = LinearGradient::new(colors(&[0x00FFFFFF, 0x11777777, 0x44444444]))
1532            .begin(AlignmentGeometry::BOTTOM_RIGHT)
1533            .end(AlignmentGeometry::xy(0.7, 1.0));
1534        let actual = LinearGradient::lerp(None, Some(&test_gradient), 0.25).unwrap();
1535        assert_matches_linear(
1536            &actual,
1537            &LinearGradient::new(colors(&[0x00FFFFFF, 0x04777777, 0x11444444]))
1538                .begin(AlignmentGeometry::BOTTOM_RIGHT)
1539                .end(AlignmentGeometry::xy(0.7, 1.0)),
1540        );
1541    }
1542
1543    #[test]
1544    fn linear_gradients_lerp() {
1545        let test_gradient1 = LinearGradient::new(colors(&[0x33333333, 0x66666666]))
1546            .begin(AlignmentGeometry::TOP_LEFT)
1547            .end(AlignmentGeometry::BOTTOM_LEFT);
1548        let test_gradient2 = LinearGradient::new(colors(&[0x44444444, 0x88888888]))
1549            .begin(AlignmentGeometry::TOP_RIGHT)
1550            .end(AlignmentGeometry::TOP_LEFT);
1551        let actual = LinearGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
1552        assert_matches_linear(
1553            &actual.unwrap(),
1554            &LinearGradient::new(colors(&[0x3B3B3B3B, 0x77777777]))
1555                .begin(AlignmentGeometry::TOP_CENTER)
1556                .end(AlignmentGeometry::CENTER_LEFT)
1557                .stops(vec![0.0, 1.0]),
1558        );
1559    }
1560
1561    #[test]
1562    fn linear_gradient_lerp_of_identical_a_and_b_returns_a() {
1563        assert!(LinearGradient::lerp(None, None, 0.0).is_none());
1564        let gradient = LinearGradient::new(colors(&[0x33333333, 0x66666666]));
1565        assert_eq!(
1566            LinearGradient::lerp(Some(&gradient), Some(&gradient), 0.5).unwrap(),
1567            gradient
1568        );
1569    }
1570
1571    #[test]
1572    fn linear_gradients_lerp_with_stops() {
1573        let test_gradient1 = LinearGradient::new(colors(&[0x33333333, 0x66666666]))
1574            .begin(AlignmentGeometry::TOP_LEFT)
1575            .end(AlignmentGeometry::BOTTOM_LEFT)
1576            .stops(vec![0.0, 0.5]);
1577        let test_gradient2 = LinearGradient::new(colors(&[0x44444444, 0x88888888]))
1578            .begin(AlignmentGeometry::TOP_RIGHT)
1579            .end(AlignmentGeometry::TOP_LEFT)
1580            .stops(vec![0.5, 1.0]);
1581        let actual = LinearGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
1582        assert_matches_linear(
1583            &actual.unwrap(),
1584            &LinearGradient::new(colors(&[0x3B3B3B3B, 0x55555555, 0x77777777]))
1585                .begin(AlignmentGeometry::TOP_CENTER)
1586                .end(AlignmentGeometry::CENTER_LEFT)
1587                .stops(vec![0.0, 0.5, 1.0]),
1588        );
1589    }
1590
1591    #[test]
1592    fn linear_gradients_lerp_with_unequal_numbers_of_colours() {
1593        let test_gradient1 = LinearGradient::new(colors(&[0x22222222, 0x66666666]));
1594        let test_gradient2 = LinearGradient::new(colors(&[0x44444444, 0x66666666, 0x88888888]));
1595        let actual = LinearGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
1596        assert_matches_linear(
1597            &actual.unwrap(),
1598            &LinearGradient::new(colors(&[0x33333333, 0x55555555, 0x77777777]))
1599                .stops(vec![0.0, 0.5, 1.0]),
1600        );
1601    }
1602
1603    #[test]
1604    fn linear_gradients_lerp_with_stops_and_unequal_numbers_of_colours() {
1605        let test_gradient1 =
1606            LinearGradient::new(colors(&[0x33333333, 0x66666666])).stops(vec![0.0, 0.5]);
1607        let test_gradient2 = LinearGradient::new(colors(&[0x44444444, 0x48484848, 0x88888888]))
1608            .stops(vec![0.5, 0.7, 1.0]);
1609        let actual = LinearGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
1610        assert_matches_linear(
1611            &actual.unwrap(),
1612            &LinearGradient::new(colors(&[0x3B3B3B3B, 0x55555555, 0x57575757, 0x77777777]))
1613                .stops(vec![0.0, 0.5, 0.7, 1.0]),
1614        );
1615    }
1616
1617    #[test]
1618    fn linear_gradients_lerp_with_transforms() {
1619        let test_gradient1 = LinearGradient::new(colors(&[0x33333333, 0x66666666]))
1620            .transform(GradientRotation::new(PI / 4.0))
1621            .stops(vec![0.0, 1.0]);
1622        let test_gradient2 = LinearGradient::new(colors(&[0x33333333, 0x66666666]))
1623            .transform(GradientRotation::new(PI / 2.0))
1624            .stops(vec![0.0, 1.0]);
1625        let lerp = |t| LinearGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), t);
1626        assert_eq!(Some(test_gradient1.clone()), lerp(0.0));
1627        assert_eq!(Some(test_gradient2.clone()), lerp(1.0));
1628        assert_eq!(Some(test_gradient2.clone()), lerp(0.5));
1629    }
1630
1631    #[test]
1632    fn a_linear_gradient_prints_as_dart_does() {
1633        let red = Color::new(0x33333333);
1634        let green = Color::new(0x66666666);
1635        assert_eq!(
1636            format!(
1637                "{:?}",
1638                LinearGradient::new(vec![red, green])
1639                    .begin(AlignmentGeometry::TOP_LEFT)
1640                    .end(AlignmentGeometry::BOTTOM_LEFT)
1641                    .transform(GradientRotation::new(1.6))
1642            ),
1643            format!(
1644                "LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomLeft, colors: [{red:?}, {green:?}], tileMode: TileMode.clamp, transform: GradientRotation(radians: 1.6))"
1645            )
1646        );
1647    }
1648
1649    #[test]
1650    fn linear_gradients_with_different_transforms_differ() {
1651        let test_gradient1 = LinearGradient::new(colors(&[0x33333333, 0x66666666]))
1652            .transform(GradientRotation::new(PI / 4.0));
1653        let test_gradient1_copy = LinearGradient::new(colors(&[0x33333333, 0x66666666]))
1654            .transform(GradientRotation::new(PI / 4.0));
1655        let test_gradient2 = LinearGradient::new(colors(&[0x33333333, 0x66666666]))
1656            .transform(GradientRotation::new(PI / 2.0));
1657        assert_eq!(test_gradient1, test_gradient1_copy);
1658        assert_ne!(test_gradient1, test_gradient2);
1659    }
1660
1661    const RECT: Rect = Rect::from_ltwh(0.0, 0.0, 100.0, 100.0);
1662
1663    #[test]
1664    #[should_panic(expected = "No TextDirection found.")]
1665    fn a_directional_linear_gradient_needs_a_text_direction() {
1666        LinearGradient::new(colors(&[0xFFFFFFFF, 0xFFFFFFFF]))
1667            .begin(AlignmentGeometry::TOP_START)
1668            .create_shader(RECT, None);
1669    }
1670
1671    #[test]
1672    fn a_linear_gradient_resolves_its_alignments_with_a_text_direction() {
1673        let directional = LinearGradient::new(colors(&[0xFFFFFFFF, 0xFFFFFFFF]))
1674            .begin(AlignmentGeometry::TOP_START);
1675        directional.create_shader(RECT, Some(TextDirection::Rtl));
1676        directional.create_shader(RECT, Some(TextDirection::Ltr));
1677        LinearGradient::new(colors(&[0xFFFFFFFF, 0xFFFFFFFF]))
1678            .begin(AlignmentGeometry::TOP_LEFT)
1679            .create_shader(RECT, None);
1680    }
1681
1682    #[test]
1683    fn a_linear_gradient_with_opacity_sets_every_alpha() {
1684        let test_gradient = LinearGradient::new(colors(&[0xFFFFFFFF, 0xAF777777, 0x44444444]))
1685            .begin(AlignmentGeometry::BOTTOM_RIGHT)
1686            .end(AlignmentGeometry::TOP_CENTER);
1687        assert_eq!(
1688            test_gradient.with_opacity(0.5),
1689            LinearGradient::new(colors(&[0x80FFFFFF, 0x80777777, 0x80444444]))
1690                .begin(AlignmentGeometry::BOTTOM_RIGHT)
1691                .end(AlignmentGeometry::TOP_CENTER)
1692        );
1693    }
1694
1695    #[test]
1696    fn a_linear_gradient_with_opacity_keeps_its_transform() {
1697        let test_gradient = LinearGradient::new(colors(&[0xFFFFFFFF, 0xAF777777, 0x44444444]))
1698            .begin(AlignmentGeometry::BOTTOM_RIGHT)
1699            .end(AlignmentGeometry::TOP_CENTER)
1700            .transform(GradientRotation::new(1.0));
1701        assert_eq!(
1702            test_gradient.with_opacity(0.5),
1703            LinearGradient::new(colors(&[0x80FFFFFF, 0x80777777, 0x80444444]))
1704                .begin(AlignmentGeometry::BOTTOM_RIGHT)
1705                .end(AlignmentGeometry::TOP_CENTER)
1706                .transform(GradientRotation::new(1.0))
1707        );
1708    }
1709
1710    #[test]
1711    fn a_linear_gradient_from_a_colour_replaces_its_colours_and_keeps_its_geometry() {
1712        let test_gradient = LinearGradient::new(colors(&[0xFFFFFFFF, 0xAF777777, 0x44444444]))
1713            .begin(AlignmentGeometry::BOTTOM_RIGHT)
1714            .end(AlignmentGeometry::TOP_CENTER)
1715            .stops(vec![0.0, 0.3, 1.0])
1716            .tile_mode(TileMode::Mirror)
1717            .transform(GradientRotation::new(1.0));
1718        assert_eq!(
1719            test_gradient.from_color(Color::new(0xFF00FF00)),
1720            LinearGradient::new(colors(&[0xFF00FF00, 0xFF00FF00, 0xFF00FF00]))
1721                .begin(AlignmentGeometry::BOTTOM_RIGHT)
1722                .end(AlignmentGeometry::TOP_CENTER)
1723                .stops(vec![0.0, 0.3, 1.0])
1724                .tile_mode(TileMode::Mirror)
1725                .transform(GradientRotation::new(1.0))
1726        );
1727    }
1728
1729    #[test]
1730    fn a_radial_gradient_from_a_colour_replaces_its_colours_and_keeps_its_geometry() {
1731        let test_gradient = RadialGradient::new(colors(&[0xFFFFFFFF, 0x44444444]))
1732            .center(AlignmentGeometry::TOP_LEFT)
1733            .radius(0.25)
1734            .focal(AlignmentGeometry::CENTER_RIGHT)
1735            .focal_radius(0.1)
1736            .tile_mode(TileMode::Mirror)
1737            .transform(GradientRotation::new(1.0));
1738        assert_eq!(
1739            test_gradient.from_color(Color::new(0xFF00FF00)),
1740            RadialGradient::new(colors(&[0xFF00FF00, 0xFF00FF00]))
1741                .center(AlignmentGeometry::TOP_LEFT)
1742                .radius(0.25)
1743                .focal(AlignmentGeometry::CENTER_RIGHT)
1744                .focal_radius(0.1)
1745                .tile_mode(TileMode::Mirror)
1746                .transform(GradientRotation::new(1.0))
1747        );
1748    }
1749
1750    #[test]
1751    fn a_sweep_gradient_from_a_colour_replaces_its_colours_and_keeps_its_geometry() {
1752        let test_gradient = SweepGradient::new(colors(&[0xFFFFFFFF, 0x44444444]))
1753            .center(AlignmentGeometry::TOP_LEFT)
1754            .start_angle(0.1)
1755            .end_angle(2.0)
1756            .tile_mode(TileMode::Repeat)
1757            .transform(GradientRotation::new(1.0));
1758        assert_eq!(
1759            test_gradient.from_color(Color::new(0xFF00FF00)),
1760            SweepGradient::new(colors(&[0xFF00FF00, 0xFF00FF00]))
1761                .center(AlignmentGeometry::TOP_LEFT)
1762                .start_angle(0.1)
1763                .end_angle(2.0)
1764                .tile_mode(TileMode::Repeat)
1765                .transform(GradientRotation::new(1.0))
1766        );
1767    }
1768
1769    #[test]
1770    fn a_scaled_linear_gradient_keeps_its_transform() {
1771        let test_gradient = LinearGradient::new(colors(&[0xFFFF0000, 0xFF00FF00, 0xFF0000FF]))
1772            .begin(AlignmentGeometry::BOTTOM_RIGHT)
1773            .end(AlignmentGeometry::TOP_LEFT)
1774            .stops(vec![0.0, 0.5, 1.0])
1775            .tile_mode(TileMode::Decal)
1776            .transform(GradientRotation::new(PI / 4.0));
1777        assert_matches_linear(
1778            &test_gradient.scale(0.5),
1779            &LinearGradient::new(colors(&[0x80FF0000, 0x8000FF00, 0x800000FF]))
1780                .begin(AlignmentGeometry::BOTTOM_RIGHT)
1781                .end(AlignmentGeometry::TOP_LEFT)
1782                .stops(vec![0.0, 0.5, 1.0])
1783                .tile_mode(TileMode::Decal)
1784                .transform(GradientRotation::new(PI / 4.0)),
1785        );
1786    }
1787
1788    #[test]
1789    #[should_panic(expected = "No TextDirection found.")]
1790    fn a_directional_radial_gradient_needs_a_text_direction() {
1791        RadialGradient::new(colors(&[0xFFFFFFFF, 0xFFFFFFFF]))
1792            .center(AlignmentGeometry::TOP_START)
1793            .create_shader(RECT, None);
1794    }
1795
1796    #[test]
1797    fn a_radial_gradient_resolves_its_alignments_with_a_text_direction() {
1798        let directional = RadialGradient::new(colors(&[0xFFFFFFFF, 0xFFFFFFFF]))
1799            .center(AlignmentGeometry::TOP_START);
1800        directional.create_shader(RECT, Some(TextDirection::Rtl));
1801        directional.create_shader(RECT, Some(TextDirection::Ltr));
1802        RadialGradient::new(colors(&[0xFFFFFFFF, 0xFFFFFFFF]))
1803            .center(AlignmentGeometry::TOP_LEFT)
1804            .create_shader(RECT, None);
1805    }
1806
1807    #[test]
1808    fn radial_gradients_lerp() {
1809        let test_gradient1 = RadialGradient::new(colors(&[0x33333333, 0x66666666]))
1810            .center(AlignmentGeometry::TOP_LEFT)
1811            .radius(20.0);
1812        let test_gradient2 = RadialGradient::new(colors(&[0x44444444, 0x88888888]))
1813            .center(AlignmentGeometry::TOP_RIGHT)
1814            .radius(10.0);
1815        let actual = RadialGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
1816        assert_matches_radial(
1817            &actual.unwrap(),
1818            &RadialGradient::new(colors(&[0x3B3B3B3B, 0x77777777]))
1819                .center(AlignmentGeometry::TOP_CENTER)
1820                .radius(15.0)
1821                .stops(vec![0.0, 1.0]),
1822        );
1823    }
1824
1825    #[test]
1826    fn radial_gradient_lerp_of_identical_a_and_b_returns_a() {
1827        assert!(RadialGradient::lerp(None, None, 0.0).is_none());
1828        let gradient = RadialGradient::new(colors(&[0x33333333, 0x66666666]));
1829        assert_eq!(
1830            RadialGradient::lerp(Some(&gradient), Some(&gradient), 0.5).unwrap(),
1831            gradient
1832        );
1833    }
1834
1835    #[test]
1836    fn radial_gradients_lerp_with_stops() {
1837        let test_gradient1 = RadialGradient::new(colors(&[0x33333333, 0x66666666]))
1838            .center(AlignmentGeometry::TOP_LEFT)
1839            .radius(20.0)
1840            .stops(vec![0.0, 0.5]);
1841        let test_gradient2 = RadialGradient::new(colors(&[0x44444444, 0x88888888]))
1842            .center(AlignmentGeometry::TOP_RIGHT)
1843            .radius(10.0)
1844            .stops(vec![0.5, 1.0]);
1845        let actual =
1846            RadialGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5).unwrap();
1847        assert_matches_radial(
1848            &actual,
1849            &RadialGradient::new(colors(&[0x3B3B3B3B, 0x55555555, 0x77777777]))
1850                .center(AlignmentGeometry::TOP_CENTER)
1851                .radius(15.0)
1852                .stops(vec![0.0, 0.5, 1.0]),
1853        );
1854        assert!(actual.focal.is_none());
1855    }
1856
1857    #[test]
1858    fn radial_gradients_lerp_with_unequal_numbers_of_colours() {
1859        let test_gradient1 = RadialGradient::new(colors(&[0x22222222, 0x66666666]));
1860        let test_gradient2 = RadialGradient::new(colors(&[0x44444444, 0x66666666, 0x88888888]));
1861        let actual = RadialGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
1862        assert_matches_radial(
1863            &actual.unwrap(),
1864            &RadialGradient::new(colors(&[0x33333333, 0x55555555, 0x77777777]))
1865                .stops(vec![0.0, 0.5, 1.0]),
1866        );
1867    }
1868
1869    #[test]
1870    fn radial_gradients_lerp_with_stops_and_unequal_numbers_of_colours() {
1871        let test_gradient1 =
1872            RadialGradient::new(colors(&[0x33333333, 0x66666666])).stops(vec![0.0, 0.5]);
1873        let test_gradient2 = RadialGradient::new(colors(&[0x44444444, 0x48484848, 0x88888888]))
1874            .stops(vec![0.5, 0.7, 1.0]);
1875        let actual = RadialGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
1876        assert_matches_radial(
1877            &actual.unwrap(),
1878            &RadialGradient::new(colors(&[0x3B3B3B3B, 0x55555555, 0x57575757, 0x77777777]))
1879                .stops(vec![0.0, 0.5, 0.7, 1.0]),
1880        );
1881    }
1882
1883    #[test]
1884    fn radial_gradients_lerp_with_transforms() {
1885        let test_gradient1 = RadialGradient::new(colors(&[0x33333333, 0x66666666]))
1886            .transform(GradientRotation::new(PI / 4.0))
1887            .stops(vec![0.0, 1.0]);
1888        let test_gradient2 = RadialGradient::new(colors(&[0x33333333, 0x66666666]))
1889            .transform(GradientRotation::new(PI / 2.0))
1890            .stops(vec![0.0, 1.0]);
1891        let lerp = |t| RadialGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), t);
1892        assert_eq!(Some(test_gradient1.clone()), lerp(0.0));
1893        assert_eq!(Some(test_gradient2.clone()), lerp(1.0));
1894        assert_eq!(Some(test_gradient2.clone()), lerp(0.5));
1895    }
1896
1897    #[test]
1898    fn radial_gradients_lerp_with_focal() {
1899        let test_gradient1 = RadialGradient::new(colors(&[0x33333333, 0x66666666]))
1900            .center(AlignmentGeometry::TOP_LEFT)
1901            .focal(AlignmentGeometry::CENTER_LEFT)
1902            .radius(20.0)
1903            .focal_radius(10.0);
1904        let test_gradient2 = RadialGradient::new(colors(&[0x44444444, 0x88888888]))
1905            .center(AlignmentGeometry::TOP_RIGHT)
1906            .focal(AlignmentGeometry::CENTER_RIGHT)
1907            .radius(10.0)
1908            .focal_radius(5.0);
1909        let test_gradient3 = RadialGradient::new(colors(&[0x44444444, 0x88888888]))
1910            .center(AlignmentGeometry::TOP_RIGHT)
1911            .radius(10.0);
1912
1913        let actual = RadialGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
1914        assert_matches_radial(
1915            &actual.unwrap(),
1916            &RadialGradient::new(colors(&[0x3B3B3B3B, 0x77777777]))
1917                .center(AlignmentGeometry::TOP_CENTER)
1918                .focal(AlignmentGeometry::CENTER)
1919                .radius(15.0)
1920                .focal_radius(7.5)
1921                .stops(vec![0.0, 1.0]),
1922        );
1923
1924        let actual2 = RadialGradient::lerp(Some(&test_gradient1), Some(&test_gradient3), 0.5);
1925        assert_matches_radial(
1926            &actual2.unwrap(),
1927            &RadialGradient::new(colors(&[0x3B3B3B3B, 0x77777777]))
1928                .center(AlignmentGeometry::TOP_CENTER)
1929                .focal(AlignmentGeometry::xy(-0.5, 0.0))
1930                .radius(15.0)
1931                .focal_radius(5.0)
1932                .stops(vec![0.0, 1.0]),
1933        );
1934    }
1935
1936    #[test]
1937    fn a_radial_gradient_with_opacity_sets_every_alpha() {
1938        let test_gradient = RadialGradient::new(colors(&[0xFFFFFFFF, 0xAF777777, 0x44444444]))
1939            .center(AlignmentGeometry::TOP_LEFT)
1940            .focal(AlignmentGeometry::CENTER_LEFT)
1941            .radius(20.0)
1942            .focal_radius(10.0);
1943        assert_eq!(
1944            test_gradient.with_opacity(0.5),
1945            RadialGradient::new(colors(&[0x80FFFFFF, 0x80777777, 0x80444444]))
1946                .center(AlignmentGeometry::TOP_LEFT)
1947                .focal(AlignmentGeometry::CENTER_LEFT)
1948                .radius(20.0)
1949                .focal_radius(10.0)
1950        );
1951    }
1952
1953    #[test]
1954    fn a_radial_gradient_with_opacity_keeps_its_transform() {
1955        let test_gradient = RadialGradient::new(colors(&[0xFFFFFFFF, 0xAF777777, 0x44444444]))
1956            .center(AlignmentGeometry::TOP_LEFT)
1957            .focal(AlignmentGeometry::CENTER_LEFT)
1958            .radius(20.0)
1959            .focal_radius(10.0)
1960            .transform(GradientRotation::new(1.0));
1961        assert_eq!(
1962            test_gradient.with_opacity(0.5),
1963            RadialGradient::new(colors(&[0x80FFFFFF, 0x80777777, 0x80444444]))
1964                .center(AlignmentGeometry::TOP_LEFT)
1965                .focal(AlignmentGeometry::CENTER_LEFT)
1966                .radius(20.0)
1967                .focal_radius(10.0)
1968                .transform(GradientRotation::new(1.0))
1969        );
1970    }
1971
1972    #[test]
1973    fn a_scaled_radial_gradient_keeps_its_transform() {
1974        let test_gradient = RadialGradient::new(colors(&[0xFFFF0000, 0xFF00FF00, 0xFF0000FF]))
1975            .center(AlignmentGeometry::TOP_LEFT)
1976            .focal(AlignmentGeometry::CENTER_LEFT)
1977            .radius(20.0)
1978            .focal_radius(10.0)
1979            .stops(vec![0.0, 0.5, 1.0])
1980            .tile_mode(TileMode::Decal)
1981            .transform(GradientRotation::new(PI / 4.0));
1982        assert_matches_radial(
1983            &test_gradient.scale(0.5),
1984            &RadialGradient::new(colors(&[0x80FF0000, 0x8000FF00, 0x800000FF]))
1985                .center(AlignmentGeometry::TOP_LEFT)
1986                .focal(AlignmentGeometry::CENTER_LEFT)
1987                .radius(20.0)
1988                .focal_radius(10.0)
1989                .stops(vec![0.0, 0.5, 1.0])
1990                .tile_mode(TileMode::Decal)
1991                .transform(GradientRotation::new(PI / 4.0)),
1992        );
1993    }
1994
1995    #[test]
1996    fn sweep_gradients_lerp() {
1997        let test_gradient1 = SweepGradient::new(colors(&[0x33333333, 0x66666666]))
1998            .center(AlignmentGeometry::TOP_LEFT)
1999            .end_angle(PI / 2.0);
2000        let test_gradient2 = SweepGradient::new(colors(&[0x44444444, 0x88888888]))
2001            .center(AlignmentGeometry::TOP_RIGHT)
2002            .start_angle(PI / 2.0)
2003            .end_angle(PI);
2004        let actual = SweepGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
2005        assert_matches_sweep(
2006            &actual.unwrap(),
2007            &SweepGradient::new(colors(&[0x3B3B3B3B, 0x77777777]))
2008                .center(AlignmentGeometry::TOP_CENTER)
2009                .start_angle(PI / 4.0)
2010                .end_angle(PI * 3.0 / 4.0)
2011                .stops(vec![0.0, 1.0]),
2012        );
2013    }
2014
2015    #[test]
2016    fn sweep_gradient_lerp_of_identical_a_and_b_returns_a() {
2017        assert!(SweepGradient::lerp(None, None, 0.0).is_none());
2018        let gradient = SweepGradient::new(colors(&[0x33333333, 0x66666666]));
2019        assert_eq!(
2020            SweepGradient::lerp(Some(&gradient), Some(&gradient), 0.5).unwrap(),
2021            gradient
2022        );
2023    }
2024
2025    #[test]
2026    fn sweep_gradients_lerp_with_stops() {
2027        let test_gradient1 = SweepGradient::new(colors(&[0x33333333, 0x66666666]))
2028            .center(AlignmentGeometry::TOP_LEFT)
2029            .end_angle(PI / 2.0)
2030            .stops(vec![0.0, 0.5]);
2031        let test_gradient2 = SweepGradient::new(colors(&[0x44444444, 0x88888888]))
2032            .center(AlignmentGeometry::TOP_RIGHT)
2033            .start_angle(PI / 2.0)
2034            .end_angle(PI)
2035            .stops(vec![0.5, 1.0]);
2036        let actual = SweepGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
2037        assert_matches_sweep(
2038            &actual.unwrap(),
2039            &SweepGradient::new(colors(&[0x3B3B3B3B, 0x55555555, 0x77777777]))
2040                .center(AlignmentGeometry::TOP_CENTER)
2041                .start_angle(PI / 4.0)
2042                .end_angle(PI * 3.0 / 4.0)
2043                .stops(vec![0.0, 0.5, 1.0]),
2044        );
2045    }
2046
2047    #[test]
2048    fn sweep_gradients_lerp_with_unequal_numbers_of_colours() {
2049        let test_gradient1 = SweepGradient::new(colors(&[0x22222222, 0x66666666]));
2050        let test_gradient2 = SweepGradient::new(colors(&[0x44444444, 0x66666666, 0x88888888]));
2051        let actual = SweepGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
2052        assert_matches_sweep(
2053            &actual.unwrap(),
2054            &SweepGradient::new(colors(&[0x33333333, 0x55555555, 0x77777777]))
2055                .stops(vec![0.0, 0.5, 1.0]),
2056        );
2057    }
2058
2059    #[test]
2060    fn sweep_gradients_lerp_with_stops_and_unequal_numbers_of_colours() {
2061        let test_gradient1 =
2062            SweepGradient::new(colors(&[0x33333333, 0x66666666])).stops(vec![0.0, 0.5]);
2063        let test_gradient2 = SweepGradient::new(colors(&[0x44444444, 0x48484848, 0x88888888]))
2064            .stops(vec![0.5, 0.7, 1.0]);
2065        let actual = SweepGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), 0.5);
2066        assert_matches_sweep(
2067            &actual.unwrap(),
2068            &SweepGradient::new(colors(&[0x3B3B3B3B, 0x55555555, 0x57575757, 0x77777777]))
2069                .stops(vec![0.0, 0.5, 0.7, 1.0]),
2070        );
2071    }
2072
2073    #[test]
2074    fn sweep_gradients_lerp_with_transforms() {
2075        let test_gradient1 = SweepGradient::new(colors(&[0x33333333, 0x66666666]))
2076            .transform(GradientRotation::new(PI / 4.0))
2077            .stops(vec![0.0, 1.0]);
2078        let test_gradient2 = SweepGradient::new(colors(&[0x33333333, 0x66666666]))
2079            .transform(GradientRotation::new(PI / 2.0))
2080            .stops(vec![0.0, 1.0]);
2081        let lerp = |t| SweepGradient::lerp(Some(&test_gradient1), Some(&test_gradient2), t);
2082        assert_eq!(Some(test_gradient1.clone()), lerp(0.0));
2083        assert_eq!(Some(test_gradient2.clone()), lerp(1.0));
2084        assert_eq!(Some(test_gradient2.clone()), lerp(0.5));
2085    }
2086
2087    #[test]
2088    fn a_scaled_sweep_gradient_scales_its_colours() {
2089        let test_gradient = SweepGradient::new(colors(&[0xff333333, 0xff666666]))
2090            .center(AlignmentGeometry::TOP_LEFT)
2091            .end_angle(PI / 2.0);
2092        assert_matches_sweep(
2093            &test_gradient.scale(0.5),
2094            &SweepGradient::new(colors(&[0x80333333, 0x80666666]))
2095                .center(AlignmentGeometry::TOP_LEFT)
2096                .end_angle(PI / 2.0),
2097        );
2098    }
2099
2100    #[test]
2101    fn a_sweep_gradient_with_opacity_sets_every_alpha() {
2102        let test_gradient = SweepGradient::new(colors(&[0xFFFFFFFF, 0xAF777777, 0x44444444]))
2103            .center(AlignmentGeometry::TOP_LEFT)
2104            .end_angle(PI / 2.0);
2105        assert_eq!(
2106            test_gradient.with_opacity(0.5),
2107            SweepGradient::new(colors(&[0x80FFFFFF, 0x80777777, 0x80444444]))
2108                .center(AlignmentGeometry::TOP_LEFT)
2109                .end_angle(PI / 2.0)
2110        );
2111    }
2112
2113    #[test]
2114    fn a_sweep_gradient_with_opacity_keeps_its_transform() {
2115        let test_gradient = SweepGradient::new(colors(&[0xFFFFFFFF, 0xAF777777, 0x44444444]))
2116            .center(AlignmentGeometry::TOP_LEFT)
2117            .end_angle(PI / 2.0)
2118            .transform(GradientRotation::new(1.0));
2119        assert_eq!(
2120            test_gradient.with_opacity(0.5),
2121            SweepGradient::new(colors(&[0x80FFFFFF, 0x80777777, 0x80444444]))
2122                .center(AlignmentGeometry::TOP_LEFT)
2123                .end_angle(PI / 2.0)
2124                .transform(GradientRotation::new(1.0))
2125        );
2126    }
2127
2128    #[test]
2129    fn a_scaled_sweep_gradient_keeps_its_transform() {
2130        let test_gradient = SweepGradient::new(colors(&[0xFFFF0000, 0xFF00FF00, 0xFF0000FF]))
2131            .center(AlignmentGeometry::TOP_LEFT)
2132            .start_angle(PI / 4.0)
2133            .end_angle(PI * 3.0 / 4.0)
2134            .stops(vec![0.0, 0.5, 1.0])
2135            .tile_mode(TileMode::Decal)
2136            .transform(GradientRotation::new(PI / 4.0));
2137        assert_matches_sweep(
2138            &test_gradient.scale(0.5),
2139            &SweepGradient::new(colors(&[0x80FF0000, 0x8000FF00, 0x800000FF]))
2140                .center(AlignmentGeometry::TOP_LEFT)
2141                .start_angle(PI / 4.0)
2142                .end_angle(PI * 3.0 / 4.0)
2143                .stops(vec![0.0, 0.5, 1.0])
2144                .tile_mode(TileMode::Decal)
2145                .transform(GradientRotation::new(PI / 4.0)),
2146        );
2147    }
2148
2149    #[test]
2150    fn gradient_lerp_interpolates_radial_gradients_both_ways() {
2151        let test_gradient1 = RadialGradient::new(colors(&[0x33333333, 0x66666666]))
2152            .center(AlignmentGeometry::TOP_LEFT)
2153            .radius(20.0)
2154            .stops(vec![0.0, 1.0]);
2155        let test_gradient2 = RadialGradient::new(colors(&[0x3B3B3B3B, 0x77777777]))
2156            .center(AlignmentGeometry::TOP_CENTER)
2157            .radius(15.0)
2158            .stops(vec![0.0, 1.0]);
2159        let test_gradient3 = RadialGradient::new(colors(&[0x44444444, 0x88888888]))
2160            .center(AlignmentGeometry::TOP_RIGHT)
2161            .radius(10.0)
2162            .stops(vec![0.0, 1.0]);
2163        let lerp = |a: &RadialGradient, b: &RadialGradient, t| {
2164            GradientRef::lerp(
2165                Some(&GradientRef::new(a.clone())),
2166                Some(&GradientRef::new(b.clone())),
2167                t,
2168            )
2169            .unwrap()
2170        };
2171
2172        assert_matches_radial(
2173            &*lerp(&test_gradient1, &test_gradient3, 0.0),
2174            &test_gradient1,
2175        );
2176        assert_matches_radial(
2177            &*lerp(&test_gradient1, &test_gradient3, 0.5),
2178            &test_gradient2,
2179        );
2180        assert_matches_radial(
2181            &*lerp(&test_gradient1, &test_gradient3, 1.0),
2182            &test_gradient3,
2183        );
2184        assert_matches_radial(
2185            &*lerp(&test_gradient3, &test_gradient1, 0.0),
2186            &test_gradient3,
2187        );
2188        assert_matches_radial(
2189            &*lerp(&test_gradient3, &test_gradient1, 0.5),
2190            &test_gradient2,
2191        );
2192        assert_matches_radial(
2193            &*lerp(&test_gradient3, &test_gradient1, 1.0),
2194            &test_gradient1,
2195        );
2196    }
2197
2198    #[test]
2199    fn gradient_lerp_from_a_linear_to_a_radial_gradient_fades_through_nothing() {
2200        let test_gradient1 = LinearGradient::new(colors(&[0x33333333, 0x66666666]))
2201            .begin(AlignmentGeometry::TOP_LEFT)
2202            .end(AlignmentGeometry::BOTTOM_RIGHT);
2203        let test_gradient2 = RadialGradient::new(colors(&[0x44444444, 0x88888888])).radius(20.0);
2204        let lerp = |t| {
2205            GradientRef::lerp(
2206                Some(&GradientRef::new(test_gradient1.clone())),
2207                Some(&GradientRef::new(test_gradient2.clone())),
2208                t,
2209            )
2210            .unwrap()
2211        };
2212
2213        assert!(lerp(0.0).eq_gradient(&test_gradient1));
2214        assert!(lerp(1.0).eq_gradient(&test_gradient2));
2215        assert!(lerp(0.5).eq_gradient(&test_gradient2.scale(0.0)));
2216    }
2217
2218    #[test]
2219    fn gradients_imply_missing_stops_and_reject_mismatched_ones() {
2220        let three = colors(&[0x11111111, 0x22222222, 0x33333333]);
2221        let test1a = LinearGradient::new(three.clone());
2222        let test1b = RadialGradient::new(three.clone());
2223        let test2a = LinearGradient::new(three.clone()).stops(vec![0.0, 1.0]);
2224        let test2b = RadialGradient::new(three).stops(vec![0.0, 1.0]);
2225        let rect = Rect::from_ltwh(1.0, 2.0, 3.0, 4.0);
2226        assert_eq!(test1a.create_shader(rect, None).stops().len(), 3);
2227        assert_eq!(test1b.create_shader(rect, None).stops().len(), 3);
2228        assert!(catch_unwind(AssertUnwindSafe(|| test2a.create_shader(rect, None))).is_err());
2229        assert!(catch_unwind(AssertUnwindSafe(|| test2b.create_shader(rect, None))).is_err());
2230    }
2231
2232    fn point(x: f32, y: f32) -> Point {
2233        Point { x, y }
2234    }
2235
2236    fn assert_maps(matrix: Matrix4, from: Point, to: Point) {
2237        let mapped = matrix.map_point(from);
2238        assert!(
2239            (mapped.x - to.x).abs() < 1e-3 && (mapped.y - to.y).abs() < 1e-3,
2240            "{from:?} mapped to {mapped:?}, not {to:?}"
2241        );
2242    }
2243
2244    const TRANSFORMS_RECT: Rect = Rect::from_ltwh(0.0, 0.0, 300.0, 400.0);
2245
2246    #[test]
2247    fn a_gradient_rotation_turns_clockwise_about_the_bounds_centre() {
2248        let quarter = GradientRotation::new(PI / 2.0)
2249            .transform(TRANSFORMS_RECT, None)
2250            .unwrap();
2251        assert_maps(quarter, point(150.0, 200.0), point(150.0, 200.0));
2252        assert_maps(quarter, point(0.0, 0.0), point(350.0, 50.0));
2253
2254        let eighth = GradientRotation::new(PI / 4.0)
2255            .transform(TRANSFORMS_RECT, None)
2256            .unwrap();
2257        assert_maps(eighth, point(150.0, 200.0), point(150.0, 200.0));
2258        let half_root_two = std::f32::consts::FRAC_1_SQRT_2;
2259        assert_maps(
2260            eighth,
2261            point(0.0, 0.0),
2262            point(150.0 + 50.0 * half_root_two, 200.0 - 350.0 * half_root_two),
2263        );
2264    }
2265
2266    #[test]
2267    fn each_gradient_hands_its_rotation_to_its_shader() {
2268        let gradient_colors = colors(&[0xFFFFFFFF, 0xFF000088]);
2269        let stops = vec![
2270            GradientStop {
2271                offset: 0.0,
2272                color: Color::new(0xFFFFFFFF).into(),
2273            },
2274            GradientStop {
2275                offset: 1.0,
2276                color: Color::new(0xFF000088).into(),
2277            },
2278        ];
2279        for radians in [PI / 4.0, PI / 2.0] {
2280            let rotation = GradientRotation::new(radians);
2281            let local = rotation.transform(TRANSFORMS_RECT, None).unwrap();
2282            assert_eq!(
2283                LinearGradient::new(gradient_colors.clone())
2284                    .transform(rotation)
2285                    .create_shader(TRANSFORMS_RECT, None),
2286                Shader::Linear {
2287                    start: point(0.0, 200.0),
2288                    end: point(300.0, 200.0),
2289                    stops: stops.clone(),
2290                    spread: SpreadMode::Pad,
2291                    local,
2292                }
2293            );
2294            assert_eq!(
2295                RadialGradient::new(gradient_colors.clone())
2296                    .center(AlignmentGeometry::TOP_CENTER)
2297                    .transform(rotation)
2298                    .create_shader(TRANSFORMS_RECT, None),
2299                Shader::Radial {
2300                    center: point(150.0, 0.0),
2301                    radius: 150.0,
2302                    stops: stops.clone(),
2303                    spread: SpreadMode::Pad,
2304                    focus: None,
2305                    local,
2306                }
2307            );
2308            assert_eq!(
2309                SweepGradient::new(gradient_colors.clone())
2310                    .transform(rotation)
2311                    .create_shader(TRANSFORMS_RECT, None),
2312                Shader::Sweep {
2313                    center: point(150.0, 200.0),
2314                    start_angle: 0.0,
2315                    end_angle: (PI * 2.0) as f32,
2316                    stops: stops.clone(),
2317                    spread: SpreadMode::Pad,
2318                    local,
2319                }
2320            );
2321        }
2322    }
2323
2324    #[test]
2325    fn a_focal_radial_gradient_starts_from_its_focal_circle() {
2326        let shader = RadialGradient::new(colors(&[0xFFFFFFFF, 0xFF000088]))
2327            .focal(AlignmentGeometry::TOP_LEFT)
2328            .focal_radius(0.1)
2329            .tile_mode(TileMode::Mirror)
2330            .create_shader(TRANSFORMS_RECT, None);
2331        let Shader::Radial { focus, spread, .. } = shader else {
2332            panic!("a radial shader: {shader:?}");
2333        };
2334        assert_eq!(
2335            focus,
2336            Some(FocalCircle {
2337                center: point(0.0, 0.0),
2338                radius: 30.0,
2339            })
2340        );
2341        assert_eq!(spread, SpreadMode::Reflect);
2342    }
2343
2344    #[test]
2345    fn a_focal_point_on_the_centre_is_a_plain_radial_gradient() {
2346        let shader = RadialGradient::new(colors(&[0xFFFFFFFF, 0xFF000088]))
2347            .focal(AlignmentGeometry::CENTER)
2348            .create_shader(TRANSFORMS_RECT, None);
2349        assert!(
2350            matches!(shader, Shader::Radial { focus: None, .. }),
2351            "{shader:?}"
2352        );
2353    }
2354
2355    #[test]
2356    fn a_linear_gradient_spreads_its_stops_and_tiles_as_asked() {
2357        let shader = LinearGradient::new(colors(&[0xFF000001, 0xFF000002, 0xFF000003]))
2358            .tile_mode(TileMode::Repeat)
2359            .create_shader(TRANSFORMS_RECT, None);
2360        let Shader::Linear {
2361            stops,
2362            spread,
2363            local,
2364            ..
2365        } = shader
2366        else {
2367            panic!("a linear shader: {shader:?}");
2368        };
2369        assert_eq!(
2370            stops.iter().map(|stop| stop.offset).collect::<Vec<_>>(),
2371            [0.0, 0.5, 1.0]
2372        );
2373        assert_eq!(spread, SpreadMode::Repeat);
2374        assert_eq!(local, Matrix4::IDENTITY);
2375    }
2376}