Skip to main content

waft_embedder/
painting.rs

1//! Flutter counterpart: dart:ui `Canvas` / `Paint` / `Path` / `Picture` /
2//! `Image`. These are valo types under Flutter names, but for [`Path`], a valo path with the
3//! fill type valo takes beside it; the paragraph types live in `paragraph.rs`.
4//!
5//! Recording uses valo method signatures (`draw_rect`, f32 `Rect`). Convert
6//! framework geometry with [`From`] at the call (`rect.into()`).
7
8use std::fmt::Display;
9use std::sync::Arc;
10
11use valo::DisplayList;
12use valo::DisplayListBuilder;
13use valo::Op;
14
15use crate::{Matrix4, Offset, Rect};
16
17/// Flutter `Canvas` — valo records into a display list.
18pub type Canvas = DisplayListBuilder;
19
20/// Flutter `Picture` — a finished display list, what a scene's layers hold and what a host
21/// draws.
22pub type Picture = DisplayList;
23
24/// Flutter `StrokeCap` — valo's `Cap`: how a stroke ends at an open contour, `Butt` by default.
25pub type StrokeCap = valo::Cap;
26
27/// Flutter `PathFillType` — valo's `FillRule`: how the interior of a [`Path`] is calculated,
28/// which valo takes beside the path's contours wherever it fills, clips to or hit tests them.
29pub type PathFillType = valo::FillRule;
30
31/// Flutter `PaintingStyle` — valo's `PaintStyle`: whether a [`Paint`] fills a shape or strokes
32/// its outline. Its `Stroke` variant carries the [`Stroke`] (width, cap, join, miter limit) that
33/// a Dart `Paint` keeps in fields of its own.
34pub type PaintingStyle = valo::PaintStyle;
35
36/// The picture's operations in replay order with every embedded list's following its embedding
37/// op, for a test or a diagnostic that asks what a scene draws regardless of how its layers
38/// nested it.
39pub fn flattened_ops(picture: &Picture) -> Vec<Op> {
40    let mut ops = Vec::new();
41    flatten_into(picture, &mut ops);
42    ops
43}
44
45fn flatten_into(picture: &Picture, ops: &mut Vec<Op>) {
46    for op in picture.ops() {
47        ops.push(op.clone());
48        if let Op::DrawDisplayList { list, .. } = op {
49            flatten_into(list, ops);
50        }
51    }
52}
53
54pub use valo::{
55    Backdrop, BlendMode, BlurStyle, ClipOp, FillRule, Image, MaskBlur, Paint, PaintStyle,
56    PathBuilder, PathOperation, Shader, Stroke,
57};
58
59/// A complex, one-dimensional subset of a plane: dart:ui's `Path`.
60///
61/// Its contours are a valo path, built with a [`PathBuilder`] and shared, not copied, by every
62/// clone; its [`fill_type`](Self::fill_type) is what valo is handed with them wherever the path
63/// is filled, clipped to or hit tested. A call that passes [`as_valo`](Self::as_valo) to valo
64/// without the fill type fills the path with whatever rule it names instead.
65///
66/// Two paths are equal when their contours and fill types are, which is how a scene tells a
67/// clip that changed from one that did not.
68#[derive(Clone, Debug, PartialEq)]
69pub struct Path {
70    contours: Arc<valo::Path>,
71    /// Determines how the interior of this path is calculated.
72    ///
73    /// Defaults to the non-zero winding rule, [`PathFillType::NonZero`].
74    pub fill_type: PathFillType,
75}
76
77impl Path {
78    /// The path of `contours`, filled with the non-zero winding rule, as dart:ui's `Path()` is.
79    pub fn new(contours: Arc<valo::Path>) -> Path {
80        Path {
81            contours,
82            fill_type: PathFillType::NonZero,
83        }
84    }
85
86    /// The contours, for valo's calls, which take the fill type beside them.
87    pub fn as_valo(&self) -> &Arc<valo::Path> {
88        &self.contours
89    }
90
91    /// Tests to see if the given point is within the path. (That is, whether the point would be
92    /// in the visible portion of the path if the path was used with [`Canvas::clip_path`].)
93    ///
94    /// The `point` argument is interpreted as an offset from the origin.
95    ///
96    /// Returns true if the point is in the path, and false otherwise.
97    pub fn contains(&self, point: Offset) -> bool {
98        self.contours.contains(point.into(), self.fill_type)
99    }
100
101    /// Computes the bounding rectangle for this path.
102    ///
103    /// A path containing only axis-aligned points on the same straight line will have no area,
104    /// and therefore `Rect::is_empty` will return true for such a path.
105    pub fn get_bounds(&self) -> Rect {
106        let bounds = self.contours.bounds();
107        Rect::from_ltwh(
108            f64::from(bounds.x),
109            f64::from(bounds.y),
110            f64::from(bounds.width),
111            f64::from(bounds.height),
112        )
113    }
114
115    /// Returns a copy of the path with all the segments of every subpath translated by the given
116    /// offset: Skia's `makeTransform` by a translation, so a path built as a rounded rectangle or
117    /// an oval stays one, and a shadow drawn from it keeps its closed form.
118    pub fn shift(&self, offset: Offset) -> Path {
119        if offset == Offset::ZERO {
120            return self.clone();
121        }
122        self.transform(&Matrix4::translation(
123            offset.dx() as f32,
124            offset.dy() as f32,
125        ))
126    }
127
128    /// Returns a copy of the path with all the segments of every sub path transformed by the
129    /// given matrix.
130    pub fn transform(&self, matrix: &Matrix4) -> Path {
131        Path {
132            contours: self.contours.transformed(matrix),
133            fill_type: self.fill_type,
134        }
135    }
136}
137
138impl From<Arc<valo::Path>> for Path {
139    fn from(contours: Arc<valo::Path>) -> Path {
140        Path::new(contours)
141    }
142}
143
144/// Combines the two paths according to the manner specified by the given `operation`: dart:ui's
145/// `Path.combine`, Skia's `Op`, which reads each path with its own fill type.
146///
147/// The resulting path will be constructed from non-overlapping contours. The curve order is
148/// reduced where possible so that cubics may be turned into quadratics, and quadratics maybe
149/// turned into lines. It fills with the even-odd rule, as Skia's `Op` sets on what it writes.
150///
151/// Panics where Dart throws its `StateError`: Skia's `Op` gives no path for these two.
152pub fn path_combine(operation: PathOperation, path1: &Path, path2: &Path) -> Path {
153    let contours = path1
154        .contours
155        .combine(path1.fill_type, operation, &path2.contours, path2.fill_type)
156        .unwrap_or_else(|_| {
157            panic!(
158                "Path.combine() failed.  This may be due an invalid path; in particular, check for NaN values."
159            )
160        });
161    Path {
162        contours,
163        fill_type: PathFillType::EvenOdd,
164    }
165}
166
167/// The full valo API for hosts and for recording that needs a type the
168/// aliases do not cover (`Op`, `Context`, `Surface`).
169pub use valo;
170
171/// Quality levels for image sampling in [`ImageFilter`] and [`Shader`] objects that sample
172/// images and for [`Canvas`] operations that render images.
173///
174/// When scaling up typically the quality is lowest at [`none`](Self::None), higher at
175/// [`low`](Self::Low) and [`medium`](Self::Medium), and for very large scale factors (over 10x)
176/// the highest at [`high`](Self::High).
177///
178/// When scaling down, [`medium`](Self::Medium) provides the best quality especially when scaling
179/// an image to less than half its size or for animating the scale factor between such
180/// reductions. Otherwise, [`low`](Self::Low) and [`high`](Self::High) provide similar effects for
181/// reductions of between 50% and 100% but the image may lose detail and have dropouts below 50%.
182///
183/// To get high quality when scaling images up and down, or when the scale is unknown,
184/// [`medium`](Self::Medium) is typically a good balanced choice.
185///
186/// See also:
187///
188///  * [`FragmentShader::set_image_sampler`](crate::FragmentShader::set_image_sampler).
189///  * [`ImageFilter::shader`].
190#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
191pub enum FilterQuality {
192    /// The fastest filtering method, albeit also the lowest quality.
193    ///
194    /// This value results in a "Nearest Neighbor" algorithm which just repeats or eliminates
195    /// pixels as an image is scaled up or down.
196    None,
197
198    /// Better quality than [`none`](Self::None), faster than [`medium`](Self::Medium).
199    ///
200    /// This value results in a "Bilinear" algorithm which smoothly interpolates between pixels in
201    /// an image.
202    Low,
203
204    /// The best all around filtering method that is only worse than [`high`](Self::High) at
205    /// extremely large scale factors.
206    ///
207    /// This value improves upon the "Bilinear" algorithm specified by [`low`](Self::Low) by
208    /// utilizing a Mipmap that pre-computes high quality lower resolutions of the image at half
209    /// (and quarter and eighth, etc.) sizes and then blends between those to prevent loss of
210    /// detail at small scale sizes.
211    Medium,
212
213    /// Best possible quality when scaling up images by scale factors larger than 5-10x.
214    ///
215    /// When images are scaled down, this can be worse than [`medium`](Self::Medium) for scales
216    /// smaller than 0.5x, or when animating the scale factor.
217    ///
218    /// This option is also the slowest.
219    ///
220    /// This value results in a standard "Bicubic" algorithm which uses a 3rd order equation to
221    /// smooth the abrupt transitions between pixels while preserving some of the sense of an edge
222    /// and avoiding sharp peaks in the result.
223    High,
224}
225
226impl FilterQuality {
227    /// How valo samples an image at this quality: the engine's `ImageFilter::SamplingFromIndex`
228    /// as Impeller's `ToSamplerDescriptor` turns it into a sampler, clamped at the edges as
229    /// `ReusableFragmentShader::SetImageSampler` clamps them. Impeller samples
230    /// [`High`](Self::High), the engine's cubic, as it samples [`Medium`](Self::Medium).
231    pub fn to_valo(self) -> valo::Sampling {
232        let (filter, mipmap) = match self {
233            FilterQuality::None => (valo::Filter::Nearest, valo::MipmapMode::None),
234            FilterQuality::Low => (valo::Filter::Linear, valo::MipmapMode::None),
235            FilterQuality::Medium | FilterQuality::High => {
236                (valo::Filter::Linear, valo::MipmapMode::Linear)
237            }
238        };
239        valo::Sampling {
240            filter,
241            mipmap,
242            tile_x: valo::TileMode::Clamp,
243            tile_y: valo::TileMode::Clamp,
244        }
245    }
246}
247
248impl std::fmt::Display for FilterQuality {
249    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250        let name = match self {
251            FilterQuality::None => "none",
252            FilterQuality::Low => "low",
253            FilterQuality::Medium => "medium",
254            FilterQuality::High => "high",
255        };
256        write!(f, "FilterQuality.{name}")
257    }
258}
259
260/// A description of a color filter to apply when drawing a shape or compositing
261/// a layer with a particular [`Paint`]. A color filter is a function that takes
262/// two colors, and outputs one color. When applied during compositing, it is
263/// independently applied to each pixel of the layer being drawn before the
264/// entire layer is merged with the destination.
265///
266/// Instances of this class are used with [`Paint`]'s color filter on `Paint`
267/// objects.
268#[derive(Clone, Copy, Debug, PartialEq)]
269pub enum ColorFilter {
270    /// Applies the blend mode, with the color as the source and the layer being
271    /// composited as the destination; Dart's `ColorFilter.mode`.
272    Mode {
273        /// The source color of the blend.
274        color: crate::Color,
275        /// How the source color is composited onto the destination.
276        blend_mode: BlendMode,
277    },
278
279    /// A 4x5 row-major matrix over `[R, G, B, A]`; Dart's `ColorFilter.matrix`.
280    ///
281    /// Every pixel's color value, represented as an `[R, G, B, A]`, is matrix
282    /// multiplied to create a new color:
283    ///
284    /// ```text
285    /// | R' |   | a00 a01 a02 a03 a04 |   | R |
286    /// | G' |   | a10 a11 a12 a13 a14 |   | G |
287    /// | B' | = | a20 a21 a22 a23 a24 | * | B |
288    /// | A' |   | a30 a31 a32 a33 a34 |   | A |
289    /// | 1  |   |  0   0   0   0   1  |   | 1 |
290    /// ```
291    ///
292    /// The matrix is in row-major order and the translation column is specified
293    /// in unnormalized, 0...255, space.
294    Matrix([f64; 20]),
295
296    /// Applies the sRGB gamma curve to the RGB channels; Dart's
297    /// `ColorFilter.linearToSrgbGamma`.
298    LinearToSrgbGamma,
299
300    /// Applies the inverse of the sRGB gamma curve to the RGB channels; Dart's
301    /// `ColorFilter.srgbToLinearGamma`.
302    SrgbToLinearGamma,
303}
304
305impl ColorFilter {
306    /// Creates a color filter that applies the blend mode given as the second
307    /// argument. The source color is the one given as the first argument, and the
308    /// destination color is the one from the layer being composited.
309    ///
310    /// The output of this filter is then composited into the background according
311    /// to the `Paint`'s blend mode, using the output of this filter as the source
312    /// and the background as the destination.
313    pub const fn mode(color: crate::Color, blend_mode: BlendMode) -> ColorFilter {
314        ColorFilter::Mode { color, blend_mode }
315    }
316
317    /// Constructs a color filter from a 4x5 row-major matrix. The matrix is
318    /// interpreted as a 5x5 matrix, where the fifth row is the identity
319    /// configuration.
320    ///
321    /// The identity matrix is:
322    ///
323    /// ```
324    /// # use waft_embedder::ColorFilter;
325    /// const IDENTITY: ColorFilter = ColorFilter::matrix([
326    ///     1.0, 0.0, 0.0, 0.0, 0.0, //
327    ///     0.0, 1.0, 0.0, 0.0, 0.0, //
328    ///     0.0, 0.0, 1.0, 0.0, 0.0, //
329    ///     0.0, 0.0, 0.0, 1.0, 0.0, //
330    /// ]);
331    /// ```
332    pub const fn matrix(matrix: [f64; 20]) -> ColorFilter {
333        ColorFilter::Matrix(matrix)
334    }
335
336    /// Constructs a color filter that applies the sRGB gamma curve to the RGB
337    /// channels.
338    pub const fn linear_to_srgb_gamma() -> ColorFilter {
339        ColorFilter::LinearToSrgbGamma
340    }
341
342    /// Creates a color filter that applies the inverse of the sRGB gamma curve
343    /// to the RGB channels.
344    pub const fn srgb_to_linear_gamma() -> ColorFilter {
345        ColorFilter::SrgbToLinearGamma
346    }
347
348    /// Creates a color filter that applies the given saturation to the RGB
349    /// channels.
350    pub fn saturation(saturation: f64) -> ColorFilter {
351        const R_LUMINANCE: f64 = 0.2126;
352        const G_LUMINANCE: f64 = 0.7152;
353        const B_LUMINANCE: f64 = 0.0722;
354        let inv_sat = 1.0 - saturation;
355
356        ColorFilter::matrix([
357            inv_sat * R_LUMINANCE + saturation,
358            inv_sat * G_LUMINANCE,
359            inv_sat * B_LUMINANCE,
360            0.0,
361            0.0,
362            inv_sat * R_LUMINANCE,
363            inv_sat * G_LUMINANCE + saturation,
364            inv_sat * B_LUMINANCE,
365            0.0,
366            0.0,
367            inv_sat * R_LUMINANCE,
368            inv_sat * G_LUMINANCE,
369            inv_sat * B_LUMINANCE + saturation,
370            0.0,
371            0.0,
372            0.0,
373            0.0,
374            0.0,
375            1.0,
376            0.0,
377        ])
378    }
379
380    /// Dart's `debugShortDescription`.
381    pub fn debug_short_description(&self) -> String {
382        match self {
383            ColorFilter::Mode { color, blend_mode } => {
384                format!("ColorFilter.mode({color:?}, {blend_mode:?})")
385            }
386            ColorFilter::Matrix(matrix) => format!("ColorFilter.matrix({matrix:?})"),
387            ColorFilter::LinearToSrgbGamma => String::from("ColorFilter.linearToSrgbGamma()"),
388            ColorFilter::SrgbToLinearGamma => String::from("ColorFilter.srgbToLinearGamma()"),
389        }
390    }
391}
392
393impl std::fmt::Display for ColorFilter {
394    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395        f.write_str(&self.debug_short_description())
396    }
397}
398
399impl ColorFilter {
400    /// The valo filter that replays this one.
401    pub fn to_valo(&self) -> valo::ColorFilter {
402        match *self {
403            ColorFilter::Mode { color, blend_mode } => {
404                valo::ColorFilter::Blend(color.into(), blend_mode)
405            }
406            ColorFilter::Matrix(matrix) => valo::ColorFilter::Matrix(valo_matrix(matrix)),
407            ColorFilter::LinearToSrgbGamma => valo::ColorFilter::LinearToSrgbGamma,
408            ColorFilter::SrgbToLinearGamma => valo::ColorFilter::SrgbToLinearGamma,
409        }
410    }
411}
412
413/// A colour matrix in valo's terms: the translation column, which Flutter gives in 0...255,
414/// in the 0...1 its colour channels are in.
415fn valo_matrix(matrix: [f64; 20]) -> [f32; 20] {
416    const ROW_LENGTH: usize = 5;
417    const TRANSLATION_COLUMN: usize = 4;
418    std::array::from_fn(|index| {
419        let entry = matrix[index];
420        let entry = if index % ROW_LENGTH == TRANSLATION_COLUMN {
421            entry / 255.0
422        } else {
423            entry
424        };
425        entry as f32
426    })
427}
428
429/// A filter operation to apply to a raster image.
430///
431/// See also:
432///
433///  * `BackdropFilter`, a widget that applies [`ImageFilter`] to its rendering.
434///  * `ImageFiltered`, a widget that applies [`ImageFilter`] to its children.
435///  * `SceneBuilder.pushBackdropFilter`, which is the low-level API for using
436///    this class as a backdrop filter.
437///  * `SceneBuilder.pushImageFilter`, which is the low-level API for using
438///    this class as a child layer filter.
439#[derive(Clone, Debug, PartialEq)]
440pub enum ImageFilter {
441    /// A Gaussian blur; Dart's `_GaussianBlurImageFilter`.
442    Blur {
443        /// The standard deviation along the horizontal axis.
444        sigma_x: f64,
445        /// The standard deviation along the vertical axis.
446        sigma_y: f64,
447        /// The area the blur is confined to, when given.
448        bounds: Option<crate::Rect>,
449    },
450
451    /// A [`ColorFilter`] used as an image filter; Dart's `ColorFilter implements
452    /// ImageFilter`.
453    Color(ColorFilter),
454
455    /// `outer` applied to the result of `inner`; Dart's `_ComposeImageFilter`.
456    Compose {
457        /// The filter that receives the filtered result of `inner`.
458        outer: Arc<ImageFilter>,
459        /// The filter that receives the original input.
460        inner: Arc<ImageFilter>,
461    },
462
463    /// The input moved by a matrix; Dart's `_MatrixImageFilter`, made by
464    /// [`ImageFilter::matrix`].
465    Matrix {
466        /// The matrix that moves the input.
467        data: crate::Matrix4,
468        /// The quality the moved input is sampled at.
469        filter_quality: FilterQuality,
470    },
471
472    /// A [`FragmentShader`](crate::FragmentShader)'s program run over the input; Dart's
473    /// `_FragmentShaderImageFilter`, made by [`ImageFilter::shader`].
474    Shader {
475        /// The shader's uniforms and images as they were when the filter was made, its first
476        /// image left for the input, which is sampled at `filter_quality`.
477        shader: valo::RuntimeShader,
478        /// The quality the input is sampled at.
479        filter_quality: FilterQuality,
480    },
481}
482
483impl ImageFilter {
484    /// Creates an image filter that applies a Gaussian blur.
485    pub const fn blur(sigma_x: f64, sigma_y: f64) -> ImageFilter {
486        ImageFilter::Blur {
487            sigma_x,
488            sigma_y,
489            bounds: None,
490        }
491    }
492
493    /// Dart `ImageFilter.blur(bounds:)`.
494    pub fn bounds(self, bounds: crate::Rect) -> ImageFilter {
495        match self {
496            ImageFilter::Blur {
497                sigma_x, sigma_y, ..
498            } => ImageFilter::Blur {
499                sigma_x,
500                sigma_y,
501                bounds: Some(bounds),
502            },
503            other => other,
504        }
505    }
506
507    /// Creates an image filter that applies a matrix transformation.
508    ///
509    /// For example, applying a positive scale matrix (see `Matrix4.diagonal3`) when used with
510    /// `BackdropFilter` would magnify the background image.
511    ///
512    /// The `filter_quality` argument sets the quality level the moved input is sampled at;
513    /// Flutter's default is [`FilterQuality::Medium`].
514    pub const fn matrix(matrix4: crate::Matrix4, filter_quality: FilterQuality) -> ImageFilter {
515        ImageFilter::Matrix {
516            data: matrix4,
517            filter_quality,
518        }
519    }
520
521    /// Composes the `inner` filter with `outer`, to combine their effects.
522    ///
523    /// Creates a single [`ImageFilter`] that when applied, has the same effect as
524    /// subsequently applying `inner` and `outer`, i.e.,
525    /// `result = outer(inner(source))`.
526    #[cfg_attr(
527        target_arch = "wasm32",
528        expect(
529            clippy::arc_with_non_send_sync,
530            reason = "a shader filter's images are the web's GPU objects, which stay on their \
531                      thread there; a filter crosses threads with its picture elsewhere"
532        )
533    )]
534    pub fn compose(outer: ImageFilter, inner: ImageFilter) -> ImageFilter {
535        ImageFilter::Compose {
536            outer: Arc::new(outer),
537            inner: Arc::new(inner),
538        }
539    }
540
541    /// Creates an image filter from a [`FragmentShader`](crate::FragmentShader).
542    ///
543    /// The fragment shader provided here has additional requirements to be used by the engine
544    /// for filtering. The first uniform value must be a `vec2`, this will be set by the engine to
545    /// the size of the bound texture. There must also be at least one image, the first of which
546    /// will be set by the engine to contain the filter input.
547    ///
548    /// The `filter_quality` argument sets the quality level used to sample the filter input;
549    /// Flutter's default is [`FilterQuality::None`].
550    ///
551    /// For example, the following is a valid fragment shader that can be used with this API.
552    /// Note that the uniform names are not required to have any particular value.
553    ///
554    /// ```wgsl
555    /// struct Uniforms { u_size: vec2<f32>, u_time: f32 }
556    /// @group(2) @binding(0) var<uniform> u: Uniforms;
557    /// @group(1) @binding(0) var u_texture_input: texture_2d<f32>;
558    /// @group(1) @binding(1) var u_texture_input_sampler: sampler;
559    ///
560    /// fn shade(position: vec2<f32>) -> vec4<f32> {
561    ///     let uv = position / u.u_size;
562    ///     return textureSampleLevel(u_texture_input, u_texture_input_sampler, uv, 0.0) * u.u_time;
563    /// }
564    /// ```
565    ///
566    /// The uniforms and images are those `shader` has now; setting them afterwards changes the
567    /// filter made next, not this one.
568    ///
569    /// # Panics
570    ///
571    /// Where the shader's first uniform is not a `vec2` or it has no image, as Dart throws a
572    /// `StateError`.
573    pub fn shader(shader: &crate::FragmentShader, filter_quality: FilterQuality) -> ImageFilter {
574        let invalid_floats = shader.float_count() < 2;
575        let invalid_sampler = !shader.validate_image_filter();
576        if invalid_floats || invalid_sampler {
577            let mut buffer = String::from(
578                "ImageFilter.shader requires that the first uniform is a vec2 and at least one \
579                 sampler uniform is present.\n",
580            );
581            if invalid_floats {
582                buffer.push_str("The shader has fewer than two float uniforms.\n");
583            }
584            if invalid_sampler {
585                buffer.push_str("The shader is missing a sampler uniform.\n");
586            }
587            panic!("{buffer}");
588        }
589        let shader = shader.as_image_filter(filter_quality.to_valo());
590        if let Err(error) = valo::ImageFilter::runtime(shader.clone()) {
591            panic!("ImageFilter.shader requires that the first uniform is a vec2: {error}");
592        }
593        ImageFilter::Shader {
594            shader,
595            filter_quality,
596        }
597    }
598
599    /// Whether [`ImageFilter::shader`] is supported on the current backend: always, as valo
600    /// runs every shader the way Impeller does.
601    pub const fn is_shader_filter_supported() -> bool {
602        true
603    }
604
605    /// Dart's `debugShortDescription`.
606    pub fn debug_short_description(&self) -> String {
607        match self {
608            ImageFilter::Blur {
609                sigma_x,
610                sigma_y,
611                bounds,
612            } => {
613                let bounds = match bounds {
614                    Some(bounds) => format!(", bounds: {bounds:?}"),
615                    None => String::new(),
616                };
617                format!("blur({sigma_x}, {sigma_y}, unspecified{bounds})")
618            }
619            ImageFilter::Color(filter) => filter.debug_short_description(),
620            ImageFilter::Matrix {
621                data,
622                filter_quality,
623            } => format!("matrix({:?}, {filter_quality})", data.to_flutter_array()),
624            ImageFilter::Compose { outer, inner } => format!(
625                "{} -> {}",
626                inner.debug_short_description(),
627                outer.debug_short_description()
628            ),
629            ImageFilter::Shader { .. } => String::from("shader"),
630        }
631    }
632}
633
634impl std::fmt::Display for ImageFilter {
635    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
636        match self {
637            ImageFilter::Blur { .. } | ImageFilter::Matrix { .. } => {
638                write!(f, "ImageFilter.{}", self.debug_short_description())
639            }
640            ImageFilter::Color(filter) => Display::fmt(filter, f),
641            ImageFilter::Compose { .. } => write!(
642                f,
643                "ImageFilter.compose(source -> {} -> result)",
644                self.debug_short_description()
645            ),
646            ImageFilter::Shader {
647                shader,
648                filter_quality,
649            } => write!(
650                f,
651                "ImageFilter.shader(Shader#{}, {filter_quality})",
652                shader.effect.id()
653            ),
654        }
655    }
656}
657
658impl ImageFilter {
659    /// The valo filter that replays this one, step for step and in the same order.
660    pub fn to_valo(&self) -> valo::ImageFilter {
661        match self {
662            ImageFilter::Blur {
663                sigma_x,
664                sigma_y,
665                bounds,
666            } => {
667                let (sigma_x, sigma_y) = (*sigma_x as f32, *sigma_y as f32);
668                match bounds {
669                    Some(bounds) => {
670                        valo::ImageFilter::bounded_blur(sigma_x, sigma_y, (*bounds).into())
671                    }
672                    None => valo::ImageFilter::blur(sigma_x, sigma_y),
673                }
674            }
675            ImageFilter::Color(filter) => valo::ImageFilter::Color(filter.to_valo()),
676            ImageFilter::Matrix {
677                data,
678                filter_quality,
679            } => valo::ImageFilter::matrix(*data, filter_quality.to_valo()),
680            ImageFilter::Compose { outer, inner } => {
681                valo::ImageFilter::compose(outer.to_valo(), inner.to_valo())
682            }
683            ImageFilter::Shader { shader, .. } => valo::ImageFilter::Runtime(shader.clone()),
684        }
685    }
686}
687
688#[cfg(test)]
689mod tests {
690    use std::sync::Arc;
691
692    use super::{
693        ColorFilter, FilterQuality, ImageFilter, Path, PathBuilder, PathFillType, PathOperation,
694        path_combine, valo,
695    };
696    use crate::{BlendMode, Color, Matrix4, Offset, Rect};
697
698    #[test]
699    fn a_saturation_of_one_is_the_identity_matrix() {
700        let ColorFilter::Matrix(matrix) = ColorFilter::saturation(1.0) else {
701            panic!("saturation is a matrix filter");
702        };
703        let identity = [
704            1.0, 0.0, 0.0, 0.0, 0.0, //
705            0.0, 1.0, 0.0, 0.0, 0.0, //
706            0.0, 0.0, 1.0, 0.0, 0.0, //
707            0.0, 0.0, 0.0, 1.0, 0.0, //
708        ];
709        for (value, expected) in matrix.iter().zip(identity) {
710            assert!((value - expected).abs() < 1e-12, "{matrix:?}");
711        }
712    }
713
714    #[test]
715    fn a_matrix_filter_reaches_valo_with_its_sampling_and_prints_as_darts() {
716        let scale = Matrix4::scale(2.0, 2.0);
717        let filter = ImageFilter::matrix(scale, FilterQuality::Low);
718        assert_eq!(
719            filter.to_valo(),
720            valo::ImageFilter::matrix(scale, FilterQuality::Low.to_valo())
721        );
722        assert_eq!(
723            filter.to_string(),
724            "ImageFilter.matrix([2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, \
725             0.0, 0.0, 0.0, 1.0], FilterQuality.low)"
726        );
727    }
728
729    #[test]
730    fn combining_two_paths_cuts_one_from_the_other() {
731        let mut host = PathBuilder::new();
732        host.rect(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0).into());
733        let mut guest = PathBuilder::new();
734        guest.rect(Rect::from_ltwh(50.0, -10.0, 100.0, 60.0).into());
735        let notched = path_combine(
736            PathOperation::Difference,
737            &Path::new(host.build()),
738            &Path::new(guest.build()),
739        );
740        assert_eq!(notched.fill_type, PathFillType::EvenOdd);
741        let contains = |x: f64, y: f64| notched.contains(Offset::new(x, y));
742        assert!(contains(25.0, 25.0));
743        assert!(!contains(75.0, 25.0), "the guest is cut out");
744        assert!(contains(75.0, 75.0));
745        assert!(!contains(125.0, 25.0), "nothing of the guest is added");
746    }
747
748    #[test]
749    fn a_combined_path_leaves_the_hole_of_a_guest_wholly_inside() {
750        let mut host = PathBuilder::new();
751        host.rect(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0).into());
752        let mut guest = PathBuilder::new();
753        guest.rect(Rect::from_ltwh(25.0, 25.0, 50.0, 50.0).into());
754        let holed = path_combine(
755            PathOperation::Difference,
756            &Path::new(host.build()),
757            &Path::new(guest.build()),
758        );
759        assert!(holed.contains(Offset::new(10.0, 10.0)));
760        assert!(
761            !holed.contains(Offset::new(50.0, 50.0)),
762            "the guest is a hole"
763        );
764    }
765
766    #[test]
767    fn combining_reads_each_path_with_its_own_fill_type() {
768        let mut ring = PathBuilder::new();
769        ring.rect(Rect::from_ltwh(0.0, 0.0, 100.0, 100.0).into());
770        ring.rect(Rect::from_ltwh(25.0, 25.0, 50.0, 50.0).into());
771        let mut even_odd = Path::new(ring.build());
772        even_odd.fill_type = PathFillType::EvenOdd;
773        let non_zero = Path::new(Arc::clone(even_odd.as_valo()));
774        let mut point = PathBuilder::new();
775        point.rect(Rect::from_ltwh(40.0, 40.0, 20.0, 20.0).into());
776        let point = Path::new(point.build());
777
778        let through_the_hole = path_combine(PathOperation::Intersect, &even_odd, &point);
779        assert!(!through_the_hole.contains(Offset::new(50.0, 50.0)));
780        let over_the_fill = path_combine(PathOperation::Intersect, &non_zero, &point);
781        assert!(over_the_fill.contains(Offset::new(50.0, 50.0)));
782    }
783
784    #[test]
785    fn a_path_keeps_its_fill_type_through_a_shift_and_a_transform() {
786        let mut builder = PathBuilder::new();
787        builder.rect(Rect::from_ltwh(0.0, 0.0, 10.0, 10.0).into());
788        let mut path = Path::new(builder.build());
789        assert_eq!(path.fill_type, PathFillType::NonZero);
790        path.fill_type = PathFillType::EvenOdd;
791        let shifted = path.shift(Offset::new(5.0, 0.0));
792        assert_eq!(shifted.fill_type, PathFillType::EvenOdd);
793        assert!(shifted.contains(Offset::new(12.0, 5.0)));
794        assert!(!shifted.contains(Offset::new(2.0, 5.0)));
795        let scaled = path.transform(&Matrix4::scale(2.0, 2.0));
796        assert_eq!(scaled.fill_type, PathFillType::EvenOdd);
797        assert!(scaled.contains(Offset::new(15.0, 15.0)));
798    }
799
800    #[test]
801    fn a_blur_reports_its_bounds_and_a_composition_reads_inner_then_outer() {
802        let blur = ImageFilter::blur(2.0, 3.0).bounds(Rect::from_ltwh(0.0, 0.0, 4.0, 5.0));
803        assert_eq!(
804            blur.debug_short_description(),
805            "blur(2, 3, unspecified, bounds: Rect.fromLTRB(0.0, 0.0, 4.0, 5.0))"
806        );
807
808        let tint = ImageFilter::Color(ColorFilter::mode(
809            Color::new(0xFF000000),
810            BlendMode::SrcOver,
811        ));
812        let composed = ImageFilter::compose(tint, ImageFilter::blur(2.0, 3.0));
813        assert_eq!(
814            composed.to_string(),
815            "ImageFilter.compose(source -> blur(2, 3, unspecified) -> \
816             ColorFilter.mode(Color(alpha: 1.0000, red: 0.0000, green: 0.0000, blue: 0.0000, \
817             colorSpace: ColorSpace.sRGB), SrcOver) -> result)"
818        );
819    }
820
821    #[test]
822    fn a_colour_matrix_reaches_valo_with_its_translation_in_the_channels_range() {
823        let mut matrix = [0.0; 20];
824        matrix[0] = 2.0;
825        matrix[4] = 51.0;
826        matrix[18] = 1.0;
827        matrix[19] = 255.0;
828        let valo::ColorFilter::Matrix(replayed) = ColorFilter::matrix(matrix).to_valo() else {
829            panic!("a matrix reaches valo as a matrix");
830        };
831        assert_eq!(
832            [replayed[0], replayed[4], replayed[18], replayed[19]],
833            [2.0, 0.2, 1.0, 1.0]
834        );
835    }
836
837    #[test]
838    fn a_mode_filter_reaches_valo_as_a_blend_and_a_gamma_curve_as_the_same_curve() {
839        let green = Color::new(0x8C00FF00);
840        assert_eq!(
841            ColorFilter::mode(green, BlendMode::Darken).to_valo(),
842            valo::ColorFilter::Blend(green.into(), BlendMode::Darken)
843        );
844        assert_eq!(
845            ColorFilter::linear_to_srgb_gamma().to_valo(),
846            valo::ColorFilter::LinearToSrgbGamma
847        );
848        assert_eq!(
849            ColorFilter::srgb_to_linear_gamma().to_valo(),
850            valo::ColorFilter::SrgbToLinearGamma
851        );
852    }
853
854    #[test]
855    fn a_composition_reaches_valo_in_its_order_with_both_sigmas_and_the_bounds() {
856        let tint = ColorFilter::mode(Color::new(0xFF0000FF), BlendMode::Multiply);
857        let bounds = Rect::from_ltwh(0.0, 0.0, 4.0, 4.0);
858        let filter = ImageFilter::compose(
859            ImageFilter::Color(tint),
860            ImageFilter::blur(2.0, 5.0).bounds(bounds),
861        );
862        assert_eq!(
863            filter.to_valo(),
864            valo::ImageFilter::compose(
865                valo::ImageFilter::Color(valo::ColorFilter::Blend(
866                    Color::new(0xFF0000FF).into(),
867                    BlendMode::Multiply
868                )),
869                valo::ImageFilter::bounded_blur(2.0, 5.0, bounds.into()),
870            )
871        );
872    }
873
874    #[test]
875    fn a_gamma_curve_reaches_valo_in_its_place_in_a_composition() {
876        let filter = ImageFilter::compose(
877            ImageFilter::Color(ColorFilter::linear_to_srgb_gamma()),
878            ImageFilter::blur(3.0, 3.0),
879        );
880        assert_eq!(
881            filter.to_valo(),
882            valo::ImageFilter::compose(
883                valo::ImageFilter::Color(valo::ColorFilter::LinearToSrgbGamma),
884                valo::ImageFilter::blur(3.0, 3.0),
885            )
886        );
887    }
888}