Skip to main content

waft_widgets/widgets/
image_filter.rs

1//! Flutter counterpart: `widgets/image_filter.dart`.
2
3use std::fmt::{self, Debug};
4
5use waft_embedder::{ImageFilter, Matrix4, Offset, Size, TextBaseline};
6use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty};
7use waft_rendering::{
8    AnyOffsetLayer, AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult,
9    ImageFilterLayer, OffsetLayerMixin, PaintingContext, RenderBox, RenderBoxData, RenderHandle,
10    RenderObject, RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
11    RenderProxyBoxMixin,
12};
13
14use crate::framework::{
15    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, WidgetRef,
16};
17
18/// Applies an [`ImageFilter`] to its child.
19///
20/// An image filter will always apply its filter operation to the child widget, even if said
21/// filter is conceptually a "no-op", such as an [`ImageFilter::blur`] with a radius of 0 or an
22/// `ImageFilter.matrix` with an identity matrix. Setting [`enabled`](Self::enabled) to `false`
23/// is a more efficient manner of disabling an image filter.
24///
25/// The framework does not attempt to optimize out "no-op" filters because it cannot tell the
26/// difference between an intentional no-op and a filter that is only incidentally a no-op.
27/// Consider an `ImageFilter.matrix` that is animated and happens to pass through the identity
28/// matrix. If the framework identified it as a no-op it would drop and then recreate the layer
29/// during the animation which would be more expensive than keeping it around.
30///
31/// See also:
32///
33///  * [`BackdropFilter`](crate::BackdropFilter), which applies an [`ImageFilter`] to everything
34///    beneath its child.
35///  * [`ImageFilter::shader`], which runs a fragment program over the child.
36pub struct ImageFiltered {
37    pub key: Option<KeyRef>,
38    /// The image filter to apply to the child of this widget.
39    pub image_filter: ImageFilter,
40    /// Whether or not to apply the image filter operation to the child of this widget.
41    ///
42    /// Prefer setting enabled to `false` instead of creating a "no-op" filter type for
43    /// performance reasons.
44    pub enabled: bool,
45    /// The widget below this widget in the tree.
46    pub child: Option<WidgetRef>,
47}
48
49impl ImageFiltered {
50    /// Creates a widget that applies an [`ImageFilter`] to its child; Dart's named arguments are
51    /// the setters.
52    pub fn new(image_filter: ImageFilter) -> ImageFiltered {
53        ImageFiltered {
54            key: None,
55            image_filter,
56            enabled: true,
57            child: None,
58        }
59    }
60
61    /// Dart `ImageFiltered(key:)`.
62    pub fn key(mut self, key: KeyRef) -> ImageFiltered {
63        self.key = Some(key);
64        self
65    }
66
67    /// Dart `ImageFiltered(enabled:)`.
68    pub fn enabled(mut self, enabled: bool) -> ImageFiltered {
69        self.enabled = enabled;
70        self
71    }
72
73    /// Dart `ImageFiltered(child:)`.
74    #[cfg_attr(debug_assertions, track_caller)]
75    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ImageFiltered {
76        self.child = Some(child.into_widget());
77        self
78    }
79}
80
81impl RenderObjectWidget for ImageFiltered {
82    type RenderObject = ImageFilterRenderObject;
83
84    fn key(&self) -> Option<&KeyRef> {
85        self.key.as_ref()
86    }
87
88    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
89        properties.add(DiagnosticsProperty::new(
90            "imageFilter",
91            self.image_filter.clone(),
92        ));
93    }
94
95    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
96        ImageFilterRenderObject::new(app, self.image_filter.clone(), self.enabled).as_object()
97    }
98
99    fn update_render_object(
100        &self,
101        app: &mut App,
102        _context: BuildContext,
103        render_object: RenderHandle<ImageFilterRenderObject>,
104    ) {
105        render_object.set_enabled(app, self.enabled);
106        render_object.set_image_filter(app, self.image_filter.clone());
107    }
108}
109
110impl SingleChildRenderObjectWidget for ImageFiltered {
111    fn child(&self) -> Option<&WidgetRef> {
112        self.child.as_ref()
113    }
114}
115
116impl Debug for ImageFiltered {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_struct("ImageFiltered")
119            .field("key", &self.key)
120            .field("image_filter", &self.image_filter)
121            .field("enabled", &self.enabled)
122            .finish_non_exhaustive()
123    }
124}
125
126/// The render object of [`ImageFiltered`]: a repaint boundary, while it has a child and is
127/// enabled, whose layer is an [`ImageFilterLayer`] of its filter.
128///
129/// Dart's `_ImageFilterRenderObject`.
130pub struct ImageFilterRenderObject {
131    render_object: RenderObjectData,
132    render_box: RenderBoxData,
133    child: RenderObjectWithChildData<AnyRenderBox>,
134    enabled: bool,
135    image_filter: ImageFilter,
136}
137
138impl ImageFilterRenderObject {
139    fn new(app: &mut App, image_filter: ImageFilter, enabled: bool) -> RenderHandle<Self> {
140        RenderHandle::new_box(
141            app,
142            ImageFilterRenderObject {
143                render_object: RenderObjectData::new(),
144                render_box: RenderBoxData::new(),
145                child: RenderObjectWithChildData::new(),
146                enabled,
147                image_filter,
148            },
149        )
150    }
151
152    /// Whether the filter is applied.
153    pub fn enabled(self: RenderHandle<Self>, app: &App) -> bool {
154        self.get(app).enabled
155    }
156
157    /// Sets [`enabled`](Self::enabled).
158    pub fn set_enabled(self: RenderHandle<Self>, app: &mut App, value: bool) {
159        if self.enabled(app) == value {
160            return;
161        }
162        let was_repaint_boundary = self.as_object().is_repaint_boundary(app);
163        self.get_mut(app).enabled = value;
164        if self.as_object().is_repaint_boundary(app) != was_repaint_boundary {
165            self.as_object().mark_needs_compositing_bits_update(app);
166        }
167        self.as_object().mark_needs_paint(app);
168    }
169
170    /// The filter applied to the child.
171    pub fn image_filter(self: RenderHandle<Self>, app: &App) -> &ImageFilter {
172        &self.get(app).image_filter
173    }
174
175    /// Sets [`image_filter`](Self::image_filter).
176    pub fn set_image_filter(self: RenderHandle<Self>, app: &mut App, value: ImageFilter) {
177        if value != self.get(app).image_filter {
178            self.get_mut(app).image_filter = value;
179            self.as_object().mark_needs_composited_layer_update(app);
180        }
181    }
182}
183
184impl RenderObjectWithChildMixin for ImageFilterRenderObject {
185    type ChildType = AnyRenderBox;
186
187    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
188        &self.get(app).child
189    }
190
191    fn child_data_mut(
192        self: RenderHandle<Self>,
193        app: &mut App,
194    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
195        &mut self.get_mut(app).child
196    }
197}
198
199impl RenderProxyBoxMixin for ImageFilterRenderObject {}
200
201impl RenderObject for ImageFilterRenderObject {
202    waft_rendering::render_object_accessors!();
203
204    fn always_needs_compositing(self: RenderHandle<Self>, app: &App) -> bool {
205        self.child(app).is_some() && self.enabled(app)
206    }
207
208    fn is_repaint_boundary(self: RenderHandle<Self>, app: &App) -> bool {
209        self.always_needs_compositing(app)
210    }
211
212    fn update_composited_layer(
213        self: RenderHandle<Self>,
214        app: &mut App,
215        old_layer: Option<AnyOffsetLayer>,
216    ) -> AnyOffsetLayer {
217        let layer = match old_layer {
218            Some(old) => app
219                .handle::<ImageFilterLayer>(old.id())
220                .expect("ImageFiltered reuses an ImageFilterLayer"),
221            None => ImageFilterLayer::new(app),
222        };
223        let image_filter = self.image_filter(app).clone();
224        layer.set_image_filter(app, image_filter);
225        layer.as_offset_layer()
226    }
227
228    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
229        RenderProxyBoxMixin::perform_layout(self, app);
230    }
231
232    fn paint(
233        self: RenderHandle<Self>,
234        app: &mut App,
235        context: &mut PaintingContext,
236        offset: Offset,
237    ) {
238        RenderProxyBoxMixin::paint(self, app, context, offset);
239    }
240
241    fn visit_children(
242        self: RenderHandle<Self>,
243        app: &App,
244        visitor: &mut dyn FnMut(AnyRenderObject),
245    ) {
246        if let Some(child) = self.child(app) {
247            visitor(child.as_object());
248        }
249    }
250}
251
252impl RenderBox for ImageFilterRenderObject {
253    waft_rendering::render_box_accessors!();
254
255    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
256        RenderProxyBoxMixin::setup_parent_data(self, app, child);
257    }
258
259    fn apply_paint_transform(
260        self: RenderHandle<Self>,
261        app: &App,
262        child: AnyRenderObject,
263        transform: &mut Matrix4,
264    ) {
265        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
266    }
267
268    fn hit_test_children(
269        self: RenderHandle<Self>,
270        app: &mut App,
271        result: &mut BoxHitTestResult<'_>,
272        position: Offset,
273    ) -> bool {
274        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
275    }
276
277    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
278        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
279    }
280
281    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
282        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
283    }
284
285    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
286        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
287    }
288
289    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
290        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
291    }
292
293    fn compute_distance_to_actual_baseline(
294        self: RenderHandle<Self>,
295        app: &mut App,
296        baseline: TextBaseline,
297    ) -> Option<f64> {
298        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
299    }
300
301    fn compute_dry_baseline(
302        self: RenderHandle<Self>,
303        app: &mut App,
304        constraints: BoxConstraints,
305        baseline: TextBaseline,
306    ) -> Option<f64> {
307        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
308    }
309
310    fn compute_dry_layout(
311        self: RenderHandle<Self>,
312        app: &mut App,
313        constraints: BoxConstraints,
314    ) -> Size {
315        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    //! Ported from `test/widgets/image_filter_test.dart`; its golden cases wait on golden tests.
322
323    use waft_embedder::{FilterQuality, FragmentProgram};
324    use waft_foundation::{AppCell, Handle};
325    use waft_rendering::{AnyContainerLayer, ErasedLayer};
326
327    use super::*;
328    use crate::test_harness::Harness;
329    use crate::widgets::basic::{RepaintBoundary, SizedBox};
330
331    fn filtered(image_filter: ImageFilter, enabled: bool) -> WidgetRef {
332        RepaintBoundary::new()
333            .child(
334                ImageFiltered::new(image_filter)
335                    .enabled(enabled)
336                    .child(SizedBox::new().width(10.0).height(10.0)),
337            )
338            .into_widget()
339    }
340
341    /// The `ImageFiltered` under the root's repaint boundary.
342    fn render_object(harness: &Harness, app: &App) -> RenderHandle<ImageFilterRenderObject> {
343        harness
344            .render_root(app)
345            .child(app)
346            .expect("the repaint boundary")
347            .as_object()
348            .downcast::<waft_rendering::RenderRepaintBoundary>(app)
349            .expect("the repaint boundary")
350            .child(app)
351            .expect("the image filter")
352            .as_object()
353            .downcast::<ImageFilterRenderObject>(app)
354            .expect("the image filter")
355    }
356
357    fn image_filter_layer(layer: AnyContainerLayer, app: &App) -> Handle<ImageFilterLayer> {
358        app.handle::<ImageFilterLayer>(layer.as_layer().id())
359            .expect("an ImageFilterLayer")
360    }
361
362    /// Dart's `Image filter - reuses its layer`.
363    #[test]
364    fn the_layer_is_reused_when_the_filter_changes() {
365        let cell = AppCell::new();
366        let mut app = cell.borrow_mut();
367        let harness = Harness::mount(&mut app, filtered(ImageFilter::blur(5.0, 5.0), true));
368        harness.pump(&mut app);
369        let object = render_object(&harness, &app).as_object();
370        let original = object.debug_layer(&app).expect("a layer");
371
372        harness.set_child(&mut app, filtered(ImageFilter::blur(10.0, 10.0), true));
373        harness.pump(&mut app);
374        let layer = object.debug_layer(&app).expect("a layer");
375        assert_eq!(layer, original);
376        assert_eq!(
377            image_filter_layer(layer, &app).image_filter(&app),
378            Some(&ImageFilter::blur(10.0, 10.0))
379        );
380    }
381
382    /// Dart's `Image filter - enabled and disabled`.
383    #[test]
384    fn a_disabled_filter_makes_no_layer() {
385        let cell = AppCell::new();
386        let mut app = cell.borrow_mut();
387        let harness = Harness::mount(&mut app, filtered(ImageFilter::blur(5.0, 5.0), false));
388        harness.pump(&mut app);
389        let object = render_object(&harness, &app).as_object();
390        assert!(object.debug_layer(&app).is_none());
391
392        harness.set_child(&mut app, filtered(ImageFilter::blur(5.0, 5.0), true));
393        harness.pump(&mut app);
394        let layer = object.debug_layer(&app).expect("a layer once enabled");
395        image_filter_layer(layer, &app);
396    }
397
398    /// Dart's `ImageFiltered does not crash at zero area`.
399    #[test]
400    fn a_filter_of_zero_area_lays_out() {
401        let cell = AppCell::new();
402        let mut app = cell.borrow_mut();
403        let harness = Harness::mount(
404            &mut app,
405            SizedBox::shrink()
406                .child(ImageFiltered::new(ImageFilter::blur(5.0, 5.0)).child(SizedBox::new()))
407                .into_widget(),
408        );
409        harness.pump(&mut app);
410        let image_filtered = harness
411            .render_root(&app)
412            .child(&app)
413            .expect("the sized box")
414            .as_object()
415            .downcast::<waft_rendering::RenderConstrainedBox>(&app)
416            .expect("the sized box")
417            .child(&app)
418            .expect("the image filter");
419        assert_eq!(image_filtered.size(&app), Size::ZERO);
420    }
421
422    /// A fragment program as the filter, as the stretch effect filters its child.
423    #[test]
424    fn a_shader_filter_reaches_the_layer() {
425        let program = FragmentProgram::from_wgsl(
426            "struct U { u_size: vec2<f32> }
427             @group(2) @binding(0) var<uniform> u: U;
428             @group(1) @binding(0) var u_texture: texture_2d<f32>;
429             @group(1) @binding(1) var u_texture_sampler: sampler;
430             fn shade(position: vec2<f32>) -> vec4<f32> {
431                 return textureSampleLevel(u_texture, u_texture_sampler, position / u.u_size, 0.0);
432             }",
433        )
434        .expect("a valid program");
435        let filter = ImageFilter::shader(&program.fragment_shader(), FilterQuality::Low);
436        let cell = AppCell::new();
437        let mut app = cell.borrow_mut();
438        let harness = Harness::mount(&mut app, filtered(filter.clone(), true));
439        harness.pump(&mut app);
440        let layer = render_object(&harness, &app)
441            .as_object()
442            .debug_layer(&app)
443            .expect("a layer");
444        assert_eq!(
445            image_filter_layer(layer, &app).image_filter(&app),
446            Some(&filter)
447        );
448    }
449}