Skip to main content

waft_rendering/
custom_paint.rs

1//! Flutter counterpart: `rendering/custom_paint.dart` (`CustomPainter`, `RenderCustomPaint`).
2//!
3//! Semantics (`SemanticsBuilderCallback`, `CustomPainterSemantics`,
4//! `CustomPainter.semanticsBuilder` / `shouldRebuildSemantics`) waits.
5
6use std::any::Any;
7use std::rc::Rc;
8
9use waft_embedder::{Canvas, Matrix4, Offset, Size, TextBaseline};
10use waft_foundation::{
11    App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listenable,
12    Listener, MessageProperty,
13};
14use waft_painting::ClipContext;
15
16use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult, RenderBox, RenderBoxData};
17use crate::object::{
18    AnyRenderObject, RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
19    RenderObjectWithChildMixin,
20};
21use crate::painting_context::PaintingContext;
22use crate::pipeline_owner::PipelineOwner;
23use crate::proxy_box::{RenderProxyBoxMixin, same_instance};
24
25/// The interface used by `CustomPaint` (in the widgets library) and
26/// [`RenderCustomPaint`] (in the rendering library).
27///
28/// To implement a custom painter, implement this trait to define your custom paint delegate.
29/// A [`CustomPainter`] must implement the [`paint`](Self::paint) and
30/// [`should_repaint`](Self::should_repaint) methods, and may optionally also implement the
31/// [`hit_test`](Self::hit_test) method.
32///
33/// The [`paint`](Self::paint) method is called whenever the custom object needs to be
34/// repainted.
35///
36/// The [`should_repaint`](Self::should_repaint) method is called when a new instance of the
37/// class is provided, to check if the new instance actually represents different information.
38///
39/// The most efficient way to trigger a repaint is to supply a [`repaint`](Self::repaint)
40/// listenable, which notifies its listeners when it is time to repaint: the
41/// [`RenderCustomPaint`] listens to it and repaints whenever the animation ticks, avoiding both
42/// the build and layout phases of the pipeline.
43///
44/// The [`hit_test`](Self::hit_test) method is called when the user interacts with the
45/// underlying render object, to determine if the user hit the object or missed it.
46///
47/// ## Composition and the sharing of canvases
48///
49/// Widgets (or rather, render objects) are composited together using a minimum
50/// number of [`Canvas`]es, for performance reasons. As a result, a
51/// [`CustomPainter`]'s [`Canvas`] may be the same as that used by other widgets
52/// (including other `CustomPaint` widgets).
53///
54/// This is mostly unnoticeable, except when using unusual blend modes. For
55/// example, trying to use `BlendMode::DstOut` to "punch a hole" through a
56/// previously-drawn image may erase more than was intended, because previous
57/// widgets will have been painted onto the same canvas.
58///
59/// To avoid this issue, consider using `Canvas::save_layer` and
60/// `Canvas::restore` when using such blend modes. Creating new layers is
61/// relatively expensive, however, and should be done sparingly to avoid
62/// introducing jank.
63pub trait CustomPainter: 'static {
64    /// The [`Listenable`] that notifies when it is time to repaint.
65    ///
66    /// Dart's `CustomPainter` takes it as a constructor argument and forwards `addListener` /
67    /// `removeListener` to it; here the painter answers with it and the same forwarding is the
68    /// [`Listenable`] implementation of `dyn CustomPainter`.
69    fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
70        None
71    }
72
73    /// Called whenever the object needs to paint. The given [`Canvas`] has its
74    /// coordinate space configured such that the origin is at the top left of the
75    /// box. The area of the box is the size of the `size` argument.
76    ///
77    /// Paint operations should remain inside the given area. Graphical
78    /// operations outside the bounds may be silently ignored, clipped, or not
79    /// clipped. It may sometimes be difficult to guarantee that a certain
80    /// operation is inside the bounds (e.g., drawing a rectangle whose size is
81    /// determined by user inputs). In that case, consider calling
82    /// `Canvas::clip_rect` at the beginning of `paint` so everything that follows
83    /// will be guaranteed to only draw within the clipped area.
84    ///
85    /// Implementations should be wary of correctly pairing any calls to
86    /// `Canvas::save` / `Canvas::save_layer` and `Canvas::restore`, otherwise all
87    /// subsequent painting on this canvas may be affected, with potentially
88    /// hilarious but confusing results.
89    ///
90    /// To paint text on a [`Canvas`], use a `TextPainter`.
91    ///
92    /// `app` reaches what a Dart painter reads directly: an animation's value, the fonts.
93    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size);
94
95    /// Called whenever a new instance of the custom painter delegate class is
96    /// provided to the [`RenderCustomPaint`] object, or any time that a new
97    /// `CustomPaint` object is created with a new instance of the custom painter
98    /// delegate class (which amounts to the same thing, because the latter is
99    /// implemented in terms of the former).
100    ///
101    /// If the new instance represents different information than the old
102    /// instance, then the method should return true, otherwise it should return
103    /// false.
104    ///
105    /// If the method returns false, then the [`paint`](Self::paint) call might be optimized
106    /// away.
107    ///
108    /// It's possible that the [`paint`](Self::paint) method will get called even if
109    /// [`should_repaint`](Self::should_repaint) returns false (e.g. if an ancestor or
110    /// descendant needed to be repainted). It's also possible that the [`paint`](Self::paint)
111    /// method will get called without [`should_repaint`](Self::should_repaint) being called at
112    /// all (e.g. if the box changes size).
113    ///
114    /// If a custom delegate has a particularly expensive paint function such that
115    /// repaints should be avoided as much as possible, a `RepaintBoundary` or
116    /// [`crate::RenderRepaintBoundary`] (or other render object with
117    /// [`RenderObject::is_repaint_boundary`] set to true) might be helpful.
118    ///
119    /// `old_delegate` is only ever a painter of this painter's own type, as Dart's `covariant`
120    /// parameter is.
121    fn should_repaint(&self, app: &App, old_delegate: &dyn CustomPainter) -> bool;
122
123    /// Called whenever a hit test is being performed on an object that is using
124    /// this custom paint delegate.
125    ///
126    /// The given point is relative to the same coordinate space as the last
127    /// [`paint`](Self::paint) call.
128    ///
129    /// The default behavior is to consider all points to be hits for
130    /// background painters, and no points to be hits for foreground painters.
131    ///
132    /// Return `Some(true)` if the given position corresponds to a point on the drawn
133    /// image that should be considered a "hit", `Some(false)` if it corresponds to a
134    /// point that should be considered outside the painted image, and `None` to use
135    /// the default behavior.
136    fn hit_test(&self, app: &App, position: Offset) -> Option<bool> {
137        let _ = (app, position);
138        None
139    }
140
141    /// Downcast support for Dart's `runtimeType` comparison and `covariant` parameter.
142    fn as_any(&self) -> &dyn Any;
143}
144
145impl Listenable for dyn CustomPainter {
146    /// Register a closure to be notified when it is time to repaint.
147    ///
148    /// Forwards to the [`repaint`](CustomPainter::repaint) listenable, if it is not `None`.
149    fn add_listener(&self, app: &mut App, listener: Listener) {
150        if let Some(repaint) = self.repaint() {
151            repaint.add_listener(app, listener);
152        }
153    }
154
155    /// Remove a previously registered closure from the list of closures that the
156    /// object notifies when it is time to repaint.
157    fn remove_listener(&self, app: &mut App, listener: &Listener) {
158        if let Some(repaint) = self.repaint() {
159            repaint.remove_listener(app, listener);
160        }
161    }
162}
163
164/// Delegates its painting to a [`painter`](Self::painter) and a
165/// [`foreground_painter`](Self::foreground_painter).
166pub struct RenderCustomPaint {
167    render_object: RenderObjectData,
168    render_box: RenderBoxData,
169    child: RenderObjectWithChildData<AnyRenderBox>,
170    painter: Option<Rc<dyn CustomPainter>>,
171    foreground_painter: Option<Rc<dyn CustomPainter>>,
172    preferred_size: Size,
173    is_complex: bool,
174    will_change: bool,
175}
176
177impl RenderCustomPaint {
178    /// Creates a render object that delegates its painting.
179    pub fn new(
180        app: &mut App,
181        painter: Option<Rc<dyn CustomPainter>>,
182        foreground_painter: Option<Rc<dyn CustomPainter>>,
183        preferred_size: Size,
184        is_complex: bool,
185        will_change: bool,
186        child: Option<AnyRenderBox>,
187    ) -> RenderHandle<RenderCustomPaint> {
188        let this = RenderHandle::new_box(
189            app,
190            RenderCustomPaint {
191                render_object: RenderObjectData::new(),
192                render_box: RenderBoxData::new(),
193                child: RenderObjectWithChildData::new(),
194                painter,
195                foreground_painter,
196                preferred_size,
197                is_complex,
198                will_change,
199            },
200        );
201        this.set_child(app, child);
202        this
203    }
204
205    /// The background custom paint delegate.
206    ///
207    /// This painter, if non-`None`, is called to paint behind the children.
208    pub fn painter(self: RenderHandle<Self>, app: &App) -> Option<Rc<dyn CustomPainter>> {
209        self.get(app).painter.clone()
210    }
211
212    /// Set a new background custom paint delegate.
213    ///
214    /// If the new delegate is the same as the previous one, this does nothing.
215    ///
216    /// If the new delegate is the same class as the previous one, then the new
217    /// delegate has its [`CustomPainter::should_repaint`] called; if the result is
218    /// true, then the delegate will be called.
219    ///
220    /// If the new delegate is a different class than the previous one, then the
221    /// delegate will be called.
222    ///
223    /// If the new value is `None`, then there is no background custom painter.
224    pub fn set_painter(
225        self: RenderHandle<Self>,
226        app: &mut App,
227        value: Option<Rc<dyn CustomPainter>>,
228    ) {
229        let old_painter = self.get(app).painter.clone();
230        if same_instance(old_painter.as_ref(), value.as_ref()) {
231            return;
232        }
233        self.get_mut(app).painter = value.clone();
234        self.did_update_painter(app, value.as_ref(), old_painter.as_ref());
235    }
236
237    /// The foreground custom paint delegate.
238    ///
239    /// This painter, if non-`None`, is called to paint in front of the children.
240    pub fn foreground_painter(
241        self: RenderHandle<Self>,
242        app: &App,
243    ) -> Option<Rc<dyn CustomPainter>> {
244        self.get(app).foreground_painter.clone()
245    }
246
247    /// Set a new foreground custom paint delegate.
248    ///
249    /// If the new delegate is the same as the previous one, this does nothing.
250    ///
251    /// If the new delegate is the same class as the previous one, then the new
252    /// delegate has its [`CustomPainter::should_repaint`] called; if the result is
253    /// true, then the delegate will be called.
254    ///
255    /// If the new delegate is a different class than the previous one, then the
256    /// delegate will be called.
257    ///
258    /// If the new value is `None`, then there is no foreground custom painter.
259    pub fn set_foreground_painter(
260        self: RenderHandle<Self>,
261        app: &mut App,
262        value: Option<Rc<dyn CustomPainter>>,
263    ) {
264        let old_painter = self.get(app).foreground_painter.clone();
265        if same_instance(old_painter.as_ref(), value.as_ref()) {
266            return;
267        }
268        self.get_mut(app).foreground_painter = value.clone();
269        self.did_update_painter(app, value.as_ref(), old_painter.as_ref());
270    }
271
272    fn did_update_painter(
273        self: RenderHandle<Self>,
274        app: &mut App,
275        new_painter: Option<&Rc<dyn CustomPainter>>,
276        old_painter: Option<&Rc<dyn CustomPainter>>,
277    ) {
278        // Check if we need to repaint.
279        let repaint = match (new_painter, old_painter) {
280            (None, old_painter) => {
281                debug_assert!(old_painter.is_some()); // We should be called only for changes.
282                true
283            }
284            (Some(new_painter), Some(old_painter)) => {
285                new_painter.as_any().type_id() != old_painter.as_any().type_id()
286                    || new_painter.should_repaint(app, &**old_painter)
287            }
288            (Some(_), None) => true,
289        };
290        if repaint {
291            self.mark_needs_paint(app);
292        }
293        if self.attached(app) {
294            if let Some(old_painter) = old_painter {
295                old_painter.remove_listener(app, &self.paint_listener());
296            }
297            if let Some(new_painter) = new_painter {
298                new_painter.add_listener(app, self.paint_listener());
299            }
300        }
301        // Dart also rebuilds semantics here; semantics waits.
302    }
303
304    /// The `markNeedsPaint` tear-off, equal to itself across registrations.
305    fn paint_listener(self: RenderHandle<Self>) -> Listener {
306        Listener::handle_method(self.handle(), mark_needs_paint)
307    }
308
309    /// The size that this [`RenderCustomPaint`] should aim for, given the layout
310    /// constraints, if there is no child.
311    ///
312    /// Defaults to [`Size::ZERO`].
313    ///
314    /// If there's a child, this is ignored, and the size of the child is used
315    /// instead.
316    pub fn preferred_size(self: RenderHandle<Self>, app: &App) -> Size {
317        self.get(app).preferred_size
318    }
319
320    /// Sets [`preferred_size`](Self::preferred_size).
321    pub fn set_preferred_size(self: RenderHandle<Self>, app: &mut App, value: Size) {
322        if self.preferred_size(app) == value {
323            return;
324        }
325        self.get_mut(app).preferred_size = value;
326        self.mark_needs_layout(app);
327    }
328
329    /// Whether to hint that this layer's painting should be cached.
330    ///
331    /// The compositor contains a raster cache that holds bitmaps of layers in
332    /// order to avoid the cost of repeatedly rendering those layers on each
333    /// frame. If this flag is not set, then the compositor will apply its own
334    /// heuristics to decide whether the layer containing this render object is
335    /// complex enough to benefit from caching.
336    pub fn is_complex(self: RenderHandle<Self>, app: &App) -> bool {
337        self.get(app).is_complex
338    }
339
340    /// Sets [`is_complex`](Self::is_complex). Dart's plain field.
341    pub fn set_is_complex(self: RenderHandle<Self>, app: &mut App, value: bool) {
342        self.get_mut(app).is_complex = value;
343    }
344
345    /// Whether the raster cache should be told that this painting is likely
346    /// to change in the next frame.
347    ///
348    /// This hint tells the compositor not to cache the layer containing this
349    /// render object because the cache will not be used in the future. If this
350    /// hint is not set, the compositor will apply its own heuristics to decide
351    /// whether this layer is likely to be reused in the future.
352    pub fn will_change(self: RenderHandle<Self>, app: &App) -> bool {
353        self.get(app).will_change
354    }
355
356    /// Sets [`will_change`](Self::will_change). Dart's plain field.
357    pub fn set_will_change(self: RenderHandle<Self>, app: &mut App, value: bool) {
358        self.get_mut(app).will_change = value;
359    }
360
361    fn paint_with_painter(
362        self: RenderHandle<Self>,
363        app: &mut App,
364        canvas: &mut Canvas,
365        offset: Offset,
366        painter: &dyn CustomPainter,
367    ) {
368        canvas.save();
369        let debug_previous_canvas_save_count = canvas.save_count();
370        if offset != Offset::ZERO {
371            canvas.translate(offset.dx() as f32, offset.dy() as f32);
372        }
373        let size = self.size(app);
374        painter.paint(app, canvas, size);
375        // This isn't perfect. For example, we can't catch the case of
376        // someone first restoring, then setting a transform or whatnot,
377        // then saving.
378        debug_assert_eq!(
379            debug_previous_canvas_save_count,
380            canvas.save_count(),
381            "the custom painter had mismatching save and restore calls"
382        );
383        canvas.restore();
384    }
385
386    fn set_raster_cache_hints(self: RenderHandle<Self>, app: &App, context: &mut PaintingContext) {
387        if self.get(app).is_complex {
388            context.set_is_complex_hint();
389        }
390        if self.get(app).will_change {
391            context.set_will_change_hint();
392        }
393    }
394}
395
396fn mark_needs_paint(this: Handle<RenderCustomPaint>, app: &mut App) {
397    RenderHandle::from_handle(this).mark_needs_paint(app);
398}
399
400impl RenderObjectWithChildMixin for RenderCustomPaint {
401    type ChildType = AnyRenderBox;
402
403    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
404        &self.get(app).child
405    }
406
407    fn child_data_mut(
408        self: RenderHandle<Self>,
409        app: &mut App,
410    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
411        &mut self.get_mut(app).child
412    }
413}
414
415impl RenderProxyBoxMixin for RenderCustomPaint {
416    fn compute_size_for_no_child(
417        self: RenderHandle<Self>,
418        app: &App,
419        constraints: BoxConstraints,
420    ) -> Size {
421        constraints.constrain(self.get(app).preferred_size)
422    }
423}
424
425/// Dart's `'$painter'`: `null`, or the painter's `toString`.
426///
427/// A Dart object's default `toString` names its runtime class; a Rust trait object has no runtime
428/// class name, so every painter reads as `CustomPainter`.
429fn painter_description(painter: &Option<Rc<dyn CustomPainter>>) -> String {
430    if painter.is_some() {
431        "Instance of 'CustomPainter'".to_string()
432    } else {
433        "null".to_string()
434    }
435}
436
437impl RenderObject for RenderCustomPaint {
438    crate::render_object_accessors!();
439
440    fn debug_fill_properties(
441        self: RenderHandle<Self>,
442        app: &App,
443        properties: &mut DiagnosticPropertiesBuilder,
444    ) {
445        let this = self.get(app);
446        properties.add(MessageProperty::new(
447            "painter",
448            painter_description(&this.painter),
449        ));
450        properties.add(
451            MessageProperty::new(
452                "foregroundPainter",
453                painter_description(&this.foreground_painter),
454            )
455            .with_level(if this.foreground_painter.is_some() {
456                DiagnosticLevel::Info
457            } else {
458                DiagnosticLevel::Fine
459            }),
460        );
461        properties.add(
462            DiagnosticsProperty::new("preferredSize", this.preferred_size)
463                .default_value(Some(Size::ZERO)),
464        );
465        properties
466            .add(DiagnosticsProperty::new("isComplex", this.is_complex).default_value(Some(false)));
467        properties.add(
468            DiagnosticsProperty::new("willChange", this.will_change).default_value(Some(false)),
469        );
470    }
471
472    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
473        if let Some(child) = self.child(app) {
474            child.as_object().attach(app, owner);
475        }
476        if let Some(painter) = self.painter(app) {
477            painter.add_listener(app, self.paint_listener());
478        }
479        if let Some(foreground_painter) = self.foreground_painter(app) {
480            foreground_painter.add_listener(app, self.paint_listener());
481        }
482    }
483
484    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
485        if let Some(painter) = self.painter(app) {
486            painter.remove_listener(app, &self.paint_listener());
487        }
488        if let Some(foreground_painter) = self.foreground_painter(app) {
489            foreground_painter.remove_listener(app, &self.paint_listener());
490        }
491        if let Some(child) = self.child(app) {
492            child.as_object().detach(app);
493        }
494    }
495
496    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
497        RenderProxyBoxMixin::perform_layout(self, app);
498    }
499
500    fn paint(
501        self: RenderHandle<Self>,
502        app: &mut App,
503        context: &mut PaintingContext,
504        offset: Offset,
505    ) {
506        if let Some(painter) = self.painter(app) {
507            self.paint_with_painter(app, context.canvas(), offset, &*painter);
508            self.set_raster_cache_hints(app, context);
509        }
510        RenderProxyBoxMixin::paint(self, app, context, offset);
511        if let Some(foreground_painter) = self.foreground_painter(app) {
512            self.paint_with_painter(app, context.canvas(), offset, &*foreground_painter);
513            self.set_raster_cache_hints(app, context);
514        }
515    }
516
517    fn visit_children(
518        self: RenderHandle<Self>,
519        app: &App,
520        visitor: &mut dyn FnMut(AnyRenderObject),
521    ) {
522        if let Some(child) = self.child(app) {
523            visitor(child.as_object());
524        }
525    }
526}
527
528impl RenderBox for RenderCustomPaint {
529    crate::render_box_accessors!();
530
531    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
532        RenderProxyBoxMixin::setup_parent_data(self, app, child);
533    }
534
535    fn apply_paint_transform(
536        self: RenderHandle<Self>,
537        app: &App,
538        child: AnyRenderObject,
539        transform: &mut Matrix4,
540    ) {
541        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
542    }
543
544    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
545        if self.child(app).is_none() {
546            let width = self.preferred_size(app).width();
547            return if width.is_finite() { width } else { 0.0 };
548        }
549        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
550    }
551
552    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
553        if self.child(app).is_none() {
554            let width = self.preferred_size(app).width();
555            return if width.is_finite() { width } else { 0.0 };
556        }
557        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
558    }
559
560    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
561        if self.child(app).is_none() {
562            let height = self.preferred_size(app).height();
563            return if height.is_finite() { height } else { 0.0 };
564        }
565        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
566    }
567
568    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
569        if self.child(app).is_none() {
570            let height = self.preferred_size(app).height();
571            return if height.is_finite() { height } else { 0.0 };
572        }
573        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
574    }
575
576    fn compute_distance_to_actual_baseline(
577        self: RenderHandle<Self>,
578        app: &mut App,
579        baseline: TextBaseline,
580    ) -> Option<f64> {
581        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
582    }
583
584    fn compute_dry_baseline(
585        self: RenderHandle<Self>,
586        app: &mut App,
587        constraints: BoxConstraints,
588        baseline: TextBaseline,
589    ) -> Option<f64> {
590        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
591    }
592
593    fn compute_dry_layout(
594        self: RenderHandle<Self>,
595        app: &mut App,
596        constraints: BoxConstraints,
597    ) -> Size {
598        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
599    }
600
601    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
602        match &self.get(app).painter {
603            Some(painter) => painter.hit_test(app, position).unwrap_or(true),
604            None => false,
605        }
606    }
607
608    fn hit_test_children(
609        self: RenderHandle<Self>,
610        app: &mut App,
611        result: &mut BoxHitTestResult<'_>,
612        position: Offset,
613    ) -> bool {
614        if let Some(foreground_painter) = self.foreground_painter(app)
615            && foreground_painter.hit_test(app, position).unwrap_or(false)
616        {
617            return true;
618        }
619        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
620    }
621}
622
623#[cfg(test)]
624mod tests {
625    use std::cell::Cell;
626    use waft_foundation::AppCell;
627
628    use waft_embedder::{Color, Paint, valo};
629    use waft_foundation::ValueNotifier;
630    use waft_gestures::HitTestResult;
631    use waft_painting::AlignmentGeometry;
632
633    use super::*;
634    use crate::box_::BoxHitTestResult;
635    use crate::object::AnyRenderObject;
636    use crate::testing::{EnginePhase, layout_with, painted_ops, pump_frame};
637
638    const RED: Color = Color::from_argb(255, 255, 0, 0);
639    const BLUE: Color = Color::from_argb(255, 0, 0, 255);
640    const GREEN: Color = Color::from_argb(255, 0, 255, 0);
641
642    /// Fills the box with `color`, counting its paints; `hit` is what it reports for every
643    /// position, and `should_repaint` what it answers about any older painter.
644    struct Recorder {
645        color: Color,
646        paints: Rc<Cell<u32>>,
647        hit: Option<bool>,
648        repaint: Option<Rc<dyn Listenable>>,
649        should_repaint: bool,
650    }
651
652    impl Recorder {
653        fn new(color: Color) -> Recorder {
654            Recorder {
655                color,
656                paints: Rc::new(Cell::new(0)),
657                hit: None,
658                repaint: None,
659                should_repaint: false,
660            }
661        }
662    }
663
664    impl CustomPainter for Recorder {
665        fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
666            self.repaint.as_ref()
667        }
668
669        fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
670            self.paints.set(self.paints.get() + 1);
671            canvas.draw_rect(
672                Offset::ZERO & size,
673                &Paint {
674                    color: self.color.into(),
675                    ..Paint::default()
676                },
677            );
678        }
679
680        fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
681            self.should_repaint
682        }
683
684        fn hit_test(&self, _app: &App, _position: Offset) -> Option<bool> {
685            self.hit
686        }
687
688        fn as_any(&self) -> &dyn Any {
689            self
690        }
691    }
692
693    /// The color of every fill `render` paints, in paint order.
694    fn drawn_colors(app: &mut App, render: AnyRenderObject) -> Vec<valo::Color> {
695        painted_ops(app, render)
696            .into_iter()
697            .filter_map(|op| match op {
698                valo::Op::DrawRect { paint, .. } => Some(paint.color),
699                _ => None,
700            })
701            .collect()
702    }
703
704    fn hit_test(app: &mut App, target: AnyRenderBox, position: Offset) -> (bool, usize) {
705        let mut result = HitTestResult::new();
706        let is_hit = target.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
707        (is_hit, result.path().len())
708    }
709
710    #[test]
711    fn both_painters_paint_around_the_child() {
712        let cell = AppCell::new();
713        let mut app = cell.borrow_mut();
714        let background = Rc::new(Recorder::new(RED));
715        let foreground = Rc::new(Recorder::new(BLUE));
716        let child = crate::proxy_box::RenderColoredBox::new(&mut app, GREEN, true, None);
717        let custom = RenderCustomPaint::new(
718            &mut app,
719            Some(background.clone()),
720            Some(foreground.clone()),
721            Size::ZERO,
722            false,
723            false,
724            Some(child.as_box()),
725        );
726        layout_with(
727            &mut app,
728            custom.as_box(),
729            None,
730            AlignmentGeometry::CENTER,
731            EnginePhase::Paint,
732        );
733
734        assert_eq!((background.paints.get(), foreground.paints.get()), (1, 1));
735        assert_eq!(
736            drawn_colors(&mut app, custom.as_object()),
737            [RED.into(), GREEN.into(), BLUE.into()],
738            "background, child, foreground"
739        );
740    }
741
742    #[test]
743    fn a_painter_repaints_when_its_repaint_listenable_notifies() {
744        let cell = AppCell::new();
745        let mut app = cell.borrow_mut();
746        let notifier = app.create(ValueNotifier::new(0));
747        let painter = Rc::new(Recorder {
748            repaint: Some(Rc::new(notifier.clone())),
749            ..Recorder::new(RED)
750        });
751        let custom = RenderCustomPaint::new(
752            &mut app,
753            Some(painter.clone()),
754            None,
755            Size::new(10.0, 10.0),
756            false,
757            false,
758            None,
759        );
760        layout_with(
761            &mut app,
762            custom.as_box(),
763            None,
764            AlignmentGeometry::CENTER,
765            EnginePhase::Paint,
766        );
767        assert_eq!(painter.paints.get(), 1);
768        assert!(!custom.as_object().debug_needs_paint(&app));
769
770        notifier.set_value(&mut app, 1);
771        assert!(custom.as_object().debug_needs_paint(&app));
772        pump_frame(&mut app, EnginePhase::Paint);
773        assert_eq!(painter.paints.get(), 2);
774    }
775
776    /// Dart's `_didUpdatePainter`: the new painter decides, and the listener moves with it.
777    #[test]
778    fn replacing_the_painter_asks_it_whether_to_repaint() {
779        let cell = AppCell::new();
780        let mut app = cell.borrow_mut();
781        let notifier = app.create(ValueNotifier::new(0));
782        let painter = Rc::new(Recorder {
783            repaint: Some(Rc::new(notifier.clone())),
784            ..Recorder::new(RED)
785        });
786        let custom = RenderCustomPaint::new(
787            &mut app,
788            Some(painter.clone()),
789            None,
790            Size::new(10.0, 10.0),
791            false,
792            false,
793            None,
794        );
795        layout_with(
796            &mut app,
797            custom.as_box(),
798            None,
799            AlignmentGeometry::CENTER,
800            EnginePhase::Paint,
801        );
802
803        let quiet = Rc::new(Recorder::new(BLUE));
804        custom.set_painter(&mut app, Some(quiet.clone()));
805        assert!(
806            !custom.as_object().debug_needs_paint(&app),
807            "should_repaint is false"
808        );
809        notifier.set_value(&mut app, 1);
810        assert!(
811            !custom.as_object().debug_needs_paint(&app),
812            "the old painter's listenable was unsubscribed"
813        );
814
815        let eager = Rc::new(Recorder {
816            should_repaint: true,
817            ..Recorder::new(BLUE)
818        });
819        custom.set_painter(&mut app, Some(eager.clone()));
820        assert!(custom.as_object().debug_needs_paint(&app));
821        pump_frame(&mut app, EnginePhase::Paint);
822        assert_eq!((quiet.paints.get(), eager.paints.get()), (0, 1));
823
824        custom.set_painter(&mut app, None);
825        assert!(
826            custom.as_object().debug_needs_paint(&app),
827            "a removal repaints"
828        );
829    }
830
831    #[test]
832    fn preferred_size_is_used_without_a_child() {
833        let cell = AppCell::new();
834        let mut app = cell.borrow_mut();
835        let custom = RenderCustomPaint::new(
836            &mut app,
837            None,
838            None,
839            Size::new(20.0, 30.0),
840            false,
841            false,
842            None,
843        );
844        custom.layout(&mut app, BoxConstraints::new(), false);
845        assert_eq!(custom.size(&app), Size::new(20.0, 30.0));
846
847        custom.layout(
848            &mut app,
849            BoxConstraints::loose(Size::new(10.0, 10.0)),
850            false,
851        );
852        assert_eq!(
853            custom.size(&app),
854            Size::new(10.0, 10.0),
855            "the preferred size is constrained"
856        );
857    }
858
859    #[test]
860    fn a_child_sizes_the_custom_paint() {
861        let cell = AppCell::new();
862        let mut app = cell.borrow_mut();
863        let child = crate::proxy_box::RenderConstrainedBox::new(
864            &mut app,
865            BoxConstraints::tight(Size::new(40.0, 40.0)),
866            None,
867        );
868        let custom = RenderCustomPaint::new(
869            &mut app,
870            None,
871            None,
872            Size::new(20.0, 30.0),
873            false,
874            false,
875            Some(child.as_box()),
876        );
877        custom.layout(&mut app, BoxConstraints::new(), false);
878        assert_eq!(custom.size(&app), Size::new(40.0, 40.0));
879    }
880
881    #[test]
882    fn the_painters_answer_hit_tests() {
883        let cell = AppCell::new();
884        let mut app = cell.borrow_mut();
885        let background = Rc::new(Recorder::new(RED));
886        let custom = RenderCustomPaint::new(
887            &mut app,
888            Some(background),
889            None,
890            Size::new(100.0, 100.0),
891            false,
892            false,
893            None,
894        );
895        custom.layout(&mut app, BoxConstraints::new(), false);
896        assert_eq!(
897            hit_test(&mut app, custom.as_box(), Offset::new(50.0, 50.0)),
898            (true, 1),
899            "a background painter is hit by default"
900        );
901
902        let missing = Rc::new(Recorder {
903            hit: Some(false),
904            ..Recorder::new(RED)
905        });
906        custom.set_painter(&mut app, Some(missing));
907        assert_eq!(
908            hit_test(&mut app, custom.as_box(), Offset::new(50.0, 50.0)),
909            (false, 0)
910        );
911
912        custom.set_painter(&mut app, None);
913        assert_eq!(
914            hit_test(&mut app, custom.as_box(), Offset::new(50.0, 50.0)),
915            (false, 0),
916            "no painter, no hit"
917        );
918
919        let foreground = Rc::new(Recorder {
920            hit: Some(true),
921            ..Recorder::new(BLUE)
922        });
923        custom.set_foreground_painter(&mut app, Some(foreground));
924        assert_eq!(
925            hit_test(&mut app, custom.as_box(), Offset::new(50.0, 50.0)),
926            (true, 1),
927            "a foreground painter answers for the children"
928        );
929    }
930}