Skip to main content

waft_material/
ink_splash.rs

1//! Flutter counterpart: material_ui's `ink_splash.dart`.
2//!
3//! Dart's file reads the deprecated `Color.alpha` and its channels, and so does this one.
4#![allow(deprecated)]
5
6use std::rc::Rc;
7use std::time::Duration;
8
9use waft_animation::{
10    AnimationBehavior, AnimationController, AnimationLocalListenersMixin,
11    AnimationLocalStatusListenersMixin, AnimationRef, AnimationStatus, AnimationStatusListener,
12    Drive, IntTween, Tween,
13};
14use waft_embedder::{Canvas, Color, Matrix4, Offset, Paint, Size, TextDirection};
15use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
16use waft_painting::{BorderRadius, ShapeBorderRef};
17use waft_rendering::AnyRenderBox;
18
19use crate::ink_well::{
20    InteractiveInkFeature, InteractiveInkFeatureData, InteractiveInkFeatureFactory,
21    InteractiveInkFeatureFactoryRef, InteractiveInkFeatureLeaf, InteractiveInkFeatureLeafData,
22    InteractiveInkFeatureRef,
23};
24use crate::material::{
25    AnyMaterialInkController, InkFeature, InkFeatureData, InkFeatureLeaf, InkFeatureLeafData,
26    Material, RectCallback,
27};
28
29const K_UNCONFIRMED_SPLASH_DURATION: Duration = Duration::from_secs(1);
30const K_SPLASH_FADE_DURATION: Duration = Duration::from_millis(200);
31
32const K_SPLASH_INITIAL_SIZE: f64 = 0.0; // logical pixels
33const K_SPLASH_CONFIRMED_VELOCITY: f64 = 1.0; // logical pixels per millisecond
34
35fn get_clip_callback(
36    reference_box: AnyRenderBox,
37    contained_ink_well: bool,
38    rect_callback: Option<RectCallback>,
39) -> Option<RectCallback> {
40    if let Some(rect_callback) = rect_callback {
41        debug_assert!(contained_ink_well);
42        return Some(rect_callback);
43    }
44    if contained_ink_well {
45        return Some(Rc::new(move |app| Offset::ZERO & reference_box.size(app)));
46    }
47    None
48}
49
50fn get_target_radius(
51    app: &App,
52    reference_box: AnyRenderBox,
53    contained_ink_well: bool,
54    rect_callback: Option<&RectCallback>,
55    position: Offset,
56) -> f64 {
57    if contained_ink_well {
58        let size = match rect_callback {
59            Some(rect_callback) => rect_callback(app).size(),
60            None => reference_box.size(app),
61        };
62        return get_splash_radius_for_position_in_size(size, position);
63    }
64    Material::DEFAULT_SPLASH_RADIUS
65}
66
67fn get_splash_radius_for_position_in_size(bounds: Size, position: Offset) -> f64 {
68    let d1 = (position - bounds.top_left(Offset::ZERO)).distance();
69    let d2 = (position - bounds.top_right(Offset::ZERO)).distance();
70    let d3 = (position - bounds.bottom_left(Offset::ZERO)).distance();
71    let d4 = (position - bounds.bottom_right(Offset::ZERO)).distance();
72    d1.max(d2).max(d3.max(d4)).ceil()
73}
74
75/// Dart's `_InkSplashFactory`.
76#[derive(Debug)]
77struct InkSplashFactory;
78
79impl InteractiveInkFeatureFactory for InkSplashFactory {
80    fn create(
81        &self,
82        app: &mut App,
83        controller: AnyMaterialInkController,
84        reference_box: AnyRenderBox,
85        position: Offset,
86        color: Color,
87        text_direction: TextDirection,
88        contained_ink_well: bool,
89        rect_callback: Option<RectCallback>,
90        border_radius: Option<BorderRadius>,
91        custom_border: Option<ShapeBorderRef>,
92        radius: Option<f64>,
93        on_removed: Option<Listener>,
94    ) -> InteractiveInkFeatureRef {
95        InkSplash::new(
96            app,
97            controller,
98            reference_box,
99            text_direction,
100            Some(position),
101            color,
102            contained_ink_well,
103            rect_callback,
104            border_radius,
105            custom_border,
106            radius,
107            on_removed,
108        )
109        .into_erased()
110    }
111}
112
113/// A visual reaction on a piece of [`Material`] to user input.
114///
115/// A circular ink feature whose origin starts at the input touch point
116/// and whose radius expands from zero.
117///
118/// This object is rarely created directly. Instead of creating an ink splash
119/// directly, consider using an [`InkResponse`](crate::InkResponse) or
120/// [`InkWell`](crate::InkWell) widget, which uses gestures (such as tap and long-press) to
121/// trigger ink splashes.
122///
123/// See also:
124///
125///  * [`InkRipple`](crate::InkRipple), which is an ink splash feature that expands more
126///    aggressively than this class does.
127///  * [`InkResponse`](crate::InkResponse), which uses gestures to trigger ink highlights and
128///    ink splashes in the parent [`Material`].
129///  * [`InkWell`](crate::InkWell), which is a rectangular [`InkResponse`](crate::InkResponse)
130///    (the most common type of ink response).
131///  * [`Material`], which is the widget on which the ink splash is painted.
132///  * [`InkHighlight`](crate::InkHighlight), which is an ink feature that emphasizes a part of
133///    a [`Material`].
134///  * [`Ink`](crate::Ink), a convenience widget for drawing images and other decorations on
135///    Material widgets.
136pub struct InkSplash {
137    ink_feature: InkFeatureData,
138    interactive_ink_feature: InteractiveInkFeatureData,
139    position: Option<Offset>,
140    border_radius: BorderRadius,
141    target_radius: f64,
142    clip_callback: Option<RectCallback>,
143    reposition_to_reference_box: bool,
144    text_direction: TextDirection,
145    radius: Option<AnimationRef<f64>>,
146    radius_controller: Option<Ref<AnimationController>>,
147    alpha: Option<AnimationRef<i64>>,
148    alpha_controller: Option<Ref<AnimationController>>,
149}
150
151impl InkSplash {
152    /// Begin a splash, centered at position relative to `reference_box`.
153    ///
154    /// The `controller` argument is typically obtained via `Material::of(app, context)`.
155    ///
156    /// If `contained_ink_well` is true, then the splash will be sized to fit
157    /// the well rectangle, then clipped to it when drawn. The well
158    /// rectangle is the box returned by `rect_callback`, if provided, or
159    /// otherwise is the bounds of the `reference_box`.
160    ///
161    /// If `contained_ink_well` is false, then `rect_callback` should be null.
162    /// The ink splash is clipped only to the edges of the [`Material`].
163    /// This is the default.
164    ///
165    /// When the splash is removed, `on_removed` will be called.
166    #[allow(clippy::too_many_arguments)]
167    pub fn new(
168        app: &mut App,
169        controller: AnyMaterialInkController,
170        reference_box: AnyRenderBox,
171        text_direction: TextDirection,
172        position: Option<Offset>,
173        color: Color,
174        contained_ink_well: bool,
175        rect_callback: Option<RectCallback>,
176        border_radius: Option<BorderRadius>,
177        custom_border: Option<ShapeBorderRef>,
178        radius: Option<f64>,
179        on_removed: Option<Listener>,
180    ) -> Ref<InkSplash> {
181        let target_radius = radius.unwrap_or_else(|| {
182            get_target_radius(
183                app,
184                reference_box,
185                contained_ink_well,
186                rect_callback.as_ref(),
187                position.expect("a splash without a radius has a position"),
188            )
189        });
190        let ink_feature = InkFeatureData::new(app, controller, reference_box, on_removed);
191        let this = app.create(InkSplash {
192            ink_feature,
193            interactive_ink_feature: InteractiveInkFeatureData::new(color, custom_border),
194            position,
195            border_radius: border_radius.unwrap_or(BorderRadius::ZERO),
196            target_radius,
197            clip_callback: get_clip_callback(reference_box, contained_ink_well, rect_callback),
198            reposition_to_reference_box: !contained_ink_well,
199            text_direction,
200            radius: None,
201            radius_controller: None,
202            alpha: None,
203            alpha_controller: None,
204        });
205        let handle = this.handle();
206        let vsync = controller.vsync(app);
207        let radius_controller = AnimationController::new(
208            app,
209            None,
210            Some(K_UNCONFIRMED_SPLASH_DURATION),
211            None,
212            0.0,
213            1.0,
214            AnimationBehavior::Normal,
215            Rc::clone(&vsync),
216        );
217        radius_controller.add_listener(app, controller.mark_needs_paint_listener());
218        radius_controller.forward(app, None);
219        let radius_tween = Tween::new(app, Some(K_SPLASH_INITIAL_SIZE), Some(target_radius));
220        let radius = radius_controller.drive(app, radius_tween);
221        let alpha_controller = AnimationController::new(
222            app,
223            None,
224            Some(K_SPLASH_FADE_DURATION),
225            None,
226            0.0,
227            1.0,
228            AnimationBehavior::Normal,
229            vsync,
230        );
231        alpha_controller.add_listener(app, controller.mark_needs_paint_listener());
232        alpha_controller.add_status_listener(
233            app,
234            AnimationStatusListener::new(move |status, app| {
235                handle.handle_alpha_status_changed(app, status)
236            }),
237        );
238        let alpha_tween = IntTween::new(app, Some(i64::from(color.alpha())), Some(0));
239        let alpha = alpha_controller.drive(app, alpha_tween);
240        let splash = app.get_mut(handle);
241        splash.radius_controller = Some(radius_controller);
242        splash.radius = Some(radius);
243        splash.alpha_controller = Some(alpha_controller);
244        splash.alpha = Some(alpha);
245
246        controller.add_ink_feature(app, this.erase());
247        this
248    }
249
250    /// Used to specify this type of ink splash for an [`InkWell`](crate::InkWell),
251    /// [`InkResponse`](crate::InkResponse), material `Theme`, or `ButtonStyle`.
252    ///
253    /// Dart's `static const`: every call hands out the same factory, so they compare equal.
254    pub fn splash_factory() -> InteractiveInkFeatureFactoryRef {
255        thread_local! {
256            static FACTORY: InteractiveInkFeatureFactoryRef = Rc::new(InkSplashFactory);
257        }
258        FACTORY.with(Rc::clone)
259    }
260
261    fn radius_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
262        app.get(self)
263            .radius_controller
264            .handle()
265            .expect("created in new")
266    }
267
268    fn handle_alpha_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
269        if status.is_completed() {
270            InkFeatureLeaf::dispose(self, app);
271        }
272    }
273}
274
275impl InkFeatureLeafData for InkSplash {
276    fn ink_feature(&self) -> &InkFeatureData {
277        &self.ink_feature
278    }
279
280    fn ink_feature_mut(&mut self) -> &mut InkFeatureData {
281        &mut self.ink_feature
282    }
283}
284
285impl InteractiveInkFeatureLeafData for InkSplash {
286    fn interactive_ink_feature(&self) -> &InteractiveInkFeatureData {
287        &self.interactive_ink_feature
288    }
289
290    fn interactive_ink_feature_mut(&mut self) -> &mut InteractiveInkFeatureData {
291        &mut self.interactive_ink_feature
292    }
293}
294
295impl InteractiveInkFeatureLeaf for InkSplash {
296    fn confirm(self: Handle<Self>, app: &mut App) {
297        let duration = (app.get(self).target_radius / K_SPLASH_CONFIRMED_VELOCITY).floor() as u64;
298        let radius_controller = self.radius_controller(app);
299        app.get_mut(radius_controller).duration = Some(Duration::from_millis(duration));
300        radius_controller.forward(app, None);
301        app.get(self)
302            .alpha_controller
303            .as_ref()
304            .expect("not disposed")
305            .forward(app, None);
306    }
307
308    fn cancel(self: Handle<Self>, app: &mut App) {
309        if let Some(alpha_controller) = app.get(self).alpha_controller.handle() {
310            alpha_controller.forward(app, None);
311        }
312    }
313}
314
315impl InkFeatureLeaf for InkSplash {
316    fn dispose(self: Handle<Self>, app: &mut App) {
317        let radius_controller = self.radius_controller(app);
318        radius_controller.dispose(app);
319        let alpha_controller = app
320            .get_mut(self)
321            .alpha_controller
322            .take()
323            .expect("disposed once");
324        alpha_controller.dispose(app);
325        InkFeature::dispose(self, app);
326    }
327
328    fn paint_feature(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, transform: &Matrix4) {
329        let splash = app.get(self);
330        let alpha = splash.alpha.as_ref().expect("created in new").value(app);
331        let radius = splash.radius.as_ref().expect("created in new").value(app);
332        let color = InteractiveInkFeature::color(self, app);
333        let paint = Paint::from_color(color.with_alpha(alpha as i32).into());
334        let mut center = splash.position;
335        if splash.reposition_to_reference_box {
336            let reference_box = InkFeature::reference_box(self, app);
337            center = Offset::lerp(
338                center,
339                Some(reference_box.size(app).center(Offset::ZERO)),
340                self.radius_controller(app).value(app),
341            );
342        }
343        InteractiveInkFeature::paint_ink_circle(
344            app,
345            canvas,
346            transform,
347            &paint,
348            center.expect("a splash has a center"),
349            radius,
350            Some(splash.text_direction),
351            splash.interactive_ink_feature.custom_border_ref(),
352            splash.border_radius,
353            splash.clip_callback.as_ref(),
354        );
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use waft_foundation::K_IS_WEB;
361    use waft_widgets::testing::{TestPointer, WidgetTester, test_widgets};
362    use waft_widgets::{Center, Directionality, IntoWidget, SizedBox, WidgetRef};
363
364    use super::*;
365    use crate::ink_well::InkWell;
366    use crate::no_splash::NoSplash;
367    use crate::test_support::{PaintInspection, path_like};
368    use crate::theme::Theme;
369    use crate::theme_data::ThemeData;
370    use waft_rendering::testing::RecordedCall;
371
372    fn with_theme(tester: &WidgetTester, use_material3: bool, child: WidgetRef) -> WidgetRef {
373        let data = ThemeData::builder()
374            .use_material3(use_material3)
375            .build(&tester.cell.borrow());
376        Theme::new(data, Directionality::new(TextDirection::Ltr, child)).into_widget()
377    }
378
379    #[test]
380    fn material2_ink_well_widget_renders_an_ink_splash() {
381        test_widgets(|tester| {
382            let splash_color = Color::new(0xAA0000FF);
383            let border_radius = BorderRadius::all(waft_embedder::Radius::circular(6.0));
384            let widget = with_theme(
385                tester,
386                false,
387                Material::new()
388                    .child(
389                        Center::new().child(
390                            SizedBox::new().width(200.0).height(60.0).child(
391                                InkWell::new()
392                                    .border_radius(border_radius)
393                                    .splash_color(splash_color)
394                                    .on_tap(Listener::new(|_app| {})),
395                            ),
396                        ),
397                    )
398                    .into_widget(),
399            );
400            tester.pump_widget(widget);
401
402            let mut gesture = TestPointer::touch(1);
403            tester.down(&mut gesture, WidgetTester::SIZE.center(Offset::ZERO));
404            tester.pump(); // start gesture
405            tester.pump_by(Duration::from_millis(200)); // wait for splash to be well under way
406
407            let drawn = tester.ink_calls();
408            let circle = drawn
409                .iter()
410                .find_map(|call| {
411                    path_like(call)
412                        .filter(|(color, _)| color.value() == splash_color.value())
413                        .map(|(_, bounds)| bounds)
414                })
415                .unwrap_or_else(|| panic!("a splash circle in {drawn:?}"));
416            assert_eq!(circle.center(), Offset::new(100.0, 30.0));
417            waft_widgets::testing::assert_more_or_less_equals_within(
418                circle.width() / 2.0,
419                21.0,
420                1e-3,
421            );
422            let all: Vec<RecordedCall> = tester
423                .ink_list()
424                .ops()
425                .iter()
426                .map(RecordedCall::of)
427                .collect();
428            assert!(
429                all.contains(&RecordedCall::Clip),
430                "the rounded clip: {all:?}"
431            );
432
433            tester.up(&gesture);
434        });
435    }
436
437    /// Dart's `InkWell with NoSplash splashFactory paints nothing`, Material 2 and 3. Valo
438    /// records no draw of a circle of radius 0 or a transparent highlight, which are what
439    /// the frame after the press holds, so one more frame runs before each count.
440    fn press_and_count(
441        tester: &mut WidgetTester,
442        use_material3: bool,
443        splash_factory: Option<InteractiveInkFeatureFactoryRef>,
444    ) -> (usize, usize) {
445        let mut ink_well = InkWell::new()
446            .on_tap(Listener::new(|_app| {}))
447            .child(SizedBox::new().width(40.0).height(20.0));
448        if let Some(splash_factory) = splash_factory {
449            ink_well = ink_well.splash_factory(splash_factory);
450        }
451        let widget = with_theme(
452            tester,
453            use_material3,
454            Center::new()
455                .child(Material::new().child(ink_well))
456                .into_widget(),
457        );
458        tester.pump_widget(widget);
459        let mut gesture = TestPointer::touch(1);
460        tester.down(&mut gesture, WidgetTester::SIZE.center(Offset::ZERO));
461        tester.pump_by(Duration::from_millis(200));
462        tester.pump_by(Duration::from_millis(16));
463        let drawn = tester.ink_calls();
464        let rects = drawn
465            .iter()
466            .filter(|drawn| matches!(drawn, RecordedCall::Rect { .. }))
467            .count();
468        let circles = drawn
469            .iter()
470            .filter(|drawn| path_like(drawn).is_some())
471            .count();
472        tester.up(&gesture);
473        tester.pump_and_settle();
474        (rects, circles)
475    }
476
477    #[test]
478    fn material2_ink_well_with_no_splash_splash_factory_paints_nothing() {
479        test_widgets(|tester| {
480            // NoSplash.splashFactory, no splash circles drawn
481            let (_, circles) = press_and_count(tester, false, Some(NoSplash::splash_factory()));
482            assert_eq!(circles, 0);
483
484            // Default splashFactory (from Theme.of().splashFactory), one splash circle drawn.
485            let (_, circles) = press_and_count(tester, false, None);
486            assert_eq!(circles, 1);
487        });
488    }
489
490    #[test]
491    fn material3_ink_well_with_no_splash_splash_factory_paints_nothing() {
492        test_widgets(|tester| {
493            // NoSplash.splashFactory, one rect is drawn for the highlight.
494            let (rects, circles) = press_and_count(tester, true, Some(NoSplash::splash_factory()));
495            assert_eq!((rects, circles), (1, 0));
496
497            // Default splashFactory (from Theme.of().splashFactory), two rects are drawn for the
498            // splash and highlight.
499            let (rects, _) = press_and_count(tester, true, None);
500            assert_eq!(rects, if K_IS_WEB { 1 } else { 2 });
501        });
502    }
503}