Skip to main content

waft_material/
ink_highlight.rs

1//! Flutter counterpart: material_ui's `ink_highlight.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::time::Duration;
7
8use waft_animation::{
9    AnimationBehavior, AnimationController, AnimationLocalListenersMixin,
10    AnimationLocalStatusListenersMixin, AnimationRef, AnimationStatus, AnimationStatusListener,
11    Drive, IntTween,
12};
13use waft_embedder::{Canvas, Color, Matrix4, Offset, Paint, Rect, TextDirection};
14use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
15use waft_painting::{BorderRadius, BoxShape, ShapeBorderRef, draw_rrect, get_as_translation};
16use waft_rendering::AnyRenderBox;
17
18use crate::ink_well::{
19    InteractiveInkFeature, InteractiveInkFeatureData, InteractiveInkFeatureLeaf,
20    InteractiveInkFeatureLeafData, rrect_from_rect_and_corners,
21};
22use crate::material::{
23    AnyMaterialInkController, InkFeature, InkFeatureData, InkFeatureLeaf, InkFeatureLeafData,
24    Material, RectCallback,
25};
26
27const K_DEFAULT_HIGHLIGHT_FADE_DURATION: Duration = Duration::from_millis(200);
28
29/// A visual emphasis on a part of a [`Material`] receiving user interaction.
30///
31/// This object is rarely created directly. Instead of creating an ink highlight
32/// directly, consider using an [`InkResponse`](crate::InkResponse) or
33/// [`InkWell`](crate::InkWell) widget, which uses gestures (such as tap and long-press) to
34/// trigger ink highlights.
35///
36/// See also:
37///
38///  * [`InkResponse`](crate::InkResponse), which uses gestures to trigger ink highlights and
39///    ink splashes in the parent [`Material`].
40///  * [`InkWell`](crate::InkWell), which is a rectangular [`InkResponse`](crate::InkResponse)
41///    (the most common type of ink response).
42///  * [`Material`], which is the widget on which the ink highlight is painted.
43///  * [`InkSplash`](crate::InkSplash), which is an ink feature that shows a reaction to user
44///    input on a [`Material`].
45///  * [`Ink`](crate::Ink), a convenience widget for drawing images and other decorations on
46///    Material widgets.
47pub struct InkHighlight {
48    ink_feature: InkFeatureData,
49    interactive_ink_feature: InteractiveInkFeatureData,
50    shape: BoxShape,
51    radius: Option<f64>,
52    border_radius: BorderRadius,
53    rect_callback: Option<RectCallback>,
54    text_direction: TextDirection,
55    alpha: Option<AnimationRef<i64>>,
56    alpha_controller: Option<Ref<AnimationController>>,
57    active: bool,
58}
59
60impl InkHighlight {
61    /// The default fade duration of [`InkHighlight::new`]: Dart's
62    /// `_kDefaultHighlightFadeDuration`.
63    pub const DEFAULT_FADE_DURATION: Duration = K_DEFAULT_HIGHLIGHT_FADE_DURATION;
64
65    /// Begin a highlight animation.
66    ///
67    /// The `controller` argument is typically obtained via
68    /// `Material::of(app, context)`.
69    ///
70    /// If a `rect_callback` is given, then it provides the highlight rectangle,
71    /// otherwise, the highlight rectangle is coincident with the `reference_box`.
72    ///
73    /// When the highlight is removed, `on_removed` will be called.
74    ///
75    /// Dart's defaults: `shape` [`BoxShape::Rectangle`], `border_radius`
76    /// [`BorderRadius::ZERO`], `fade_duration` [`InkHighlight::DEFAULT_FADE_DURATION`].
77    #[allow(clippy::too_many_arguments)]
78    pub fn new(
79        app: &mut App,
80        controller: AnyMaterialInkController,
81        reference_box: AnyRenderBox,
82        color: Color,
83        text_direction: TextDirection,
84        shape: BoxShape,
85        radius: Option<f64>,
86        border_radius: Option<BorderRadius>,
87        custom_border: Option<ShapeBorderRef>,
88        rect_callback: Option<RectCallback>,
89        on_removed: Option<Listener>,
90        fade_duration: Duration,
91    ) -> Ref<InkHighlight> {
92        let ink_feature = InkFeatureData::new(app, controller, reference_box, on_removed);
93        let this = app.create(InkHighlight {
94            ink_feature,
95            interactive_ink_feature: InteractiveInkFeatureData::new(color, custom_border),
96            shape,
97            radius,
98            border_radius: border_radius.unwrap_or(BorderRadius::ZERO),
99            rect_callback,
100            text_direction,
101            alpha: None,
102            alpha_controller: None,
103            active: true,
104        });
105        let handle = this.handle();
106        let vsync = controller.vsync(app);
107        let alpha_controller = AnimationController::new(
108            app,
109            None,
110            Some(fade_duration),
111            None,
112            0.0,
113            1.0,
114            AnimationBehavior::Normal,
115            vsync,
116        );
117        alpha_controller.add_listener(app, controller.mark_needs_paint_listener());
118        alpha_controller.add_status_listener(
119            app,
120            AnimationStatusListener::new(move |status, app| {
121                handle.handle_alpha_status_changed(app, status)
122            }),
123        );
124        alpha_controller.forward(app, None);
125        let alpha_tween = IntTween::new(app, Some(0), Some(i64::from(color.alpha())));
126        let alpha = alpha_controller.drive(app, alpha_tween);
127        let highlight = app.get_mut(handle);
128        highlight.alpha_controller = Some(alpha_controller);
129        highlight.alpha = Some(alpha);
130
131        controller.add_ink_feature(app, this.erase());
132        this
133    }
134
135    fn alpha_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
136        app.get(self)
137            .alpha_controller
138            .handle()
139            .expect("created in new")
140    }
141
142    /// Whether this part of the material is being visually emphasized.
143    pub fn active(self: Handle<Self>, app: &App) -> bool {
144        app.get(self).active
145    }
146
147    /// Start visually emphasizing this part of the material.
148    pub fn activate(self: Handle<Self>, app: &mut App) {
149        app.get_mut(self).active = true;
150        self.alpha_controller(app).forward(app, None);
151    }
152
153    /// Stop visually emphasizing this part of the material.
154    pub fn deactivate(self: Handle<Self>, app: &mut App) {
155        app.get_mut(self).active = false;
156        self.alpha_controller(app).reverse(app, None);
157    }
158
159    /// The color [`paint_feature`](InkFeatureLeaf::paint_feature) paints with now; a
160    /// transparent one draws nothing a test can record.
161    #[cfg(test)]
162    pub(crate) fn debug_paint_color(self: Handle<Self>, app: &App) -> Color {
163        let alpha = app
164            .get(self)
165            .alpha
166            .as_ref()
167            .expect("created in new")
168            .value(app);
169        InteractiveInkFeature::color(self, app).with_alpha(alpha as i32)
170    }
171
172    fn handle_alpha_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
173        if status.is_dismissed() && !app.get(self).active {
174            InkFeatureLeaf::dispose(self, app);
175        }
176    }
177
178    fn paint_highlight(
179        self: Handle<Self>,
180        app: &App,
181        canvas: &mut Canvas,
182        rect: Rect,
183        paint: &Paint,
184    ) {
185        let highlight = app.get(self);
186        canvas.save();
187        if let Some(custom_border) = highlight.interactive_ink_feature().custom_border_ref() {
188            let path = custom_border.get_outer_path(rect, Some(highlight.text_direction));
189            canvas.clip_path(
190                path.as_valo(),
191                path.fill_type,
192                waft_embedder::ClipOp::Intersect,
193                true,
194            );
195        }
196        match highlight.shape {
197            BoxShape::Circle => {
198                canvas.draw_circle(
199                    rect.center(),
200                    highlight.radius.unwrap_or(Material::DEFAULT_SPLASH_RADIUS) as f32,
201                    paint,
202                );
203            }
204            BoxShape::Rectangle => {
205                if highlight.border_radius != BorderRadius::ZERO {
206                    let clip_rrect = rrect_from_rect_and_corners(rect, highlight.border_radius);
207                    draw_rrect(canvas, clip_rrect, paint);
208                } else {
209                    canvas.draw_rect(rect, paint);
210                }
211            }
212        }
213        canvas.restore();
214    }
215}
216
217impl InkFeatureLeafData for InkHighlight {
218    fn ink_feature(&self) -> &InkFeatureData {
219        &self.ink_feature
220    }
221
222    fn ink_feature_mut(&mut self) -> &mut InkFeatureData {
223        &mut self.ink_feature
224    }
225}
226
227impl InteractiveInkFeatureLeafData for InkHighlight {
228    fn interactive_ink_feature(&self) -> &InteractiveInkFeatureData {
229        &self.interactive_ink_feature
230    }
231
232    fn interactive_ink_feature_mut(&mut self) -> &mut InteractiveInkFeatureData {
233        &mut self.interactive_ink_feature
234    }
235}
236
237impl InkFeatureLeaf for InkHighlight {
238    fn dispose(self: Handle<Self>, app: &mut App) {
239        let alpha_controller = self.alpha_controller(app);
240        alpha_controller.dispose(app);
241        InkFeature::dispose(self, app);
242    }
243
244    fn paint_feature(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, transform: &Matrix4) {
245        let alpha = app
246            .get(self)
247            .alpha
248            .as_ref()
249            .expect("created in new")
250            .value(app);
251        let color = InteractiveInkFeature::color(self, app);
252        let paint = Paint::from_color(color.with_alpha(alpha as i32).into());
253        let origin_offset = get_as_translation(*transform);
254        let rect = match &app.get(self).rect_callback {
255            Some(rect_callback) => rect_callback(app),
256            None => Offset::ZERO & InkFeature::reference_box(self, app).size(app),
257        };
258        match origin_offset {
259            None => {
260                canvas.save();
261                canvas.concat(transform);
262                self.paint_highlight(app, canvas, rect, &paint);
263                canvas.restore();
264            }
265            Some(origin_offset) => {
266                self.paint_highlight(app, canvas, rect.shift(origin_offset), &paint);
267            }
268        }
269    }
270}
271
272impl InteractiveInkFeatureLeaf for InkHighlight {}