Skip to main content

waft_material/
ink_decoration.rs

1//! Flutter counterpart: material_ui's `ink_decoration.dart`.
2//!
3//! `Ink.image` waits with `DecorationImage`.
4
5use std::fmt;
6use std::rc::Rc;
7
8use waft_embedder::{Canvas, Color, Matrix4, Offset};
9use waft_foundation::{
10    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listener, OptionRetained, Ref,
11};
12use waft_painting::{
13    BoxDecoration, BoxPainter, DecorationRef, EdgeInsets, EdgeInsetsGeometry, ImageConfiguration,
14    get_as_translation,
15};
16use waft_rendering::{AnyRenderBox, BoxConstraints};
17use waft_widgets::{
18    BuildContext, Builder, ConstrainedBox, GlobalKey, IntoWidget, KeyRef, Padding, SizedBox, State,
19    StateData, StatefulWidget, Visibility, WidgetRef, create_local_image_configuration,
20};
21
22use crate::debug::debug_check_has_material;
23use crate::material::{
24    AnyMaterialInkController, InkFeature, InkFeatureData, InkFeatureLeaf, InkFeatureLeafData,
25    Material,
26};
27
28/// A convenience widget for drawing images and other decorations on [`Material`]
29/// widgets, so that [`InkWell`](crate::InkWell) and [`InkResponse`](crate::InkResponse)
30/// splashes will render over them.
31///
32/// Ink splashes and highlights, as rendered by [`InkWell`](crate::InkWell) and similar
33/// widgets, are actually painted on the underlying [`Material`], which is typically
34/// below the children of the [`Material`] widget. This is problematic if a child of the
35/// [`Material`] has its own decoration, which would cover the ink effects.
36///
37/// The [`Ink`] widget fixes this by painting on the [`Material`] directly, below the ink
38/// effects.
39///
40/// The [`padding`](Self::padding) is applied around the [`child`](Self::child); the
41/// decoration's padding is added to it.
42///
43/// [`Ink`] is not a replacement for a `Container`: it paints a decoration on the
44/// material, not around it, so the [`Material`]'s clip is the decoration's clip.
45///
46/// See also:
47///
48///  * `Container`, a more generic form of this widget which paints itself,
49///    rather that deferring to the nearest [`Material`] widget.
50///  * [`InkDecoration`], the [`InkFeature`] subclass used by this widget to paint
51///    on [`Material`] widgets.
52///  * [`InkWell`](crate::InkWell) and [`InkResponse`](crate::InkResponse), which also draw on
53///    [`Material`] widgets.
54pub struct Ink {
55    pub key: Option<KeyRef>,
56
57    /// The [`child`](Self::child) contained by the container.
58    ///
59    /// If null, this widget's size will expand to fill the box constraints, or, when
60    /// [`width`](Self::width) or [`height`](Self::height) is given, that size.
61    pub child: Option<WidgetRef>,
62
63    /// Empty space to inscribe inside the [`decoration`](Self::decoration). The
64    /// [`child`](Self::child), if any, is placed inside this padding.
65    ///
66    /// This padding is in addition to any padding inherent in the
67    /// [`decoration`](Self::decoration) (see `Decoration::padding`).
68    pub padding: Option<EdgeInsetsGeometry>,
69
70    /// Dart's `color:` argument: a shorthand for "decoration: BoxDecoration(color: color)".
71    pub color: Option<Color>,
72
73    /// The decoration to paint on the nearest ancestor [`Material`] widget.
74    ///
75    /// A shorthand for specifying just a solid color is available in the
76    /// constructor: set the `color` argument instead of the `decoration`
77    /// argument.
78    ///
79    /// A shorthand for specifying just an image is also available using the
80    /// `Ink.image` constructor.
81    pub decoration: Option<DecorationRef>,
82
83    /// A width to apply to the [`decoration`](Self::decoration) and the
84    /// [`child`](Self::child). The width includes any [`padding`](Self::padding).
85    pub width: Option<f64>,
86
87    /// A height to apply to the [`decoration`](Self::decoration) and the
88    /// [`child`](Self::child). The height includes any [`padding`](Self::padding).
89    pub height: Option<f64>,
90}
91
92impl fmt::Debug for Ink {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.debug_struct("Ink")
95            .field("padding", &self.padding)
96            .field("bg", &self.effective_decoration())
97            .finish_non_exhaustive()
98    }
99}
100
101impl Ink {
102    /// Paints a decoration (which can be a simple color) on a [`Material`]; Dart's named
103    /// arguments are the setters.
104    ///
105    /// The [`height`](Self::height) and [`width`](Self::width) values include the
106    /// [`padding`](Self::padding).
107    ///
108    /// The `color` argument is a shorthand for
109    /// `decoration: BoxDecoration::new().color(color)`, which means you cannot supply
110    /// both a `color` and a `decoration` argument. If you want to have both a
111    /// `color` and a `decoration`, you can pass the color as the `color`
112    /// argument to the `BoxDecoration`.
113    ///
114    /// If there is no intention to render anything on this decoration, consider
115    /// using a `Container` with a `BoxConstraints` instead.
116    pub fn new() -> Ink {
117        Ink {
118            key: None,
119            child: None,
120            padding: None,
121            color: None,
122            decoration: None,
123            width: None,
124            height: None,
125        }
126    }
127
128    /// Dart `Ink(key:)`.
129    pub fn key(mut self, key: KeyRef) -> Ink {
130        self.key = Some(key);
131        self
132    }
133
134    /// Dart `Ink(padding:)`.
135    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> Ink {
136        let padding = padding.into();
137        debug_assert!(padding.is_non_negative());
138        self.padding = Some(padding);
139        self
140    }
141
142    /// Dart `Ink(color:)`.
143    pub fn color(mut self, color: Color) -> Ink {
144        self.color = Some(color);
145        self.debug_assert_color_or_decoration();
146        self
147    }
148
149    /// Dart `Ink(decoration:)`.
150    pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> Ink {
151        let decoration = decoration.into();
152        debug_assert!(decoration.debug_assert_is_valid());
153        self.decoration = Some(decoration);
154        self.debug_assert_color_or_decoration();
155        self
156    }
157
158    /// Dart `Ink(width:)`.
159    pub fn width(mut self, width: f64) -> Ink {
160        self.width = Some(width);
161        self
162    }
163
164    /// Dart `Ink(height:)`.
165    pub fn height(mut self, height: f64) -> Ink {
166        self.height = Some(height);
167        self
168    }
169
170    /// Dart `Ink(child:)`.
171    #[cfg_attr(debug_assertions, track_caller)]
172    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Ink {
173        self.child = Some(child.into_widget());
174        self
175    }
176
177    fn debug_assert_color_or_decoration(&self) {
178        debug_assert!(
179            self.color.is_none() || self.decoration.is_none(),
180            "Cannot provide both a color and a decoration\nThe color argument is just a \
181             shorthand for \"decoration: BoxDecoration(color: color)\"."
182        );
183    }
184
185    /// Dart's `decoration` field, as its constructor fills it.
186    pub fn effective_decoration(&self) -> Option<DecorationRef> {
187        match (&self.decoration, self.color) {
188            (Some(decoration), _) => Some(decoration.clone()),
189            (None, Some(color)) => Some(DecorationRef::new(BoxDecoration::new().color(color))),
190            (None, None) => None,
191        }
192    }
193
194    fn padding_including_decoration(&self) -> EdgeInsetsGeometry {
195        let decoration_padding = self
196            .effective_decoration()
197            .map(|decoration| decoration.padding());
198        match (self.padding, decoration_padding) {
199            (None, None) => EdgeInsets::ZERO.into(),
200            (None, Some(padding)) => padding,
201            (Some(padding), None) => padding,
202            (Some(padding), Some(decoration_padding)) => padding.add(decoration_padding),
203        }
204    }
205}
206
207impl Default for Ink {
208    fn default() -> Ink {
209        Ink::new()
210    }
211}
212
213impl StatefulWidget for Ink {
214    type State = InkState;
215
216    fn key(&self) -> Option<&KeyRef> {
217        self.key.as_ref()
218    }
219
220    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
221        properties.add(
222            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
223                .default_value(None),
224        );
225        properties.add(
226            DiagnosticsProperty::<DecorationRef>::new("bg", self.decoration.clone())
227                .default_value(None),
228        );
229    }
230
231    fn create_state(&self) -> InkState {
232        InkState {
233            state: StateData::new(),
234            box_key: GlobalKey::new(),
235            ink: None,
236        }
237    }
238}
239
240/// Dart's `_InkState`.
241pub struct InkState {
242    state: StateData<Ink>,
243    box_key: GlobalKey,
244    ink: Option<Ref<InkDecoration>>,
245}
246
247impl InkState {
248    fn handle_removed(self: Handle<Self>, app: &mut App) {
249        app.get_mut(self).ink = None;
250    }
251
252    fn build_child(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
253        // By creating the InkDecoration from within a Builder widget, we can
254        // use the RenderBox of the Padding widget.
255        let decoration = self.widget(app).effective_decoration();
256        let is_visible = Visibility::of(app, context);
257        let configuration = create_local_image_configuration(app, context, None);
258        match app.get(self).ink.clone() {
259            None => {
260                let controller = Material::of(app, context);
261                let box_key = app.get(self).box_key.clone();
262                let reference_box = box_key
263                    .current_context(app)
264                    .expect("the padding is mounted")
265                    .find_render_object(app)
266                    .and_then(|render_object| render_object.as_box())
267                    .expect("the padding is a render box");
268                let ink = InkDecoration::new(
269                    app,
270                    decoration,
271                    is_visible,
272                    configuration,
273                    controller,
274                    reference_box,
275                    Some(Listener::handle_method(self, Self::handle_removed)),
276                );
277                app.get_mut(self).ink = Some(ink);
278            }
279            Some(ink) => {
280                ink.set_decoration(app, decoration);
281                ink.set_is_visible(app, is_visible);
282                ink.set_configuration(app, configuration);
283            }
284        }
285        self.widget(app).child.clone().unwrap_or_else(|| {
286            ConstrainedBox::new(BoxConstraints::expand(None, None)).into_widget()
287        })
288    }
289}
290
291impl State for InkState {
292    type Widget = Ink;
293    waft_widgets::state_accessors!();
294
295    fn deactivate(self: Handle<Self>, app: &mut App) {
296        if let Some(ink) = app.get(self).ink.handle() {
297            InkFeatureLeaf::dispose(ink, app);
298        }
299        debug_assert!(app.get(self).ink.is_none());
300    }
301
302    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
303        debug_assert!(debug_check_has_material(app, context));
304        let widget = self.widget(app);
305        let padding = widget.padding_including_decoration();
306        let (width, height) = (widget.width, widget.height);
307        let box_key = app.get(self).box_key.clone();
308        let mut result = Padding::new(padding)
309            .key(box_key.into())
310            .child(Builder::new(move |app, context| {
311                self.build_child(app, context)
312            }))
313            .into_widget();
314        if width.is_some() || height.is_some() {
315            let mut sized = SizedBox::new();
316            if let Some(width) = width {
317                sized = sized.width(width);
318            }
319            if let Some(height) = height {
320                sized = sized.height(height);
321            }
322            result = sized.child(result).into_widget();
323        }
324        result
325    }
326}
327
328/// A decoration on a part of a [`Material`].
329///
330/// This object is rarely created directly. Instead of creating an ink
331/// decoration directly, consider using an [`Ink`] widget, which uses this class
332/// in combination with [`Padding`] and [`ConstrainedBox`] to draw a decoration on a
333/// [`Material`].
334///
335/// See also:
336///
337///  * [`Ink`], the corresponding widget.
338///  * [`InkResponse`](crate::InkResponse), which uses gestures to trigger ink highlights and
339///    ink splashes in the parent [`Material`].
340///  * [`InkWell`](crate::InkWell), which is a rectangular [`InkResponse`](crate::InkResponse)
341///    (the most common type of ink response).
342///  * [`Material`], which is the widget on which the ink is painted.
343pub struct InkDecoration {
344    ink_feature: InkFeatureData,
345    painter: Option<Box<dyn BoxPainter>>,
346    decoration: Option<DecorationRef>,
347    is_visible: bool,
348    configuration: ImageConfiguration,
349}
350
351impl InkDecoration {
352    /// Draws a decoration on a [`Material`].
353    ///
354    /// Dart's default `is_visible` is true.
355    pub fn new(
356        app: &mut App,
357        decoration: Option<DecorationRef>,
358        is_visible: bool,
359        configuration: ImageConfiguration,
360        controller: AnyMaterialInkController,
361        reference_box: AnyRenderBox,
362        on_removed: Option<Listener>,
363    ) -> Ref<InkDecoration> {
364        let ink_feature = InkFeatureData::new(app, controller, reference_box, on_removed);
365        let this = app.create(InkDecoration {
366            ink_feature,
367            painter: None,
368            decoration: None,
369            is_visible: true,
370            configuration,
371        });
372        this.set_decoration(app, decoration);
373        this.set_is_visible(app, is_visible);
374        controller.add_ink_feature(app, this.erase());
375        this
376    }
377
378    /// What to paint on the [`Material`].
379    ///
380    /// The decoration is painted at the position and size of the `reference_box`,
381    /// on the [`Material`] that owns the `controller`.
382    pub fn decoration(self: Handle<Self>, app: &App) -> Option<&DecorationRef> {
383        app.get(self).decoration.as_ref()
384    }
385
386    /// Sets [`decoration`](Self::decoration).
387    pub fn set_decoration(self: Handle<Self>, app: &mut App, value: Option<DecorationRef>) {
388        if value == app.get(self).decoration {
389            return;
390        }
391        let controller = InkFeature::controller(self, app);
392        let painter = value.as_ref().map(|decoration| {
393            decoration.create_box_painter(Some(Rc::new(move |app: &mut App| {
394                controller.mark_needs_paint(app)
395            })))
396        });
397        let ink = app.get_mut(self);
398        ink.decoration = value;
399        if let Some(mut old_painter) = std::mem::replace(&mut ink.painter, painter) {
400            old_painter.dispose();
401        }
402        controller.mark_needs_paint(app);
403    }
404
405    /// Whether the decoration should be painted.
406    ///
407    /// Defaults to true.
408    pub fn is_visible(self: Handle<Self>, app: &App) -> bool {
409        app.get(self).is_visible
410    }
411
412    /// Sets [`is_visible`](Self::is_visible).
413    pub fn set_is_visible(self: Handle<Self>, app: &mut App, value: bool) {
414        if value == app.get(self).is_visible {
415            return;
416        }
417        app.get_mut(self).is_visible = value;
418        InkFeature::controller(self, app).mark_needs_paint(app);
419    }
420
421    /// The configuration to pass to the `BoxPainter` obtained from the
422    /// [`decoration`](Self::decoration), when painting.
423    ///
424    /// The `ImageConfiguration::size` field is ignored (and replaced by the size
425    /// of the `reference_box`, at paint time).
426    pub fn configuration(self: Handle<Self>, app: &App) -> &ImageConfiguration {
427        &app.get(self).configuration
428    }
429
430    /// Sets [`configuration`](Self::configuration).
431    pub fn set_configuration(self: Handle<Self>, app: &mut App, value: ImageConfiguration) {
432        if value == app.get(self).configuration {
433            return;
434        }
435        app.get_mut(self).configuration = value;
436        InkFeature::controller(self, app).mark_needs_paint(app);
437    }
438}
439
440impl InkFeatureLeafData for InkDecoration {
441    fn ink_feature(&self) -> &InkFeatureData {
442        &self.ink_feature
443    }
444
445    fn ink_feature_mut(&mut self) -> &mut InkFeatureData {
446        &mut self.ink_feature
447    }
448}
449
450impl InkFeatureLeaf for InkDecoration {
451    fn dispose(self: Handle<Self>, app: &mut App) {
452        if let Some(mut painter) = app.get_mut(self).painter.take() {
453            painter.dispose();
454        }
455        InkFeature::dispose(self, app);
456    }
457
458    fn paint_feature(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, transform: &Matrix4) {
459        if app.get(self).painter.is_none() || !self.is_visible(app) {
460            return;
461        }
462        let origin_offset = get_as_translation(*transform);
463        let size = InkFeature::reference_box(self, app).size(app);
464        let sized_configuration =
465            self.configuration(app)
466                .copy_with(None, None, None, None, Some(size), None);
467        let painter = app.get_mut(self).painter.as_mut().expect("checked above");
468        match origin_offset {
469            None => {
470                canvas.save();
471                canvas.concat(transform);
472                painter.paint(canvas, Offset::ZERO, &sized_configuration);
473                canvas.restore();
474            }
475            Some(origin_offset) => {
476                painter.paint(canvas, origin_offset, &sized_configuration);
477            }
478        }
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use std::time::Duration;
485
486    use waft_embedder::{Rect, Size};
487    use waft_widgets::Center;
488
489    use waft_widgets::testing::{TestPointer, WidgetTester, test_widgets};
490
491    use super::*;
492    use crate::colors::Colors;
493    use crate::ink_well::InkWell;
494    use crate::test_support::{PaintInspection, path_like};
495    use crate::theme::Theme;
496    use crate::theme_data::ThemeData;
497    use waft_rendering::testing::RecordedCall;
498
499    #[test]
500    fn the_ink_widget_expands_when_no_dimensions_are_set() {
501        test_widgets(|tester| {
502            let key = GlobalKey::new();
503            tester.pump_widget(
504                Material::new()
505                    .child(Ink::new().key(key.clone().into()))
506                    .into_widget(),
507            );
508            assert_eq!(tester.get_size(&key), Size::new(800.0, 600.0));
509        });
510    }
511
512    #[test]
513    fn the_ink_widget_fits_the_specified_size() {
514        test_widgets(|tester| {
515            let key = GlobalKey::new();
516            tester.pump_widget(
517                Material::new()
518                    .child(
519                        // used to constrain to child's size
520                        Center::new().child(
521                            Ink::new()
522                                .key(key.clone().into())
523                                .height(150.0)
524                                .width(200.0),
525                        ),
526                    )
527                    .into_widget(),
528            );
529            tester.pump_and_settle();
530            assert_eq!(tester.get_size(&key), Size::new(200.0, 150.0));
531        });
532    }
533
534    #[test]
535    fn the_ink_widget_expands_on_a_unspecified_dimension() {
536        test_widgets(|tester| {
537            let key = GlobalKey::new();
538            tester.pump_widget(
539                Material::new()
540                    .child(
541                        // used to constrain to child's size
542                        Center::new().child(Ink::new().key(key.clone().into()).height(150.0)),
543                    )
544                    .into_widget(),
545            );
546            tester.pump_and_settle();
547            assert_eq!(tester.get_size(&key), Size::new(800.0, 150.0));
548        });
549    }
550
551    fn m2_ink_frame(tester: &WidgetTester, ink: Option<Color>) -> WidgetRef {
552        let ink_well = InkWell::new()
553            .splash_color(Colors::GREEN.primary())
554            .on_tap(Listener::new(|_app| {}));
555        let child = match ink {
556            Some(color) => Ink::new()
557                .color(color)
558                .width(200.0)
559                .height(200.0)
560                .child(ink_well)
561                .into_widget(),
562            None => ink_well.into_widget(),
563        };
564        let data = ThemeData::builder()
565            .use_material3(false)
566            .build(&tester.cell.borrow());
567        Theme::new(
568            data,
569            waft_widgets::Directionality::new(
570                waft_embedder::TextDirection::Ltr,
571                Material::new().child(Center::new().child(child)),
572            ),
573        )
574        .into_widget()
575    }
576
577    /// Dart's `paints..rect(rect: rect, color: rect_color)..circle(color: circle_color)` on the
578    /// material.
579    fn paints_rect_then_circle(
580        tester: &WidgetTester,
581        rect_color: Color,
582        rect: Rect,
583        circle_color: Color,
584    ) -> bool {
585        use waft_rendering::testing::{PaintCall, paints};
586        paints(
587            tester.ink_list().ops(),
588            &[
589                PaintCall::rect_at(rect, Some(rect_color)),
590                PaintCall::circle(Some(circle_color)),
591            ],
592        )
593        .is_ok()
594    }
595
596    #[test]
597    fn material2_does_the_ink_widget_render_anything() {
598        test_widgets(|tester| {
599            let blue = Colors::BLUE.primary();
600            let red = Colors::RED.primary();
601            let green = Colors::GREEN.primary();
602            let ink_rect = Rect::from_ltrb(300.0, 200.0, 500.0, 400.0);
603            let widget = m2_ink_frame(tester, Some(blue));
604            tester.pump_widget(widget);
605
606            let mut gesture = TestPointer::touch(1);
607            tester.down(&mut gesture, WidgetTester::SIZE.center(Offset::ZERO));
608            tester.pump(); // start gesture
609            tester.pump_by(Duration::from_millis(200)); // wait for splash to be well under way
610
611            let box_ = tester.first::<crate::material::RenderInkFeatures>();
612            assert!(
613                paints_rect_then_circle(tester, blue, ink_rect, green),
614                "{:?}",
615                tester.ink_calls()
616            );
617
618            let widget = m2_ink_frame(tester, Some(red));
619            tester.pump_widget(widget);
620            assert_eq!(tester.first::<crate::material::RenderInkFeatures>(), box_);
621            assert!(
622                paints_rect_then_circle(tester, red, ink_rect, green),
623                "{:?}",
624                tester.ink_calls()
625            );
626
627            // this is at a different depth in the tree so it's now a new InkWell
628            let widget = m2_ink_frame(tester, None);
629            tester.pump_widget(widget);
630            assert_eq!(tester.first::<crate::material::RenderInkFeatures>(), box_);
631            let drawn = tester.ink_calls();
632            assert!(
633                !drawn
634                    .iter()
635                    .any(|drawn| matches!(drawn, RecordedCall::Rect { .. }))
636            );
637            assert!(!drawn.iter().any(|drawn| path_like(drawn).is_some()));
638
639            tester.up(&gesture);
640        });
641    }
642
643    #[test]
644    fn ink_with_is_visible_false_does_not_paint() {
645        test_widgets(|tester| {
646            let test_color = Color::new(0xffff1234);
647            let ink_widget = |is_visible: bool| {
648                Material::new()
649                    .child(
650                        Visibility::maintain(
651                            Ink::new().decoration(BoxDecoration::new().color(test_color)),
652                        )
653                        .visible(is_visible),
654                    )
655                    .into_widget()
656            };
657            let has_test_color = |drawn: &[RecordedCall]| {
658                drawn
659                    .iter()
660                    .any(|drawn| matches!(drawn, RecordedCall::Rect { color, .. } if color.to_argb32() == test_color.to_argb32()))
661            };
662
663            tester.pump_widget(ink_widget(true));
664            assert!(has_test_color(&tester.ink_calls()));
665
666            tester.pump_widget(ink_widget(false));
667            assert!(!has_test_color(&tester.ink_calls()));
668        });
669    }
670}