Skip to main content

waft_widgets/widgets/
snapshot_widget.rs

1//! Flutter counterpart: `widgets/snapshot_widget.dart` (`SnapshotMode`, `SnapshotController`,
2//! `SnapshotWidget`, `_RenderSnapshotWidget`, `SnapshotPainter`, `_DefaultSnapshotPainter`).
3//!
4//! `OffsetLayer.toImageSync` is deferred, so the render object never takes a raster: where
5//! Flutter would rasterise the child and hand the image to
6//! [`SnapshotPainter::paint_snapshot`], the painter's [`paint`](SnapshotPainter::paint) paints
7//! the child live. The raster fields and the snapshot branch stay as Dart has them, empty until
8//! the raster lands; a later editor who fills `child_raster` must also restore Dart's
9//! `_paintAndDetachToImage`, with its platform-view check and [`SnapshotMode`] branches.
10
11use std::any::TypeId;
12use std::fmt::{self, Debug};
13use std::hash::Hash;
14
15use waft_embedder::valo::Sampling;
16use waft_embedder::{Image, Matrix4, Offset, Paint, Rect, Size, TextBaseline};
17use waft_foundation::{
18    App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Listenable, ListenableObject,
19    Listener, Retained,
20};
21use waft_painting::ClipContext;
22use waft_rendering::{
23    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, PaintingContext,
24    PipelineOwner, RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectBase,
25    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin,
26};
27
28use crate::framework::{
29    BuildContext, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, WidgetRef,
30};
31use crate::widgets::media_query::MediaQuery;
32use waft_foundation::Ref;
33
34/// Controls how the [`SnapshotWidget`] paints its child.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum SnapshotMode {
37    /// The child is snapshotted, but only if all descendants can be snapshotted.
38    ///
39    /// If there is a platform view in the children of a snapshot widget, the
40    /// snapshot will not be used and the child will be rendered using
41    /// [`SnapshotPainter::paint`]. This uses an un-snapshotted child and by default
42    /// paints it with no additional modification.
43    Permissive,
44
45    /// An error is thrown if the child cannot be snapshotted.
46    ///
47    /// This setting is the default state of the [`SnapshotWidget`].
48    Normal,
49
50    /// The child is snapshotted and any child platform views are ignored.
51    ///
52    /// This mode can be useful if there is a platform view descendant that does
53    /// not need to be included in the snapshot.
54    Forced,
55}
56
57/// A controller for the [`SnapshotWidget`] that controls when the child image is displayed
58/// and when to regenerated the child image.
59///
60/// When the value of [`allow_snapshotting`](Self::allow_snapshotting) is true, the
61/// [`SnapshotWidget`] will paint the child widgets based on the [`SnapshotMode`] of the
62/// snapshot widget.
63///
64/// The controller notifies its listeners when the value of
65/// [`allow_snapshotting`](Self::allow_snapshotting) changes or when [`clear`](Self::clear) is
66/// called.
67///
68/// To force [`SnapshotWidget`] to recreate the child image, call [`clear`](Self::clear).
69pub struct SnapshotController {
70    change_notifier: ChangeNotifierData,
71    allow_snapshotting: bool,
72}
73
74impl SnapshotController {
75    /// Create a new [`SnapshotController`].
76    ///
77    /// By default, [`allow_snapshotting`](Self::allow_snapshotting) is `false`: Dart's
78    /// `SnapshotController({bool allowSnapshotting = false})`.
79    pub fn new(app: &mut App, allow_snapshotting: bool) -> Ref<SnapshotController> {
80        app.create(SnapshotController {
81            change_notifier: ChangeNotifierData::new(),
82            allow_snapshotting,
83        })
84    }
85
86    /// Reset the snapshot held by any listening [`SnapshotWidget`].
87    ///
88    /// This has no effect if [`allow_snapshotting`](Self::allow_snapshotting) is `false`.
89    pub fn clear(self: Handle<Self>, app: &mut App) {
90        self.notify_listeners(app);
91    }
92
93    /// Whether a snapshot of this child widget is painted in its place.
94    pub fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
95        app.get(self).allow_snapshotting
96    }
97
98    /// Sets [`allow_snapshotting`](Self::allow_snapshotting).
99    pub fn set_allow_snapshotting(self: Handle<Self>, app: &mut App, value: bool) {
100        if value == self.allow_snapshotting(app) {
101            return;
102        }
103        app.get_mut(self).allow_snapshotting = value;
104        self.notify_listeners(app);
105    }
106
107    /// Discards any resources used by the object. Dart's inherited `ChangeNotifier.dispose`.
108    pub fn dispose(self: Handle<Self>, app: &mut App) {
109        ChangeNotifierData::dispose(app, self);
110    }
111}
112
113impl ChangeNotifier for SnapshotController {
114    fn change_notifier_data(&self) -> &ChangeNotifierData {
115        &self.change_notifier
116    }
117
118    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
119        &mut self.change_notifier
120    }
121}
122
123impl Debug for SnapshotController {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.debug_struct("SnapshotController")
126            .field("allow_snapshotting", &self.allow_snapshotting)
127            .finish()
128    }
129}
130
131/// A widget that can replace its child with a snapshotted version of the child.
132///
133/// A snapshot is a frozen texture-backed representation of all child pictures
134/// and layers stored as an [`Image`].
135///
136/// This widget is useful for performing short animations that would otherwise
137/// be expensive or that cannot rely on raster caching. For example, scale and
138/// skew animations are often expensive to perform on complex children, as are
139/// blurs. For a short animation, a widget that contains these expensive effects
140/// can be replaced with a snapshot of itself and manipulated instead.
141///
142/// For example, the Android Q `ZoomPageTransitionsBuilder` uses a snapshot widget
143/// for the forward and entering route to avoid the expensive scale animation.
144/// This also has the effect of briefly pausing any animations on the page.
145///
146/// Generally, this widget should not be used in places where users expect the
147/// child widget to continue animating or to be responsive, such as an unbounded
148/// animation.
149///
150/// Caveats:
151///
152/// * The contents of platform views cannot be captured by a snapshot
153///   widget. If a platform view is encountered, then the snapshot widget will
154///   determine how to render its children based on the [`SnapshotMode`]. This
155///   defaults to [`SnapshotMode::Normal`] which will throw an exception if a
156///   platform view is encountered.
157///
158/// * On the CanvasKit backend of Flutter, the performance of using this widget may regress
159///   performance due to the fact that both the UI and engine share a single thread.
160#[derive(Debug)]
161pub struct SnapshotWidget {
162    /// See [`Widget::key`](crate::Widget::key).
163    pub key: Option<KeyRef>,
164
165    /// The controller that determines when to display the children as a snapshot.
166    pub controller: Ref<SnapshotController>,
167
168    /// Configuration that controls how the snapshot widget decides to paint its children.
169    ///
170    /// Defaults to [`SnapshotMode::Normal`], which throws an error when a platform view
171    /// or texture view is encountered.
172    ///
173    /// See [`SnapshotMode`] for more information.
174    pub mode: SnapshotMode,
175
176    /// Whether or not changes in render object size should automatically re-create
177    /// the snapshot.
178    ///
179    /// Defaults to false.
180    pub autoresize: bool,
181
182    /// The painter used to paint the child snapshot or child widgets.
183    ///
184    /// `None` is Dart's default, `const _DefaultSnapshotPainter()`: one painter per app,
185    /// reached through [`effective_painter`](Self::effective_painter), which paints the child
186    /// exactly as it would paint itself.
187    pub painter: Option<SnapshotPainterRef>,
188
189    /// The widget below this widget in the tree.
190    pub child: Option<WidgetRef>,
191}
192
193impl SnapshotWidget {
194    /// Create a new [`SnapshotWidget`].
195    ///
196    /// The [`controller`](Self::controller) and [`child`](Self::child) arguments are required;
197    /// Dart's `child` is required but nullable.
198    pub fn new(controller: Ref<SnapshotController>, child: Option<WidgetRef>) -> SnapshotWidget {
199        SnapshotWidget {
200            key: None,
201            controller,
202            mode: SnapshotMode::Normal,
203            autoresize: false,
204            painter: None,
205            child,
206        }
207    }
208
209    /// Dart `SnapshotWidget(key:)`.
210    pub fn key(mut self, key: KeyRef) -> SnapshotWidget {
211        self.key = Some(key);
212        self
213    }
214
215    /// Dart `SnapshotWidget(mode:)`.
216    pub fn mode(mut self, mode: SnapshotMode) -> SnapshotWidget {
217        self.mode = mode;
218        self
219    }
220
221    /// Dart `SnapshotWidget(painter:)`.
222    pub fn painter(mut self, painter: SnapshotPainterRef) -> SnapshotWidget {
223        self.painter = Some(painter);
224        self
225    }
226
227    /// Dart `SnapshotWidget(autoresize:)`.
228    pub fn autoresize(mut self, autoresize: bool) -> SnapshotWidget {
229        self.autoresize = autoresize;
230        self
231    }
232
233    /// Dart's `painter` field: the given painter, or the app's one default painter.
234    pub fn effective_painter(&self, app: &mut App) -> SnapshotPainterRef {
235        self.painter.clone().unwrap_or_else(|| {
236            app.singleton::<DefaultSnapshotPainter>()
237                .keep(app)
238                .into_erased()
239        })
240    }
241}
242
243impl RenderObjectWidget for SnapshotWidget {
244    type RenderObject = RenderSnapshotWidget;
245
246    fn key(&self) -> Option<&KeyRef> {
247        self.key.as_ref()
248    }
249
250    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
251        let device_pixel_ratio = MediaQuery::device_pixel_ratio_of(app, context);
252        let painter = self.effective_painter(app);
253        RenderSnapshotWidget::new(
254            app,
255            device_pixel_ratio,
256            self.controller.clone(),
257            self.mode,
258            painter,
259            self.autoresize,
260        )
261        .as_object()
262    }
263
264    fn update_render_object(
265        &self,
266        app: &mut App,
267        context: BuildContext,
268        render_object: RenderHandle<RenderSnapshotWidget>,
269    ) {
270        render_object.set_controller(app, self.controller.clone());
271        render_object.set_mode(app, self.mode);
272        let device_pixel_ratio = MediaQuery::device_pixel_ratio_of(app, context);
273        render_object.set_device_pixel_ratio(app, device_pixel_ratio);
274        let painter = self.effective_painter(app);
275        render_object.set_painter(app, painter);
276        render_object.set_autoresize(app, self.autoresize);
277    }
278}
279
280impl SingleChildRenderObjectWidget for SnapshotWidget {
281    fn child(&self) -> Option<&WidgetRef> {
282        self.child.as_ref()
283    }
284}
285
286/// A render object that conditionally converts its child into an [`Image`]
287/// and then paints it in place of the child.
288///
289/// Flutter's private `_RenderSnapshotWidget`.
290pub struct RenderSnapshotWidget {
291    render_object: RenderObjectData,
292    render_box: RenderBoxData,
293    child: RenderObjectWithChildData<AnyRenderBox>,
294    device_pixel_ratio: f64,
295    painter: SnapshotPainterRef,
296    controller: Ref<SnapshotController>,
297    mode: SnapshotMode,
298    autoresize: bool,
299    /// Always `None` until `OffsetLayer.toImageSync` lands (see the module docs).
300    child_raster: Option<Image>,
301    child_raster_size: Option<Size>,
302    /// Set to true if the snapshot mode was not forced and a platform view
303    /// was encountered while attempting to snapshot the child.
304    disable_snapshot_attempt: bool,
305    last_cached_size: Option<Size>,
306}
307
308impl RenderSnapshotWidget {
309    /// Create a new [`RenderSnapshotWidget`].
310    fn new(
311        app: &mut App,
312        device_pixel_ratio: f64,
313        controller: Ref<SnapshotController>,
314        mode: SnapshotMode,
315        painter: SnapshotPainterRef,
316        autoresize: bool,
317    ) -> RenderHandle<RenderSnapshotWidget> {
318        RenderHandle::new_box(
319            app,
320            RenderSnapshotWidget {
321                render_object: RenderObjectData::new(),
322                render_box: RenderBoxData::new(),
323                child: RenderObjectWithChildData::new(),
324                device_pixel_ratio,
325                painter,
326                controller,
327                mode,
328                autoresize,
329                child_raster: None,
330                child_raster_size: None,
331                disable_snapshot_attempt: false,
332                last_cached_size: None,
333            },
334        )
335    }
336
337    /// The device pixel ratio used to create the child image.
338    pub fn device_pixel_ratio(self: RenderHandle<Self>, app: &App) -> f64 {
339        self.get(app).device_pixel_ratio
340    }
341
342    /// Sets [`device_pixel_ratio`](Self::device_pixel_ratio).
343    pub fn set_device_pixel_ratio(self: RenderHandle<Self>, app: &mut App, value: f64) {
344        if value == self.device_pixel_ratio(app) {
345            return;
346        }
347        self.get_mut(app).device_pixel_ratio = value;
348        if self.get(app).child_raster.is_none() {
349            return;
350        }
351        self.get_mut(app).child_raster = None;
352        self.mark_needs_paint(app);
353    }
354
355    /// The painter used to paint the child snapshot or child widgets.
356    pub fn painter(self: RenderHandle<Self>, app: &App) -> AnySnapshotPainter {
357        self.get(app).painter.handle()
358    }
359
360    /// Sets [`painter`](Self::painter).
361    pub fn set_painter(self: RenderHandle<Self>, app: &mut App, value: SnapshotPainterRef) {
362        if value == self.painter(app) {
363            return;
364        }
365        let old_painter = self.painter(app);
366        old_painter.remove_listener(app, &self.paint_listener());
367        self.get_mut(app).painter = value;
368        let painter = self.painter(app);
369        if old_painter.runtime_type() != painter.runtime_type()
370            || painter.should_repaint(app, old_painter)
371        {
372            self.mark_needs_paint(app);
373        }
374        if self.attached(app) {
375            painter.add_listener(app, self.paint_listener());
376        }
377    }
378
379    /// A controller that determines whether to paint the child normally or to
380    /// paint a snapshotted version of that child.
381    pub fn controller(self: RenderHandle<Self>, app: &App) -> Handle<SnapshotController> {
382        self.get(app).controller.handle()
383    }
384
385    /// Sets [`controller`](Self::controller).
386    pub fn set_controller(self: RenderHandle<Self>, app: &mut App, value: Ref<SnapshotController>) {
387        if value == self.controller(app) {
388            return;
389        }
390        self.controller(app)
391            .remove_listener(app, &self.raster_value_changed_listener());
392        let old_value = self.controller(app).allow_snapshotting(app);
393        self.get_mut(app).controller = value;
394        if self.attached(app) {
395            self.controller(app)
396                .add_listener(app, self.raster_value_changed_listener());
397            if old_value != self.controller(app).allow_snapshotting(app) {
398                self.on_raster_value_changed(app);
399            }
400        }
401    }
402
403    /// How the snapshot widget will handle platform views in child layers.
404    pub fn mode(self: RenderHandle<Self>, app: &App) -> SnapshotMode {
405        self.get(app).mode
406    }
407
408    /// Sets [`mode`](Self::mode).
409    pub fn set_mode(self: RenderHandle<Self>, app: &mut App, value: SnapshotMode) {
410        if value == self.mode(app) {
411            return;
412        }
413        self.get_mut(app).mode = value;
414        self.mark_needs_paint(app);
415    }
416
417    /// Whether or not changes in render object size should automatically re-rasterize.
418    pub fn autoresize(self: RenderHandle<Self>, app: &App) -> bool {
419        self.get(app).autoresize
420    }
421
422    /// Sets [`autoresize`](Self::autoresize).
423    pub fn set_autoresize(self: RenderHandle<Self>, app: &mut App, value: bool) {
424        if value == self.autoresize(app) {
425            return;
426        }
427        self.get_mut(app).autoresize = value;
428        self.mark_needs_paint(app);
429    }
430
431    /// Dart's `_onRasterValueChanged`.
432    fn on_raster_value_changed(self: RenderHandle<Self>, app: &mut App) {
433        self.get_mut(app).disable_snapshot_attempt = false;
434        self.clear_child_raster(app);
435        self.mark_needs_paint(app);
436    }
437
438    /// Dart's `_childRaster?.dispose(); _childRaster = null; _childRasterSize = null;`.
439    fn clear_child_raster(self: RenderHandle<Self>, app: &mut App) {
440        let this = self.get_mut(app);
441        this.child_raster = None;
442        this.child_raster_size = None;
443    }
444
445    /// The `markNeedsPaint` tear-off, equal to itself across registrations.
446    fn paint_listener(self: RenderHandle<Self>) -> Listener {
447        Listener::handle_method(self.handle(), mark_needs_paint)
448    }
449
450    /// The `_onRasterValueChanged` tear-off, equal to itself across registrations.
451    fn raster_value_changed_listener(self: RenderHandle<Self>) -> Listener {
452        Listener::handle_method(self.handle(), on_raster_value_changed)
453    }
454
455    /// Dart's `painter.paint(context, offset, size, super.paint)`: the painter paints the child
456    /// live, through the proxy box's own paint.
457    fn paint_with_painter(
458        self: RenderHandle<Self>,
459        app: &mut App,
460        context: &mut PaintingContext,
461        offset: Offset,
462    ) {
463        let size = self.size(app);
464        self.painter(app)
465            .paint(app, context, offset, size, &mut |app, context, offset| {
466                RenderProxyBoxMixin::paint(self, app, context, offset)
467            });
468    }
469}
470
471fn mark_needs_paint(this: Handle<RenderSnapshotWidget>, app: &mut App) {
472    RenderHandle::from_handle(this).mark_needs_paint(app);
473}
474
475fn on_raster_value_changed(this: Handle<RenderSnapshotWidget>, app: &mut App) {
476    RenderHandle::from_handle(this).on_raster_value_changed(app);
477}
478
479impl RenderObjectWithChildMixin for RenderSnapshotWidget {
480    type ChildType = AnyRenderBox;
481
482    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
483        &self.get(app).child
484    }
485
486    fn child_data_mut(
487        self: RenderHandle<Self>,
488        app: &mut App,
489    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
490        &mut self.get_mut(app).child
491    }
492}
493
494impl RenderProxyBoxMixin for RenderSnapshotWidget {}
495
496impl RenderObject for RenderSnapshotWidget {
497    waft_rendering::render_object_accessors!();
498
499    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
500        self.controller(app)
501            .add_listener(app, self.raster_value_changed_listener());
502        self.painter(app).add_listener(app, self.paint_listener());
503        if let Some(child) = self.child(app) {
504            child.as_object().attach(app, owner);
505        }
506    }
507
508    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
509        self.get_mut(app).disable_snapshot_attempt = false;
510        self.controller(app)
511            .remove_listener(app, &self.raster_value_changed_listener());
512        self.painter(app)
513            .remove_listener(app, &self.paint_listener());
514        self.clear_child_raster(app);
515        if let Some(child) = self.child(app) {
516            child.as_object().detach(app);
517        }
518    }
519
520    fn dispose(self: RenderHandle<Self>, app: &mut App) {
521        self.controller(app)
522            .remove_listener(app, &self.raster_value_changed_listener());
523        self.painter(app)
524            .remove_listener(app, &self.paint_listener());
525        self.clear_child_raster(app);
526        RenderObjectBase::dispose(self, app);
527    }
528
529    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
530        RenderProxyBoxMixin::perform_layout(self, app);
531    }
532
533    fn paint(
534        self: RenderHandle<Self>,
535        app: &mut App,
536        context: &mut PaintingContext,
537        offset: Offset,
538    ) {
539        let size = self.size(app);
540        if size.is_empty() {
541            self.clear_child_raster(app);
542            return;
543        }
544        if !self.controller(app).allow_snapshotting(app) || self.get(app).disable_snapshot_attempt {
545            self.clear_child_raster(app);
546            self.paint_with_painter(app, context, offset);
547            return;
548        }
549
550        let this = self.get(app);
551        if this.autoresize && Some(size) != this.last_cached_size && this.last_cached_size.is_some()
552        {
553            self.get_mut(app).child_raster = None;
554        }
555
556        // Dart rasterises the child here (`_paintAndDetachToImage`); without
557        // `OffsetLayer.toImageSync` no raster is taken, so the painter paints the child live.
558        let this = self.get(app);
559        match (this.child_raster.clone(), this.child_raster_size) {
560            (Some(child_raster), Some(child_raster_size)) => {
561                let device_pixel_ratio = this.device_pixel_ratio;
562                self.painter(app).paint_snapshot(
563                    app,
564                    context,
565                    offset,
566                    size,
567                    &child_raster,
568                    child_raster_size,
569                    device_pixel_ratio,
570                );
571            }
572            _ => self.paint_with_painter(app, context, offset),
573        }
574    }
575
576    fn visit_children(
577        self: RenderHandle<Self>,
578        app: &App,
579        visitor: &mut dyn FnMut(AnyRenderObject),
580    ) {
581        if let Some(child) = self.child(app) {
582            visitor(child.as_object());
583        }
584    }
585}
586
587impl RenderBox for RenderSnapshotWidget {
588    waft_rendering::render_box_accessors!();
589
590    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
591        RenderProxyBoxMixin::setup_parent_data(self, app, child);
592    }
593
594    fn apply_paint_transform(
595        self: RenderHandle<Self>,
596        app: &App,
597        child: AnyRenderObject,
598        transform: &mut Matrix4,
599    ) {
600        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
601    }
602
603    fn hit_test_children(
604        self: RenderHandle<Self>,
605        app: &mut App,
606        result: &mut BoxHitTestResult<'_>,
607        position: Offset,
608    ) -> bool {
609        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
610    }
611
612    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
613        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
614    }
615
616    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
617        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
618    }
619
620    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
621        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
622    }
623
624    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
625        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
626    }
627
628    fn compute_distance_to_actual_baseline(
629        self: RenderHandle<Self>,
630        app: &mut App,
631        baseline: TextBaseline,
632    ) -> Option<f64> {
633        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
634    }
635
636    fn compute_dry_baseline(
637        self: RenderHandle<Self>,
638        app: &mut App,
639        constraints: BoxConstraints,
640        baseline: TextBaseline,
641    ) -> Option<f64> {
642        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
643    }
644
645    fn compute_dry_layout(
646        self: RenderHandle<Self>,
647        app: &mut App,
648        constraints: BoxConstraints,
649    ) -> Size {
650        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
651    }
652}
653
654/// A painter used to paint either a snapshot or the child widgets that
655/// would be a snapshot.
656///
657/// The painter can call `notify_listeners` to have the [`SnapshotWidget`]
658/// re-paint (re-using the same raster). This allows animations to be performed
659/// without re-snapshotting of children. For certain scale or perspective changing
660/// transforms, such as a rotation, this can be significantly faster than performing
661/// the same animation at the widget level.
662///
663/// By default, the [`SnapshotWidget`] includes a delegate that draws the child raster
664/// exactly as the child widgets would have been drawn. Nevertheless, this can
665/// also be used to efficiently transform the child raster and apply complex paint
666/// effects.
667///
668/// Dart's abstract `SnapshotPainter extends ChangeNotifier`: a painter is an arena object that
669/// holds [`ChangeNotifierData`] and implements [`ChangeNotifier`], which gives it the
670/// [`ListenableObject`] side this trait asks for; the default painter implements that side
671/// itself, as Dart's `_DefaultSnapshotPainter implements SnapshotPainter` does.
672pub trait SnapshotPainter: ListenableObject {
673    /// Called whenever the `image` that represents a [`SnapshotWidget`]s child should be
674    /// painted.
675    ///
676    /// The image is rasterized at the physical pixel resolution and should be scaled down by
677    /// `pixel_ratio` to account for device independent pixels.
678    ///
679    /// The default painter paints the snapshot accounting for the fact that the image width
680    /// and height will be given in physical pixels, while the image must be painted with
681    /// device independent pixels. That is, the width and height of the image is the widget and
682    /// height of the provided `size`, multiplied by the `pixel_ratio`. In addition, the actual
683    /// size of the scene captured by the `image` is not the image's width or height, but
684    /// indeed `source_size`, because the former is a rounded inaccurate integer.
685    #[allow(clippy::too_many_arguments)]
686    fn paint_snapshot(
687        self: Handle<Self>,
688        app: &mut App,
689        context: &mut PaintingContext,
690        offset: Offset,
691        size: Size,
692        image: &Image,
693        source_size: Size,
694        pixel_ratio: f64,
695    );
696
697    /// Paint the child via `painter`, applying any effects that would have been painted
698    /// in [`paint_snapshot`](Self::paint_snapshot).
699    ///
700    /// This method is called when snapshotting is disabled, or when
701    /// [`SnapshotMode::Permissive`] is used and a child platform view prevents snapshotting.
702    ///
703    /// The `offset` and `size` are the location and dimensions of the render object.
704    fn paint(
705        self: Handle<Self>,
706        app: &mut App,
707        context: &mut PaintingContext,
708        offset: Offset,
709        size: Size,
710        painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
711    );
712
713    /// Called whenever a new instance of the snapshot widget delegate class is
714    /// provided to the [`SnapshotWidget`] object, or any time that a new
715    /// [`SnapshotPainter`] object is created with a new instance of the
716    /// delegate class (which amounts to the same thing, because the latter is
717    /// implemented in terms of the former).
718    ///
719    /// If the new instance represents different information than the old
720    /// instance, then the method should return true, otherwise it should return
721    /// false.
722    ///
723    /// If the method returns false, then the [`paint`](Self::paint) call might be optimized
724    /// away.
725    ///
726    /// It's possible that the [`paint`](Self::paint) method will get called even if
727    /// [`should_repaint`](Self::should_repaint) returns false (e.g. if an ancestor or
728    /// descendant needed to be repainted). It's also possible that the [`paint`](Self::paint)
729    /// method will get called without [`should_repaint`](Self::should_repaint) being called at
730    /// all (e.g. if the box changes size).
731    ///
732    /// Changing the delegate will not cause the child image retained by the
733    /// [`SnapshotWidget`] to be updated. Instead, [`SnapshotController::clear`] can
734    /// be used to force the generation of a new image.
735    ///
736    /// The `old_painter` argument is of the same type as this painter: Dart's `covariant`
737    /// parameter, reached with [`AnySnapshotPainter::downcast`].
738    fn should_repaint(self: Handle<Self>, app: &App, old_painter: AnySnapshotPainter) -> bool;
739
740    /// The type-erased `SnapshotPainter` handle. Free: the vtable is a `const`, and the id is
741    /// copied.
742    fn as_snapshot_painter(self: Handle<Self>) -> AnySnapshotPainter {
743        AnySnapshotPainter {
744            id: self.id(),
745            vtable: const { &SnapshotPainterVTable::of::<Self>() },
746        }
747    }
748}
749
750/// The dispatch signature of [`SnapshotPainter::paint_snapshot`].
751type PaintSnapshotFn =
752    fn(&mut App, HandleId, &mut PaintingContext, Offset, Size, &Image, Size, f64);
753
754/// The dispatch signature of [`SnapshotPainter::paint`].
755type PaintFn = fn(
756    &mut App,
757    HandleId,
758    &mut PaintingContext,
759    Offset,
760    Size,
761    &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
762);
763
764/// The vtable of an erased [`AnySnapshotPainter`]: one `&'static` table per concrete
765/// [`SnapshotPainter`] type.
766struct SnapshotPainterVTable {
767    runtime_type: fn() -> TypeId,
768    type_name: fn() -> &'static str,
769    add_listener: fn(&mut App, HandleId, Listener),
770    remove_listener: fn(&mut App, HandleId, &Listener),
771    paint_snapshot: PaintSnapshotFn,
772    paint: PaintFn,
773    should_repaint: fn(&App, HandleId, AnySnapshotPainter) -> bool,
774}
775
776/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
777fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
778    Handle::from_id(id)
779}
780
781impl SnapshotPainterVTable {
782    const fn of<T: SnapshotPainter>() -> SnapshotPainterVTable {
783        SnapshotPainterVTable {
784            runtime_type: TypeId::of::<T>,
785            type_name: std::any::type_name::<T>,
786            add_listener: |app, id, listener| {
787                ListenableObject::add_listener(resolve::<T>(id), app, listener)
788            },
789            remove_listener: |app, id, listener| {
790                ListenableObject::remove_listener(resolve::<T>(id), app, listener)
791            },
792            paint_snapshot: |app, id, context, offset, size, image, source_size, pixel_ratio| {
793                T::paint_snapshot(
794                    resolve(id),
795                    app,
796                    context,
797                    offset,
798                    size,
799                    image,
800                    source_size,
801                    pixel_ratio,
802                )
803            },
804            paint: |app, id, context, offset, size, painter| {
805                T::paint(resolve(id), app, context, offset, size, painter)
806            },
807            should_repaint: |app, id, old_painter| T::should_repaint(resolve(id), app, old_painter),
808        }
809    }
810}
811
812/// Erased [`SnapshotPainter`]: what a field or parameter Dart types as `SnapshotPainter`
813/// becomes.
814///
815/// Equality is Dart's `==` on an object reference.
816#[derive(Clone, Copy)]
817pub struct AnySnapshotPainter {
818    id: HandleId,
819    vtable: &'static SnapshotPainterVTable,
820}
821
822/// A field Dart types as the erased object, kept: AnySnapshotPainter with its count.
823pub type SnapshotPainterRef = Retained<AnySnapshotPainter>;
824
825waft_foundation::erased_handle!(AnySnapshotPainter: SnapshotPainter => SnapshotPainter::as_snapshot_painter);
826
827impl AnySnapshotPainter {
828    /// The arena id behind this handle.
829    pub fn id(self) -> HandleId {
830        self.id
831    }
832
833    /// Dart's `runtimeType`.
834    pub fn runtime_type(self) -> TypeId {
835        (self.vtable.runtime_type)()
836    }
837
838    /// Dart's `painter as P`: the typed handle when this painter is a `P`, else `None`.
839    pub fn downcast<P: 'static>(self, app: &App) -> Option<Handle<P>> {
840        app.handle::<P>(self.id)
841    }
842
843    /// See [`SnapshotPainter::paint_snapshot`].
844    #[allow(clippy::too_many_arguments)]
845    pub fn paint_snapshot(
846        self,
847        app: &mut App,
848        context: &mut PaintingContext,
849        offset: Offset,
850        size: Size,
851        image: &Image,
852        source_size: Size,
853        pixel_ratio: f64,
854    ) {
855        (self.vtable.paint_snapshot)(
856            app,
857            self.id,
858            context,
859            offset,
860            size,
861            image,
862            source_size,
863            pixel_ratio,
864        )
865    }
866
867    /// See [`SnapshotPainter::paint`].
868    pub fn paint(
869        self,
870        app: &mut App,
871        context: &mut PaintingContext,
872        offset: Offset,
873        size: Size,
874        painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
875    ) {
876        (self.vtable.paint)(app, self.id, context, offset, size, painter)
877    }
878
879    /// See [`SnapshotPainter::should_repaint`].
880    pub fn should_repaint(self, app: &App, old_painter: AnySnapshotPainter) -> bool {
881        (self.vtable.should_repaint)(app, self.id, old_painter)
882    }
883}
884
885impl Debug for AnySnapshotPainter {
886    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
887        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
888    }
889}
890
891impl Listenable for AnySnapshotPainter {
892    fn add_listener(&self, app: &mut App, listener: Listener) {
893        (self.vtable.add_listener)(app, self.id, listener)
894    }
895
896    fn remove_listener(&self, app: &mut App, listener: &Listener) {
897        (self.vtable.remove_listener)(app, self.id, listener)
898    }
899}
900
901/// Flutter's private `_DefaultSnapshotPainter`: paints the child as it would paint itself, and
902/// the snapshot exactly over the render object. It never notifies, so it keeps no listeners.
903///
904/// Dart's `const` constructor makes every default painter one object; here it is the app's
905/// singleton.
906#[derive(Debug, Default)]
907struct DefaultSnapshotPainter;
908
909impl ListenableObject for DefaultSnapshotPainter {
910    fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}
911
912    fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
913}
914
915impl SnapshotPainter for DefaultSnapshotPainter {
916    fn paint(
917        self: Handle<Self>,
918        app: &mut App,
919        context: &mut PaintingContext,
920        offset: Offset,
921        _size: Size,
922        painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
923    ) {
924        painter(app, context, offset);
925    }
926
927    fn paint_snapshot(
928        self: Handle<Self>,
929        _app: &mut App,
930        context: &mut PaintingContext,
931        offset: Offset,
932        size: Size,
933        image: &Image,
934        source_size: Size,
935        _pixel_ratio: f64,
936    ) {
937        let src = Rect::from_ltwh(0.0, 0.0, source_size.width(), source_size.height());
938        let dst = Rect::from_ltwh(offset.dx(), offset.dy(), size.width(), size.height());
939        // Valo's default sampling, linear with linear mipmaps, is Dart's `FilterQuality.medium`.
940        let sampling = Sampling::default();
941        context.canvas().draw_image_rect(
942            image,
943            src.into(),
944            dst.into(),
945            sampling,
946            &Paint::default(),
947        );
948    }
949
950    fn should_repaint(self: Handle<Self>, _app: &App, _old_painter: AnySnapshotPainter) -> bool {
951        false
952    }
953}
954
955#[cfg(test)]
956mod tests {
957    use std::any::Any;
958    use std::cell::{Cell, RefCell};
959    use std::marker::PhantomData;
960    use std::rc::Rc;
961    use waft_foundation::Ref;
962
963    use waft_embedder::{Canvas, Color};
964    use waft_foundation::AppCell;
965    use waft_painting::TextDirection;
966    use waft_rendering::{
967        AnyLayer, CustomPainter, LayerHandle, OpacityLayer, PictureLayer, TransformLayer,
968    };
969
970    use super::*;
971    use crate::framework::IntoWidget;
972    use crate::test_harness::Harness;
973    use crate::widgets::basic::{
974        Center, CustomPaint, Directionality, RepaintBoundary, SizedBox, StateSetter,
975        StatefulBuilder,
976    };
977    use crate::widgets::container::Container;
978    use crate::widgets::media_query::MediaQueryData;
979
980    const YELLOW: Color = Color::new(0xFFAABB11);
981
982    struct First;
983    struct Second;
984
985    /// Flutter's `TestPainter`, and with `Second` its `TestPainter2`: a painter of another
986    /// runtime type that behaves the same.
987    struct TestPainterOf<M: 'static> {
988        change_notifier: ChangeNotifierData,
989        count: u32,
990        should_repaint_value: bool,
991        last_image: Option<Image>,
992        added_listener_count: u32,
993        removed_listener_count: u32,
994        marker: PhantomData<M>,
995    }
996
997    type TestPainter = TestPainterOf<First>;
998    type TestPainter2 = TestPainterOf<Second>;
999
1000    impl<M: 'static> TestPainterOf<M> {
1001        fn new(app: &mut App) -> Ref<TestPainterOf<M>> {
1002            app.create(TestPainterOf {
1003                change_notifier: ChangeNotifierData::new(),
1004                count: 0,
1005                should_repaint_value: false,
1006                last_image: None,
1007                added_listener_count: 0,
1008                removed_listener_count: 0,
1009                marker: PhantomData,
1010            })
1011        }
1012    }
1013
1014    impl<M: 'static> ChangeNotifier for TestPainterOf<M> {
1015        fn change_notifier_data(&self) -> &ChangeNotifierData {
1016            &self.change_notifier
1017        }
1018
1019        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1020            &mut self.change_notifier
1021        }
1022
1023        fn will_add_listener(self: Handle<Self>, app: &mut App) {
1024            app.get_mut(self).added_listener_count += 1;
1025        }
1026
1027        fn did_remove_listener(self: Handle<Self>, app: &mut App) {
1028            app.get_mut(self).removed_listener_count += 1;
1029        }
1030    }
1031
1032    impl<M: 'static> SnapshotPainter for TestPainterOf<M> {
1033        fn paint_snapshot(
1034            self: Handle<Self>,
1035            app: &mut App,
1036            _context: &mut PaintingContext,
1037            _offset: Offset,
1038            _size: Size,
1039            image: &Image,
1040            _source_size: Size,
1041            _pixel_ratio: f64,
1042        ) {
1043            let this = app.get_mut(self);
1044            this.count += 1;
1045            this.last_image = Some(image.clone());
1046        }
1047
1048        fn paint(
1049            self: Handle<Self>,
1050            app: &mut App,
1051            _context: &mut PaintingContext,
1052            _offset: Offset,
1053            _size: Size,
1054            _painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
1055        ) {
1056            app.get_mut(self).count += 1;
1057        }
1058
1059        fn should_repaint(self: Handle<Self>, app: &App, old_painter: AnySnapshotPainter) -> bool {
1060            debug_assert!(old_painter.downcast::<Self>(app).is_some());
1061            app.get(self).should_repaint_value
1062        }
1063    }
1064
1065    /// The shape of Material's zoom painters: the child painted through a transform and an
1066    /// opacity layer the painter keeps across paints.
1067    struct LayeredPainter {
1068        change_notifier: ChangeNotifierData,
1069        opacity_handle: LayerHandle<Handle<OpacityLayer>>,
1070        transform_handle: LayerHandle<Handle<TransformLayer>>,
1071    }
1072
1073    impl ChangeNotifier for LayeredPainter {
1074        fn change_notifier_data(&self) -> &ChangeNotifierData {
1075            &self.change_notifier
1076        }
1077
1078        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1079            &mut self.change_notifier
1080        }
1081    }
1082
1083    impl SnapshotPainter for LayeredPainter {
1084        fn paint_snapshot(
1085            self: Handle<Self>,
1086            _app: &mut App,
1087            _context: &mut PaintingContext,
1088            _offset: Offset,
1089            _size: Size,
1090            _image: &Image,
1091            _source_size: Size,
1092            _pixel_ratio: f64,
1093        ) {
1094        }
1095
1096        fn paint(
1097            self: Handle<Self>,
1098            app: &mut App,
1099            context: &mut PaintingContext,
1100            offset: Offset,
1101            _size: Size,
1102            painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
1103        ) {
1104            let old_transform = app.get(self).transform_handle.layer();
1105            let transform = context.push_transform(
1106                app,
1107                true,
1108                offset,
1109                Matrix4::IDENTITY,
1110                |app, context, offset| {
1111                    let old_opacity = app.get(self).opacity_handle.layer();
1112                    let opacity = context.push_opacity(app, offset, 128, painter, old_opacity);
1113                    LayerHandle::set_layer(
1114                        app,
1115                        |app| &mut app.get_mut(self).opacity_handle,
1116                        Some(opacity),
1117                    );
1118                },
1119                old_transform,
1120            );
1121            LayerHandle::set_layer(
1122                app,
1123                |app| &mut app.get_mut(self).transform_handle,
1124                transform,
1125            );
1126        }
1127
1128        fn should_repaint(
1129            self: Handle<Self>,
1130            _app: &App,
1131            _old_painter: AnySnapshotPainter,
1132        ) -> bool {
1133            false
1134        }
1135    }
1136
1137    /// Counts the paints of the child it stands in for.
1138    struct ChildPaints(Rc<Cell<u32>>);
1139
1140    impl CustomPainter for ChildPaints {
1141        fn paint(&self, _app: &mut App, _canvas: &mut Canvas, _size: Size) {
1142            self.0.set(self.0.get() + 1);
1143        }
1144
1145        fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
1146            false
1147        }
1148
1149        fn as_any(&self) -> &dyn Any {
1150            self
1151        }
1152    }
1153
1154    /// Flutter's `TestDependencies`: a text direction and a media query of `device_pixel_ratio`.
1155    fn test_dependencies<K>(device_pixel_ratio: f64, child: impl IntoWidget<K>) -> WidgetRef {
1156        let query = MediaQuery::new(
1157            MediaQueryData::new().device_pixel_ratio(device_pixel_ratio),
1158            child,
1159        )
1160        .into_widget();
1161        Directionality::new(TextDirection::Ltr, query).into_widget()
1162    }
1163
1164    /// A centred 100 x 100 box under a snapshot widget.
1165    fn centered(snapshot: SnapshotWidget) -> WidgetRef {
1166        Center::new()
1167            .child(test_dependencies(1.0, snapshot))
1168            .into_widget()
1169    }
1170
1171    fn sized_box(width: f64, height: f64) -> Option<WidgetRef> {
1172        Some(SizedBox::new().width(width).height(height).into_widget())
1173    }
1174
1175    /// Flutter's `tester.layers`: the layer tree from the root, depth first.
1176    fn layers(app: &App, harness: &Harness) -> Vec<AnyLayer> {
1177        harness.layers(app)
1178    }
1179
1180    #[test]
1181    fn changing_the_device_pixel_ratio_does_not_repaint_if_snapshotting_is_not_enabled() {
1182        let cell = AppCell::new();
1183        let mut app = cell.borrow_mut();
1184        let controller = SnapshotController::new(&mut app, false);
1185        let painter = TestPainter::new(&mut app);
1186        let device_pixel_ratio = Rc::new(Cell::new(1.0));
1187        let local_set_state: Rc<RefCell<Option<StateSetter>>> = Rc::default();
1188        let harness = Harness::mount(
1189            &mut app,
1190            StatefulBuilder::new({
1191                let (device_pixel_ratio, local_set_state) =
1192                    (Rc::clone(&device_pixel_ratio), Rc::clone(&local_set_state));
1193                let painter = painter.clone();
1194                move |_app, _context, set_state| {
1195                    *local_set_state.borrow_mut() = Some(set_state);
1196                    Center::new()
1197                        .child(test_dependencies(
1198                            device_pixel_ratio.get(),
1199                            SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
1200                                .painter(painter.erase()),
1201                        ))
1202                        .into_widget()
1203                }
1204            })
1205            .into_widget(),
1206        );
1207        harness.pump(&mut app);
1208        assert_eq!(app.get(&painter).count, 1);
1209
1210        let set_state = local_set_state.borrow().clone().expect("the builder ran");
1211        set_state(&mut app, &mut |_app| device_pixel_ratio.set(2.0));
1212        harness.pump(&mut app);
1213
1214        // Not repainted as dpr was not used.
1215        assert_eq!(app.get(&painter).count, 1);
1216    }
1217
1218    #[test]
1219    fn the_snapshot_widget_paints_its_child_as_a_single_picture_layer() {
1220        let cell = AppCell::new();
1221        let mut app = cell.borrow_mut();
1222        let controller = SnapshotController::new(&mut app, true);
1223        let child = Container::new().width(100.0).height(100.0).color(YELLOW);
1224        let harness = Harness::mount(
1225            &mut app,
1226            RepaintBoundary::new()
1227                .child(centered(SnapshotWidget::new(
1228                    controller.clone(),
1229                    Some(child.into_widget()),
1230                )))
1231                .into_widget(),
1232        );
1233        harness.pump(&mut app);
1234
1235        let found = layers(&app, &harness);
1236        assert_eq!(found.len(), 3);
1237        assert!(app.handle::<PictureLayer>(found[2].id()).is_some());
1238
1239        controller.set_allow_snapshotting(&mut app, false);
1240        harness.pump(&mut app);
1241
1242        let found = layers(&app, &harness);
1243        assert_eq!(found.len(), 3);
1244        assert!(app.handle::<PictureLayer>(found[2].id()).is_some());
1245    }
1246
1247    #[test]
1248    fn the_snapshot_widget_can_update_the_painter_type() {
1249        let cell = AppCell::new();
1250        let mut app = cell.borrow_mut();
1251        let controller = SnapshotController::new(&mut app, true);
1252        let painter1 = TestPainter::new(&mut app);
1253        let painter2 = TestPainter2::new(&mut app);
1254        let harness = Harness::mount(
1255            &mut app,
1256            centered(
1257                SnapshotWidget::new(controller.clone(), Some(SizedBox::new().into_widget()))
1258                    .painter(painter1.erase()),
1259            ),
1260        );
1261        harness.pump(&mut app);
1262
1263        harness.set_child(
1264            &mut app,
1265            centered(
1266                SnapshotWidget::new(controller.clone(), Some(SizedBox::new().into_widget()))
1267                    .painter(painter2.erase()),
1268            ),
1269        );
1270        harness.pump(&mut app);
1271    }
1272
1273    #[test]
1274    fn a_child_with_an_empty_size_does_not_fail_to_paint() {
1275        let cell = AppCell::new();
1276        let mut app = cell.borrow_mut();
1277        let controller = SnapshotController::new(&mut app, true);
1278        let painter = TestPainter::new(&mut app);
1279        let harness = Harness::mount(
1280            &mut app,
1281            centered(
1282                SnapshotWidget::new(controller.clone(), Some(SizedBox::new().into_widget()))
1283                    .painter(painter.erase()),
1284            ),
1285        );
1286        harness.pump(&mut app);
1287
1288        assert_eq!(app.get(&painter).count, 0, "an empty box paints nothing");
1289    }
1290
1291    #[test]
1292    fn a_controller_notification_repaints_the_snapshot_widget() {
1293        let cell = AppCell::new();
1294        let mut app = cell.borrow_mut();
1295        let controller = SnapshotController::new(&mut app, false);
1296        let painter = TestPainter::new(&mut app);
1297        let harness = Harness::mount(
1298            &mut app,
1299            centered(
1300                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
1301                    .painter(painter.erase()),
1302            ),
1303        );
1304        harness.pump(&mut app);
1305        assert_eq!(app.get(&painter).count, 1);
1306
1307        controller.clear(&mut app);
1308        harness.pump(&mut app);
1309        assert_eq!(app.get(&painter).count, 2);
1310
1311        controller.set_allow_snapshotting(&mut app, true);
1312        harness.pump(&mut app);
1313        assert_eq!(app.get(&painter).count, 3);
1314
1315        controller.set_allow_snapshotting(&mut app, true);
1316        harness.pump(&mut app);
1317        assert_eq!(
1318            app.get(&painter).count,
1319            3,
1320            "an unchanged value does not notify"
1321        );
1322    }
1323
1324    #[test]
1325    fn with_snapshotting_allowed_the_painter_paints_the_child_live() {
1326        let cell = AppCell::new();
1327        let mut app = cell.borrow_mut();
1328        let controller = SnapshotController::new(&mut app, true);
1329        let painter = TestPainter::new(&mut app);
1330        let harness = Harness::mount(
1331            &mut app,
1332            centered(
1333                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
1334                    .painter(painter.erase()),
1335            ),
1336        );
1337        harness.pump(&mut app);
1338
1339        assert_eq!(app.get(&painter).count, 1);
1340        assert!(
1341            app.get(&painter).last_image.is_none(),
1342            "no raster is taken until `toImageSync` lands"
1343        );
1344    }
1345
1346    #[test]
1347    fn the_painter_is_listened_to_while_attached() {
1348        let cell = AppCell::new();
1349        let mut app = cell.borrow_mut();
1350        let controller = SnapshotController::new(&mut app, false);
1351        let painter = TestPainter::new(&mut app);
1352        let harness = Harness::mount(
1353            &mut app,
1354            centered(
1355                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
1356                    .painter(painter.erase()),
1357            ),
1358        );
1359        harness.pump(&mut app);
1360        assert_eq!(app.get(&painter).added_listener_count, 1);
1361        assert_eq!(app.get(&painter).count, 1);
1362
1363        painter.notify_listeners(&mut app);
1364        harness.pump(&mut app);
1365        assert_eq!(
1366            app.get(&painter).count,
1367            2,
1368            "a painter notification repaints"
1369        );
1370
1371        harness.set_child(&mut app, SizedBox::new().into_widget());
1372        harness.pump(&mut app);
1373        assert_eq!(
1374            app.get(&painter).removed_listener_count,
1375            2,
1376            "detach and dispose each remove the listener"
1377        );
1378        assert!(!app.get(&painter).change_notifier.has_listeners());
1379        assert!(!app.get(&controller).change_notifier.has_listeners());
1380    }
1381
1382    #[test]
1383    fn a_new_painter_of_the_same_type_repaints_only_when_it_asks() {
1384        let cell = AppCell::new();
1385        let mut app = cell.borrow_mut();
1386        let controller = SnapshotController::new(&mut app, false);
1387        let painter1 = TestPainter::new(&mut app);
1388        let painter2 = TestPainter::new(&mut app);
1389        let painter3 = TestPainter::new(&mut app);
1390        app.get_mut(&painter3).should_repaint_value = true;
1391        let tree = |painter: Ref<TestPainter>| {
1392            centered(
1393                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
1394                    .painter(painter.erase()),
1395            )
1396        };
1397        let harness = Harness::mount(&mut app, tree(painter1.clone()));
1398        harness.pump(&mut app);
1399        assert_eq!(app.get(&painter1).count, 1);
1400
1401        harness.set_child(&mut app, tree(painter2.clone()));
1402        harness.pump(&mut app);
1403        assert_eq!(app.get(&painter1).removed_listener_count, 1);
1404        assert_eq!(app.get(&painter2).added_listener_count, 1);
1405        assert_eq!(app.get(&painter2).count, 0, "should_repaint is false");
1406
1407        harness.set_child(&mut app, tree(painter3.clone()));
1408        harness.pump(&mut app);
1409        assert_eq!(app.get(&painter2).removed_listener_count, 1);
1410        assert_eq!(app.get(&painter3).added_listener_count, 1);
1411        assert_eq!(app.get(&painter3).count, 1, "should_repaint is true");
1412    }
1413
1414    #[test]
1415    fn a_new_painter_of_another_type_repaints() {
1416        let cell = AppCell::new();
1417        let mut app = cell.borrow_mut();
1418        let controller = SnapshotController::new(&mut app, false);
1419        let painter1 = TestPainter::new(&mut app);
1420        let painter2 = TestPainter2::new(&mut app);
1421        let harness = Harness::mount(
1422            &mut app,
1423            centered(
1424                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
1425                    .painter(painter1.erase()),
1426            ),
1427        );
1428        harness.pump(&mut app);
1429
1430        harness.set_child(
1431            &mut app,
1432            centered(
1433                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
1434                    .painter(painter2.erase()),
1435            ),
1436        );
1437        harness.pump(&mut app);
1438        assert_eq!(app.get(&painter2).count, 1);
1439    }
1440
1441    #[test]
1442    fn a_new_controller_repaints_only_when_allow_snapshotting_differs() {
1443        let cell = AppCell::new();
1444        let mut app = cell.borrow_mut();
1445        let controller1 = SnapshotController::new(&mut app, false);
1446        let controller2 = SnapshotController::new(&mut app, false);
1447        let controller3 = SnapshotController::new(&mut app, true);
1448        let painter = TestPainter::new(&mut app);
1449        let tree = |controller: Ref<SnapshotController>| {
1450            centered(
1451                SnapshotWidget::new(controller, sized_box(100.0, 100.0)).painter(painter.erase()),
1452            )
1453        };
1454        let harness = Harness::mount(&mut app, tree(controller1.clone()));
1455        harness.pump(&mut app);
1456        assert_eq!(app.get(&painter).count, 1);
1457
1458        harness.set_child(&mut app, tree(controller2.clone()));
1459        harness.pump(&mut app);
1460        assert_eq!(app.get(&painter).count, 1);
1461        assert!(!app.get(&controller1).change_notifier.has_listeners());
1462        assert!(app.get(&controller2).change_notifier.has_listeners());
1463
1464        harness.set_child(&mut app, tree(controller3.clone()));
1465        harness.pump(&mut app);
1466        assert_eq!(app.get(&painter).count, 2);
1467        assert!(!app.get(&controller2).change_notifier.has_listeners());
1468
1469        controller3.clear(&mut app);
1470        harness.pump(&mut app);
1471        assert_eq!(
1472            app.get(&painter).count,
1473            3,
1474            "the new controller is listened to"
1475        );
1476    }
1477
1478    #[test]
1479    fn changing_the_mode_or_autoresize_repaints() {
1480        let cell = AppCell::new();
1481        let mut app = cell.borrow_mut();
1482        let controller = SnapshotController::new(&mut app, false);
1483        let painter = TestPainter::new(&mut app);
1484        let tree = |mode: SnapshotMode, autoresize: bool| {
1485            centered(
1486                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
1487                    .mode(mode)
1488                    .autoresize(autoresize)
1489                    .painter(painter.erase()),
1490            )
1491        };
1492        let harness = Harness::mount(&mut app, tree(SnapshotMode::Normal, false));
1493        harness.pump(&mut app);
1494        assert_eq!(app.get(&painter).count, 1);
1495
1496        harness.set_child(&mut app, tree(SnapshotMode::Permissive, false));
1497        harness.pump(&mut app);
1498        assert_eq!(app.get(&painter).count, 2);
1499
1500        harness.set_child(&mut app, tree(SnapshotMode::Permissive, true));
1501        harness.pump(&mut app);
1502        assert_eq!(app.get(&painter).count, 3);
1503
1504        harness.set_child(&mut app, tree(SnapshotMode::Permissive, true));
1505        harness.pump(&mut app);
1506        assert_eq!(
1507            app.get(&painter).count,
1508            3,
1509            "unchanged values do not repaint"
1510        );
1511    }
1512
1513    #[test]
1514    fn the_default_painter_paints_the_child() {
1515        let cell = AppCell::new();
1516        let mut app = cell.borrow_mut();
1517        let controller = SnapshotController::new(&mut app, false);
1518        let child_paints = Rc::new(Cell::new(0));
1519        let child = CustomPaint::new()
1520            .painter(ChildPaints(Rc::clone(&child_paints)))
1521            .child(SizedBox::new().width(100.0).height(100.0));
1522        let harness = Harness::mount(
1523            &mut app,
1524            centered(SnapshotWidget::new(
1525                controller.clone(),
1526                Some(child.into_widget()),
1527            )),
1528        );
1529        harness.pump(&mut app);
1530        assert_eq!(child_paints.get(), 1);
1531
1532        controller.set_allow_snapshotting(&mut app, true);
1533        harness.pump(&mut app);
1534        assert_eq!(
1535            child_paints.get(),
1536            2,
1537            "painted live while snapshotting is allowed"
1538        );
1539    }
1540
1541    #[test]
1542    fn a_painter_paints_the_child_through_the_layers_it_pushes() {
1543        let cell = AppCell::new();
1544        let mut app = cell.borrow_mut();
1545        let controller = SnapshotController::new(&mut app, true);
1546        let painter = app.create(LayeredPainter {
1547            change_notifier: ChangeNotifierData::new(),
1548            opacity_handle: LayerHandle::new(),
1549            transform_handle: LayerHandle::new(),
1550        });
1551        let child_paints = Rc::new(Cell::new(0));
1552        let child = CustomPaint::new()
1553            .painter(ChildPaints(Rc::clone(&child_paints)))
1554            .child(SizedBox::new().width(100.0).height(100.0));
1555        let harness = Harness::mount(
1556            &mut app,
1557            centered(
1558                SnapshotWidget::new(controller.clone(), Some(child.into_widget()))
1559                    .painter(painter.erase()),
1560            ),
1561        );
1562        harness.pump(&mut app);
1563        assert_eq!(child_paints.get(), 1);
1564        let transform = app.get(&painter).transform_handle.layer().expect("pushed");
1565        let opacity = app.get(&painter).opacity_handle.layer().expect("pushed");
1566        let found = layers(&app, &harness);
1567        let transform_at = found.iter().position(|layer| layer.id() == transform.id());
1568        let opacity_at = found.iter().position(|layer| layer.id() == opacity.id());
1569        assert!(transform_at.is_some() && opacity_at > transform_at);
1570
1571        painter.notify_listeners(&mut app);
1572        harness.pump(&mut app);
1573        assert_eq!(child_paints.get(), 2);
1574        assert_eq!(
1575            app.get(&painter).transform_handle.layer(),
1576            Some(transform),
1577            "reused"
1578        );
1579        assert_eq!(
1580            app.get(&painter).opacity_handle.layer(),
1581            Some(opacity),
1582            "reused"
1583        );
1584    }
1585}