1#![allow(deprecated)]
5
6use std::rc::Rc;
7use std::time::Duration;
8
9use waft_animation::{
10 Animatable, AnimationBehavior, AnimationController, AnimationLocalListenersMixin,
11 AnimationLocalStatusListenersMixin, AnimationRef, AnimationStatus, AnimationStatusListener,
12 CurveTween, Curves, Drive, IntTween, Interval, Tween,
13};
14use waft_embedder::{Canvas, Color, Matrix4, Offset, Paint, 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 RectCallback,
27};
28
29const K_UNCONFIRMED_RIPPLE_DURATION: Duration = Duration::from_secs(1);
30const K_FADE_IN_DURATION: Duration = Duration::from_millis(75);
31const K_RADIUS_DURATION: Duration = Duration::from_millis(225);
32const K_FADE_OUT_DURATION: Duration = Duration::from_millis(375);
33const K_CANCEL_DURATION: Duration = Duration::from_millis(75);
34
35const K_FADE_OUT_INTERVAL_START: f64 = 225.0 / 375.0;
37
38fn get_clip_callback(
39 reference_box: AnyRenderBox,
40 contained_ink_well: bool,
41 rect_callback: Option<RectCallback>,
42) -> Option<RectCallback> {
43 if let Some(rect_callback) = rect_callback {
44 debug_assert!(contained_ink_well);
45 return Some(rect_callback);
46 }
47 if contained_ink_well {
48 return Some(Rc::new(move |app| Offset::ZERO & reference_box.size(app)));
49 }
50 None
51}
52
53fn get_target_radius(
54 app: &App,
55 reference_box: AnyRenderBox,
56 _contained_ink_well: bool,
57 rect_callback: Option<&RectCallback>,
58 _position: Offset,
59) -> f64 {
60 let size = match rect_callback {
61 Some(rect_callback) => rect_callback(app).size(),
62 None => reference_box.size(app),
63 };
64 let d1 = size.bottom_right(Offset::ZERO).distance();
65 let d2 = (size.top_right(Offset::ZERO) - size.bottom_left(Offset::ZERO)).distance();
66 d1.max(d2) / 2.0
67}
68
69#[derive(Debug)]
71struct InkRippleFactory;
72
73impl InteractiveInkFeatureFactory for InkRippleFactory {
74 fn create(
75 &self,
76 app: &mut App,
77 controller: AnyMaterialInkController,
78 reference_box: AnyRenderBox,
79 position: Offset,
80 color: Color,
81 text_direction: TextDirection,
82 contained_ink_well: bool,
83 rect_callback: Option<RectCallback>,
84 border_radius: Option<BorderRadius>,
85 custom_border: Option<ShapeBorderRef>,
86 radius: Option<f64>,
87 on_removed: Option<Listener>,
88 ) -> InteractiveInkFeatureRef {
89 InkRipple::new(
90 app,
91 controller,
92 reference_box,
93 position,
94 color,
95 text_direction,
96 contained_ink_well,
97 rect_callback,
98 border_radius,
99 custom_border,
100 radius,
101 on_removed,
102 )
103 .into_erased()
104 }
105}
106
107pub struct InkRipple {
131 ink_feature: InkFeatureData,
132 interactive_ink_feature: InteractiveInkFeatureData,
133 position: Offset,
134 border_radius: BorderRadius,
135 clip_callback: Option<RectCallback>,
136 text_direction: TextDirection,
137 radius: Option<AnimationRef<f64>>,
138 radius_controller: Option<Ref<AnimationController>>,
139 fade_in: Option<AnimationRef<i64>>,
140 fade_in_controller: Option<Ref<AnimationController>>,
141 fade_out: Option<AnimationRef<i64>>,
142 fade_out_controller: Option<Ref<AnimationController>>,
143}
144
145impl InkRipple {
146 #[allow(clippy::too_many_arguments)]
161 pub fn new(
162 app: &mut App,
163 controller: AnyMaterialInkController,
164 reference_box: AnyRenderBox,
165 position: Offset,
166 color: Color,
167 text_direction: TextDirection,
168 contained_ink_well: bool,
169 rect_callback: Option<RectCallback>,
170 border_radius: Option<BorderRadius>,
171 custom_border: Option<ShapeBorderRef>,
172 radius: Option<f64>,
173 on_removed: Option<Listener>,
174 ) -> Ref<InkRipple> {
175 let target_radius = radius.unwrap_or_else(|| {
176 get_target_radius(
177 app,
178 reference_box,
179 contained_ink_well,
180 rect_callback.as_ref(),
181 position,
182 )
183 });
184 let ink_feature = InkFeatureData::new(app, controller, reference_box, on_removed);
185 let this = app.create(InkRipple {
186 ink_feature,
187 interactive_ink_feature: InteractiveInkFeatureData::new(color, custom_border),
188 position,
189 border_radius: border_radius.unwrap_or(BorderRadius::ZERO),
190 clip_callback: get_clip_callback(reference_box, contained_ink_well, rect_callback),
191 text_direction,
192 radius: None,
193 radius_controller: None,
194 fade_in: None,
195 fade_in_controller: None,
196 fade_out: None,
197 fade_out_controller: None,
198 });
199 let handle = this.handle();
200 let vsync = controller.vsync(app);
201 let create_controller = |app: &mut App, duration: Duration| {
202 AnimationController::new(
203 app,
204 None,
205 Some(duration),
206 None,
207 0.0,
208 1.0,
209 AnimationBehavior::Normal,
210 Rc::clone(&vsync),
211 )
212 };
213
214 let fade_in_controller = create_controller(app, K_FADE_IN_DURATION);
216 fade_in_controller.add_listener(app, controller.mark_needs_paint_listener());
217 fade_in_controller.forward(app, None);
218 let fade_in_tween = IntTween::new(app, Some(0), Some(i64::from(color.alpha())));
219 let fade_in = fade_in_controller.drive(app, fade_in_tween);
220
221 let radius_controller = create_controller(app, K_UNCONFIRMED_RIPPLE_DURATION);
223 radius_controller.add_listener(app, controller.mark_needs_paint_listener());
224 radius_controller.forward(app, None);
225 let radius_tween = Tween::new(app, Some(target_radius * 0.30), Some(target_radius + 5.0));
228 let ease_curve_tween = InkRipple::ease_curve_tween(app);
229 let radius = radius_controller.drive(app, radius_tween.chain(ease_curve_tween));
230
231 let fade_out_controller = create_controller(app, K_FADE_OUT_DURATION);
234 fade_out_controller.add_listener(app, controller.mark_needs_paint_listener());
235 fade_out_controller.add_status_listener(
236 app,
237 AnimationStatusListener::new(move |status, app| {
238 handle.handle_alpha_status_changed(app, status)
239 }),
240 );
241 let fade_out_tween = IntTween::new(app, Some(i64::from(color.alpha())), Some(0));
242 let fade_out_interval_tween = InkRipple::fade_out_interval_tween(app);
243 let fade_out =
244 fade_out_controller.drive(app, fade_out_tween.chain(fade_out_interval_tween));
245
246 let ripple = app.get_mut(handle);
247 ripple.fade_in_controller = Some(fade_in_controller);
248 ripple.fade_in = Some(fade_in);
249 ripple.radius_controller = Some(radius_controller);
250 ripple.radius = Some(radius);
251 ripple.fade_out_controller = Some(fade_out_controller);
252 ripple.fade_out = Some(fade_out);
253
254 controller.add_ink_feature(app, this.erase());
255 this
256 }
257
258 pub fn splash_factory() -> InteractiveInkFeatureFactoryRef {
263 thread_local! {
264 static FACTORY: InteractiveInkFeatureFactoryRef = Rc::new(InkRippleFactory);
265 }
266 FACTORY.with(Rc::clone)
267 }
268
269 fn ease_curve_tween(app: &mut App) -> Ref<CurveTween> {
272 CurveTween::new(app, Curves::ease())
273 }
274
275 fn fade_out_interval_tween(app: &mut App) -> Ref<CurveTween> {
278 CurveTween::new(
279 app,
280 Rc::new(Interval::new(
281 K_FADE_OUT_INTERVAL_START,
282 1.0,
283 Curves::linear(),
284 )),
285 )
286 }
287
288 pub(crate) fn circle(self: Handle<Self>, app: &mut App) -> (i64, Offset, f64) {
291 let ripple = app.get(self);
292 let fade_in_controller = InkRipple::controller(&ripple.fade_in_controller);
293 let alpha = if fade_in_controller.is_animating(app) {
294 app.get(self)
295 .fade_in
296 .as_ref()
297 .expect("created in new")
298 .value(app)
299 } else {
300 app.get(self)
301 .fade_out
302 .as_ref()
303 .expect("created in new")
304 .value(app)
305 };
306 let ripple = app.get(self);
307 let rect = ripple
308 .clip_callback
309 .as_ref()
310 .map(|clip_callback| clip_callback(app));
311 let center = Offset::lerp(
313 Some(ripple.position),
314 Some(match rect {
315 Some(rect) => rect.center(),
316 None => InkFeature::reference_box(self, app)
317 .size(app)
318 .center(Offset::ZERO),
319 }),
320 Curves::ease().transform(InkRipple::controller(&ripple.radius_controller).value(app)),
321 )
322 .expect("both ends are given");
323 let radius = ripple.radius.as_ref().expect("created in new").value(app);
324 (alpha, center, radius)
325 }
326
327 fn controller(field: &Option<Ref<AnimationController>>) -> Handle<AnimationController> {
328 field.handle().expect("created in new")
329 }
330
331 fn handle_alpha_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
332 if status.is_completed() {
333 InkFeatureLeaf::dispose(self, app);
334 }
335 }
336}
337
338impl InkFeatureLeafData for InkRipple {
339 fn ink_feature(&self) -> &InkFeatureData {
340 &self.ink_feature
341 }
342
343 fn ink_feature_mut(&mut self) -> &mut InkFeatureData {
344 &mut self.ink_feature
345 }
346}
347
348impl InteractiveInkFeatureLeafData for InkRipple {
349 fn interactive_ink_feature(&self) -> &InteractiveInkFeatureData {
350 &self.interactive_ink_feature
351 }
352
353 fn interactive_ink_feature_mut(&mut self) -> &mut InteractiveInkFeatureData {
354 &mut self.interactive_ink_feature
355 }
356}
357
358impl InteractiveInkFeatureLeaf for InkRipple {
359 fn confirm(self: Handle<Self>, app: &mut App) {
360 let ripple = app.get(self);
361 let radius_controller = InkRipple::controller(&ripple.radius_controller);
362 let fade_in_controller = InkRipple::controller(&ripple.fade_in_controller);
363 let fade_out_controller = InkRipple::controller(&ripple.fade_out_controller);
364 app.get_mut(radius_controller).duration = Some(K_RADIUS_DURATION);
365 radius_controller.forward(app, None);
366 fade_in_controller.forward(app, None);
368 fade_out_controller.animate_to(app, 1.0, Some(K_FADE_OUT_DURATION), Curves::linear());
369 }
370
371 fn cancel(self: Handle<Self>, app: &mut App) {
372 let ripple = app.get(self);
373 let fade_in_controller = InkRipple::controller(&ripple.fade_in_controller);
374 let fade_out_controller = InkRipple::controller(&ripple.fade_out_controller);
375 fade_in_controller.stop(app, true);
376 let fade_out_value = 1.0 - fade_in_controller.value(app);
380 fade_out_controller.set_value(app, fade_out_value);
381 if fade_out_value < 1.0 {
382 fade_out_controller.animate_to(app, 1.0, Some(K_CANCEL_DURATION), Curves::linear());
383 }
384 }
385}
386
387impl InkFeatureLeaf for InkRipple {
388 fn dispose(self: Handle<Self>, app: &mut App) {
389 let ripple = app.get(self);
390 let controllers = [
391 InkRipple::controller(&ripple.radius_controller),
392 InkRipple::controller(&ripple.fade_in_controller),
393 InkRipple::controller(&ripple.fade_out_controller),
394 ];
395 for controller in controllers {
396 controller.dispose(app);
397 }
398 InkFeature::dispose(self, app);
399 }
400
401 fn paint_feature(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, transform: &Matrix4) {
402 let (alpha, center, radius) = self.circle(app);
403 let ripple = app.get(self);
404 let color = InteractiveInkFeature::color(self, app);
405 let paint = Paint::from_color(color.with_alpha(alpha as i32).into());
406 InteractiveInkFeature::paint_ink_circle(
407 app,
408 canvas,
409 transform,
410 &paint,
411 center,
412 radius,
413 Some(ripple.text_direction),
414 ripple.interactive_ink_feature.custom_border_ref(),
415 ripple.border_radius,
416 ripple.clip_callback.as_ref(),
417 );
418 }
419}
420
421#[cfg(test)]
422mod tests {
423 use std::cell::Cell;
424
425 use waft_embedder::Size;
426 use waft_painting::BoxShape;
427 use waft_widgets::{
428 Actions, ActivateIntent, BuildContext, Builder, Center, Directionality,
429 FocusHighlightStrategy, FocusManager, IntoWidget, SizedBox, WidgetRef,
430 };
431
432 use waft_widgets::testing::{TestPointer, WidgetTester, test_widgets};
433
434 use super::*;
435
436 use crate::ink_well::{InkResponse, InkWell};
437 use crate::material::{Material, RenderInkFeatures};
438 use crate::test_support::{PaintInspection, path_like};
439 use crate::theme::Theme;
440 use crate::theme_data::ThemeData;
441
442 const HIGHLIGHT_COLOR: Color = Color::new(0xAAFF0000);
443 const SPLASH_COLOR: Color = Color::new(0xB40000FF);
444
445 fn ripple_frame(child: Option<WidgetRef>) -> WidgetRef {
447 let mut ink_well = InkWell::new()
448 .border_radius(BorderRadius::all(waft_embedder::Radius::circular(6.0)))
449 .highlight_color(HIGHLIGHT_COLOR)
450 .splash_color(SPLASH_COLOR)
451 .on_tap(Listener::new(|_app| {}))
452 .radius(100.0)
453 .splash_factory(InkRipple::splash_factory());
454 if let Some(child) = child {
455 ink_well = ink_well.child(child);
456 }
457 Directionality::new(
458 TextDirection::Ltr,
459 Material::new()
460 .child(Center::new().child(SizedBox::square(Some(100.0)).child(ink_well))),
461 )
462 .into_widget()
463 }
464
465 const TOP_LEFT: Offset = Offset::new(350.0, 250.0);
466 const INK_WELL_CENTER: Offset = Offset::new(400.0, 300.0);
467
468 fn ripple(tester: &WidgetTester) -> Handle<InkRipple> {
469 let render = tester.first::<RenderInkFeatures>();
470 let app = tester.cell.borrow();
471 render
472 .debug_ink_features(&app)
473 .unwrap_or_default()
474 .into_iter()
475 .find_map(|feature| feature.downcast::<InkRipple>(&app))
476 .expect("a ripple")
477 }
478
479 fn assert_ripple(
481 tester: &WidgetTester,
482 expected_center: Offset,
483 expected_radius: f64,
484 expected_alpha: i64,
485 ) {
486 let (alpha, center, radius) = ripple(tester).circle(&mut tester.cell.borrow_mut());
487 assert!(
488 (center - expected_center).distance() < 1.0
489 && (radius - expected_radius).abs() < 1.0
490 && alpha == expected_alpha,
491 "Expected: center == {expected_center:?}, radius == {expected_radius}, alpha == \
492 {expected_alpha}\nFound: center == {center:?} radius == {radius} alpha == {alpha}"
493 );
494 if alpha > 0 {
495 let drawn = tester.ink_calls();
496 assert!(
497 drawn
498 .iter()
499 .any(|call| path_like(call).is_some_and(|(color, bounds)| {
500 color.value() >> 24 == alpha as u32
501 && (bounds.center() - center).distance() < 1e-3
502 })),
503 "the ripple's circle is drawn: {drawn:?}"
504 );
505 }
506 }
507
508 #[test]
509 fn the_ink_well_widget_renders_an_ink_ripple() {
510 test_widgets(|tester| {
511 tester.pump_widget(ripple_frame(None));
512 let tap_down_offset = TOP_LEFT;
513 tester.tap_at(tap_down_offset, 1);
514 tester.pump(); assert_ripple(tester, Offset::ZERO, 30.0, 0);
519
520 tester.pump_by(Duration::from_millis(50));
524 assert_ripple(tester, Offset::new(17.0, 17.0), 56.0, 120);
525
526 tester.pump_by(Duration::from_millis(25));
529 assert_ripple(tester, Offset::new(29.0, 29.0), 73.0, 180);
530
531 tester.pump_by(Duration::from_millis(150));
536 assert_ripple(tester, INK_WELL_CENTER - tap_down_offset, 105.0, 180);
537
538 tester.pump_by(Duration::from_millis(150));
540 assert_ripple(tester, INK_WELL_CENTER - tap_down_offset, 105.0, 0);
541 });
542 }
543
544 #[test]
546 fn the_ink_well_widget_renders_an_activate_action_induced_ink_ripple() {
547 test_widgets(|tester| {
548 {
549 let mut app = tester.cell.borrow_mut();
550 FocusManager::instance(&mut app)
551 .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
552 }
553 let inner: Rc<Cell<Option<BuildContext>>> = Rc::default();
554 let child = Builder::new({
555 let inner = Rc::clone(&inner);
556 move |_app, context| {
557 inner.set(Some(context));
558 SizedBox::expand().into_widget()
559 }
560 })
561 .into_widget();
562 tester.pump_widget(ripple_frame(Some(child)));
563 tester.pump_and_settle();
564 let inkwell_center = INK_WELL_CENTER - TOP_LEFT;
565
566 let context = inner.get().expect("built");
567 Actions::invoke(&mut tester.cell.borrow_mut(), context, &ActivateIntent);
568 tester.pump();
569
570 assert_ripple(tester, inkwell_center, 30.0, 0);
572
573 tester.pump_by(Duration::from_millis(50));
576 assert_ripple(tester, inkwell_center, 56.0, 120);
577
578 tester.pump_by(Duration::from_millis(25));
581 assert_ripple(tester, inkwell_center, 73.0, 180);
582
583 tester.pump_by(Duration::from_millis(150));
587 assert_ripple(tester, inkwell_center, 105.0, 180);
588
589 tester.pump_by(Duration::from_millis(150));
591 assert_ripple(tester, inkwell_center, 105.0, 0);
592 });
593 }
594
595 #[test]
596 fn cancel_an_ink_ripple_that_was_disposed_when_its_animation_ended() {
597 test_widgets(|tester| {
599 tester.pump_widget(
600 Directionality::new(
601 TextDirection::Ltr,
602 Material::new().child(
603 Center::new().child(
604 SizedBox::square(Some(100.0)).child(
605 InkWell::new()
606 .on_tap(Listener::new(|_app| {}))
607 .radius(100.0)
608 .splash_factory(InkRipple::splash_factory()),
609 ),
610 ),
611 ),
612 )
613 .into_widget(),
614 );
615 tester.tap_at(TOP_LEFT, 1);
616 tester.pump(); tester.pump_by(K_FADE_OUT_DURATION); let mut gesture = TestPointer::touch(2);
620 tester.down(&mut gesture, TOP_LEFT);
621 tester.pump(); tester.move_to(&mut gesture, Offset::ZERO, true);
623 tester.up(&gesture); tester.pump_and_settle();
625 });
626 }
627
628 #[test]
629 fn cancel_an_ink_ripple_before_it_started() {
630 test_widgets(|tester| {
632 tester.pump_widget(ripple_frame(None));
633 tester.tap_at(TOP_LEFT, 1);
634 tester.pump(); let mut gesture = TestPointer::touch(2);
639 tester.down(&mut gesture, TOP_LEFT);
640 tester.pump(); tester.move_to(&mut gesture, Offset::ZERO, true);
642 tester.up(&gesture); let render = tester.first::<RenderInkFeatures>();
645 let app = tester.cell.borrow();
646 let ripples: Vec<Handle<InkRipple>> = render
647 .debug_ink_features(&app)
648 .unwrap_or_default()
649 .into_iter()
650 .filter_map(|feature| feature.downcast::<InkRipple>(&app))
651 .collect();
652 drop(app);
653 for ripple in ripples {
654 let (alpha, _, _) = ripple.circle(&mut tester.cell.borrow_mut());
655 assert_eq!(alpha, 0, "Expected: paint.color.alpha == 0, found: {alpha}");
656 }
657 });
658 }
659
660 #[derive(Debug)]
662 struct TopSquareRippleFactory;
663
664 impl InteractiveInkFeatureFactory for TopSquareRippleFactory {
665 fn create(
666 &self,
667 app: &mut App,
668 controller: AnyMaterialInkController,
669 reference_box: AnyRenderBox,
670 position: Offset,
671 color: Color,
672 text_direction: TextDirection,
673 contained_ink_well: bool,
674 _rect_callback: Option<RectCallback>,
675 border_radius: Option<BorderRadius>,
676 custom_border: Option<ShapeBorderRef>,
677 radius: Option<f64>,
678 on_removed: Option<Listener>,
679 ) -> InteractiveInkFeatureRef {
680 InkRipple::new(
681 app,
682 controller,
683 reference_box,
684 position,
685 color,
686 text_direction,
687 contained_ink_well,
688 Some(Rc::new(|_app| Offset::ZERO & Size::new(100.0, 100.0))),
689 border_radius,
690 custom_border,
691 radius,
692 on_removed,
693 )
694 .into_erased()
695 }
696 }
697
698 #[test]
699 fn material2_custom_rect_callback_renders_an_ink_splash_from_its_center() {
700 test_widgets(|tester| {
701 let splash_color = Color::new(0xff00ff00);
702 let build_widget =
703 |tester: &WidgetTester, splash_factory: Option<InteractiveInkFeatureFactoryRef>| {
704 let mut response = InkResponse::new()
705 .splash_color(splash_color)
706 .contained_ink_well(true)
707 .highlight_shape(BoxShape::Rectangle)
708 .on_tap(Listener::new(|_app| {}));
709 if let Some(splash_factory) = splash_factory {
710 response = response.splash_factory(splash_factory);
711 }
712 let data = ThemeData::builder()
713 .use_material3(false)
714 .build(&tester.cell.borrow());
715 Theme::new(
716 data,
717 Directionality::new(
718 TextDirection::Ltr,
719 Material::new().child(
720 Center::new().child(
721 SizedBox::new().width(100.0).height(200.0).child(response),
722 ),
723 ),
724 ),
725 )
726 .into_widget()
727 };
728 let circle_center = |tester: &WidgetTester| {
729 tester.ink_calls().iter().find_map(|call| {
730 path_like(call)
731 .filter(|(color, _)| color.value() == splash_color.value())
732 .map(|(_, bounds)| bounds.center())
733 })
734 };
735
736 let widget = build_widget(tester, None);
737 tester.pump_widget(widget);
738 let center = WidgetTester::SIZE.center(Offset::ZERO);
739 let mut gesture = TestPointer::touch(1);
740 tester.down(&mut gesture, center);
741 tester.pump(); tester.pump_and_settle(); assert_eq!(circle_center(tester), Some(Offset::new(50.0, 100.0)));
744 tester.up(&gesture);
745
746 let widget = build_widget(tester, Some(Rc::new(TopSquareRippleFactory)));
747 tester.pump_widget(widget);
748 tester.pump_and_settle(); let mut gesture = TestPointer::touch(2);
751 tester.down(&mut gesture, center);
752 tester.pump(); tester.pump_and_settle(); assert_eq!(circle_center(tester), Some(Offset::new(50.0, 50.0)));
755 });
756 }
757}