waft-widgets 0.7.0

Widget framework and widgets for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
//! Flutter counterpart: `widgets/snapshot_widget.dart` (`SnapshotMode`, `SnapshotController`,
//! `SnapshotWidget`, `_RenderSnapshotWidget`, `SnapshotPainter`, `_DefaultSnapshotPainter`).
//!
//! `OffsetLayer.toImageSync` is deferred, so the render object never takes a raster: where
//! Flutter would rasterise the child and hand the image to
//! [`SnapshotPainter::paint_snapshot`], the painter's [`paint`](SnapshotPainter::paint) paints
//! the child live. The raster fields and the snapshot branch stay as Dart has them, empty until
//! the raster lands; a later editor who fills `child_raster` must also restore Dart's
//! `_paintAndDetachToImage`, with its platform-view check and [`SnapshotMode`] branches.

use std::any::TypeId;
use std::fmt::{self, Debug};
use std::hash::Hash;

use waft_embedder::valo::Sampling;
use waft_embedder::{Image, Matrix4, Offset, Paint, Rect, Size, TextBaseline};
use waft_foundation::{
    App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, Listenable, ListenableObject,
    Listener, Retained,
};
use waft_painting::ClipContext;
use waft_rendering::{
    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, PaintingContext,
    PipelineOwner, RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectBase,
    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin,
};

use crate::framework::{
    BuildContext, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, WidgetRef,
};
use crate::widgets::media_query::MediaQuery;
use waft_foundation::Ref;

/// Controls how the [`SnapshotWidget`] paints its child.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SnapshotMode {
    /// The child is snapshotted, but only if all descendants can be snapshotted.
    ///
    /// If there is a platform view in the children of a snapshot widget, the
    /// snapshot will not be used and the child will be rendered using
    /// [`SnapshotPainter::paint`]. This uses an un-snapshotted child and by default
    /// paints it with no additional modification.
    Permissive,

    /// An error is thrown if the child cannot be snapshotted.
    ///
    /// This setting is the default state of the [`SnapshotWidget`].
    Normal,

    /// The child is snapshotted and any child platform views are ignored.
    ///
    /// This mode can be useful if there is a platform view descendant that does
    /// not need to be included in the snapshot.
    Forced,
}

/// A controller for the [`SnapshotWidget`] that controls when the child image is displayed
/// and when to regenerated the child image.
///
/// When the value of [`allow_snapshotting`](Self::allow_snapshotting) is true, the
/// [`SnapshotWidget`] will paint the child widgets based on the [`SnapshotMode`] of the
/// snapshot widget.
///
/// The controller notifies its listeners when the value of
/// [`allow_snapshotting`](Self::allow_snapshotting) changes or when [`clear`](Self::clear) is
/// called.
///
/// To force [`SnapshotWidget`] to recreate the child image, call [`clear`](Self::clear).
pub struct SnapshotController {
    change_notifier: ChangeNotifierData,
    allow_snapshotting: bool,
}

impl SnapshotController {
    /// Create a new [`SnapshotController`].
    ///
    /// By default, [`allow_snapshotting`](Self::allow_snapshotting) is `false`: Dart's
    /// `SnapshotController({bool allowSnapshotting = false})`.
    pub fn new(app: &mut App, allow_snapshotting: bool) -> Ref<SnapshotController> {
        app.create(SnapshotController {
            change_notifier: ChangeNotifierData::new(),
            allow_snapshotting,
        })
    }

    /// Reset the snapshot held by any listening [`SnapshotWidget`].
    ///
    /// This has no effect if [`allow_snapshotting`](Self::allow_snapshotting) is `false`.
    pub fn clear(self: Handle<Self>, app: &mut App) {
        self.notify_listeners(app);
    }

    /// Whether a snapshot of this child widget is painted in its place.
    pub fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
        app.get(self).allow_snapshotting
    }

    /// Sets [`allow_snapshotting`](Self::allow_snapshotting).
    pub fn set_allow_snapshotting(self: Handle<Self>, app: &mut App, value: bool) {
        if value == self.allow_snapshotting(app) {
            return;
        }
        app.get_mut(self).allow_snapshotting = value;
        self.notify_listeners(app);
    }

    /// Discards any resources used by the object. Dart's inherited `ChangeNotifier.dispose`.
    pub fn dispose(self: Handle<Self>, app: &mut App) {
        ChangeNotifierData::dispose(app, self);
    }
}

impl ChangeNotifier for SnapshotController {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self.change_notifier
    }
}

impl Debug for SnapshotController {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SnapshotController")
            .field("allow_snapshotting", &self.allow_snapshotting)
            .finish()
    }
}

/// A widget that can replace its child with a snapshotted version of the child.
///
/// A snapshot is a frozen texture-backed representation of all child pictures
/// and layers stored as an [`Image`].
///
/// This widget is useful for performing short animations that would otherwise
/// be expensive or that cannot rely on raster caching. For example, scale and
/// skew animations are often expensive to perform on complex children, as are
/// blurs. For a short animation, a widget that contains these expensive effects
/// can be replaced with a snapshot of itself and manipulated instead.
///
/// For example, the Android Q `ZoomPageTransitionsBuilder` uses a snapshot widget
/// for the forward and entering route to avoid the expensive scale animation.
/// This also has the effect of briefly pausing any animations on the page.
///
/// Generally, this widget should not be used in places where users expect the
/// child widget to continue animating or to be responsive, such as an unbounded
/// animation.
///
/// Caveats:
///
/// * The contents of platform views cannot be captured by a snapshot
///   widget. If a platform view is encountered, then the snapshot widget will
///   determine how to render its children based on the [`SnapshotMode`]. This
///   defaults to [`SnapshotMode::Normal`] which will throw an exception if a
///   platform view is encountered.
///
/// * On the CanvasKit backend of Flutter, the performance of using this widget may regress
///   performance due to the fact that both the UI and engine share a single thread.
#[derive(Debug)]
pub struct SnapshotWidget {
    /// See [`Widget::key`](crate::Widget::key).
    pub key: Option<KeyRef>,

    /// The controller that determines when to display the children as a snapshot.
    pub controller: Ref<SnapshotController>,

    /// Configuration that controls how the snapshot widget decides to paint its children.
    ///
    /// Defaults to [`SnapshotMode::Normal`], which throws an error when a platform view
    /// or texture view is encountered.
    ///
    /// See [`SnapshotMode`] for more information.
    pub mode: SnapshotMode,

    /// Whether or not changes in render object size should automatically re-create
    /// the snapshot.
    ///
    /// Defaults to false.
    pub autoresize: bool,

    /// The painter used to paint the child snapshot or child widgets.
    ///
    /// `None` is Dart's default, `const _DefaultSnapshotPainter()`: one painter per app,
    /// reached through [`effective_painter`](Self::effective_painter), which paints the child
    /// exactly as it would paint itself.
    pub painter: Option<SnapshotPainterRef>,

    /// The widget below this widget in the tree.
    pub child: Option<WidgetRef>,
}

impl SnapshotWidget {
    /// Create a new [`SnapshotWidget`].
    ///
    /// The [`controller`](Self::controller) and [`child`](Self::child) arguments are required;
    /// Dart's `child` is required but nullable.
    pub fn new(controller: Ref<SnapshotController>, child: Option<WidgetRef>) -> SnapshotWidget {
        SnapshotWidget {
            key: None,
            controller,
            mode: SnapshotMode::Normal,
            autoresize: false,
            painter: None,
            child,
        }
    }

    /// Dart `SnapshotWidget(key:)`.
    pub fn key(mut self, key: KeyRef) -> SnapshotWidget {
        self.key = Some(key);
        self
    }

    /// Dart `SnapshotWidget(mode:)`.
    pub fn mode(mut self, mode: SnapshotMode) -> SnapshotWidget {
        self.mode = mode;
        self
    }

    /// Dart `SnapshotWidget(painter:)`.
    pub fn painter(mut self, painter: SnapshotPainterRef) -> SnapshotWidget {
        self.painter = Some(painter);
        self
    }

    /// Dart `SnapshotWidget(autoresize:)`.
    pub fn autoresize(mut self, autoresize: bool) -> SnapshotWidget {
        self.autoresize = autoresize;
        self
    }

    /// Dart's `painter` field: the given painter, or the app's one default painter.
    pub fn effective_painter(&self, app: &mut App) -> SnapshotPainterRef {
        self.painter.clone().unwrap_or_else(|| {
            app.singleton::<DefaultSnapshotPainter>()
                .keep(app)
                .into_erased()
        })
    }
}

impl RenderObjectWidget for SnapshotWidget {
    type RenderObject = RenderSnapshotWidget;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
        let device_pixel_ratio = MediaQuery::device_pixel_ratio_of(app, context);
        let painter = self.effective_painter(app);
        RenderSnapshotWidget::new(
            app,
            device_pixel_ratio,
            self.controller.clone(),
            self.mode,
            painter,
            self.autoresize,
        )
        .as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        context: BuildContext,
        render_object: RenderHandle<RenderSnapshotWidget>,
    ) {
        render_object.set_controller(app, self.controller.clone());
        render_object.set_mode(app, self.mode);
        let device_pixel_ratio = MediaQuery::device_pixel_ratio_of(app, context);
        render_object.set_device_pixel_ratio(app, device_pixel_ratio);
        let painter = self.effective_painter(app);
        render_object.set_painter(app, painter);
        render_object.set_autoresize(app, self.autoresize);
    }
}

impl SingleChildRenderObjectWidget for SnapshotWidget {
    fn child(&self) -> Option<&WidgetRef> {
        self.child.as_ref()
    }
}

/// A render object that conditionally converts its child into an [`Image`]
/// and then paints it in place of the child.
///
/// Flutter's private `_RenderSnapshotWidget`.
pub struct RenderSnapshotWidget {
    render_object: RenderObjectData,
    render_box: RenderBoxData,
    child: RenderObjectWithChildData<AnyRenderBox>,
    device_pixel_ratio: f64,
    painter: SnapshotPainterRef,
    controller: Ref<SnapshotController>,
    mode: SnapshotMode,
    autoresize: bool,
    /// Always `None` until `OffsetLayer.toImageSync` lands (see the module docs).
    child_raster: Option<Image>,
    child_raster_size: Option<Size>,
    /// Set to true if the snapshot mode was not forced and a platform view
    /// was encountered while attempting to snapshot the child.
    disable_snapshot_attempt: bool,
    last_cached_size: Option<Size>,
}

impl RenderSnapshotWidget {
    /// Create a new [`RenderSnapshotWidget`].
    fn new(
        app: &mut App,
        device_pixel_ratio: f64,
        controller: Ref<SnapshotController>,
        mode: SnapshotMode,
        painter: SnapshotPainterRef,
        autoresize: bool,
    ) -> RenderHandle<RenderSnapshotWidget> {
        RenderHandle::new_box(
            app,
            RenderSnapshotWidget {
                render_object: RenderObjectData::new(),
                render_box: RenderBoxData::new(),
                child: RenderObjectWithChildData::new(),
                device_pixel_ratio,
                painter,
                controller,
                mode,
                autoresize,
                child_raster: None,
                child_raster_size: None,
                disable_snapshot_attempt: false,
                last_cached_size: None,
            },
        )
    }

    /// The device pixel ratio used to create the child image.
    pub fn device_pixel_ratio(self: RenderHandle<Self>, app: &App) -> f64 {
        self.get(app).device_pixel_ratio
    }

    /// Sets [`device_pixel_ratio`](Self::device_pixel_ratio).
    pub fn set_device_pixel_ratio(self: RenderHandle<Self>, app: &mut App, value: f64) {
        if value == self.device_pixel_ratio(app) {
            return;
        }
        self.get_mut(app).device_pixel_ratio = value;
        if self.get(app).child_raster.is_none() {
            return;
        }
        self.get_mut(app).child_raster = None;
        self.mark_needs_paint(app);
    }

    /// The painter used to paint the child snapshot or child widgets.
    pub fn painter(self: RenderHandle<Self>, app: &App) -> AnySnapshotPainter {
        self.get(app).painter.handle()
    }

    /// Sets [`painter`](Self::painter).
    pub fn set_painter(self: RenderHandle<Self>, app: &mut App, value: SnapshotPainterRef) {
        if value == self.painter(app) {
            return;
        }
        let old_painter = self.painter(app);
        old_painter.remove_listener(app, &self.paint_listener());
        self.get_mut(app).painter = value;
        let painter = self.painter(app);
        if old_painter.runtime_type() != painter.runtime_type()
            || painter.should_repaint(app, old_painter)
        {
            self.mark_needs_paint(app);
        }
        if self.attached(app) {
            painter.add_listener(app, self.paint_listener());
        }
    }

    /// A controller that determines whether to paint the child normally or to
    /// paint a snapshotted version of that child.
    pub fn controller(self: RenderHandle<Self>, app: &App) -> Handle<SnapshotController> {
        self.get(app).controller.handle()
    }

    /// Sets [`controller`](Self::controller).
    pub fn set_controller(self: RenderHandle<Self>, app: &mut App, value: Ref<SnapshotController>) {
        if value == self.controller(app) {
            return;
        }
        self.controller(app)
            .remove_listener(app, &self.raster_value_changed_listener());
        let old_value = self.controller(app).allow_snapshotting(app);
        self.get_mut(app).controller = value;
        if self.attached(app) {
            self.controller(app)
                .add_listener(app, self.raster_value_changed_listener());
            if old_value != self.controller(app).allow_snapshotting(app) {
                self.on_raster_value_changed(app);
            }
        }
    }

    /// How the snapshot widget will handle platform views in child layers.
    pub fn mode(self: RenderHandle<Self>, app: &App) -> SnapshotMode {
        self.get(app).mode
    }

    /// Sets [`mode`](Self::mode).
    pub fn set_mode(self: RenderHandle<Self>, app: &mut App, value: SnapshotMode) {
        if value == self.mode(app) {
            return;
        }
        self.get_mut(app).mode = value;
        self.mark_needs_paint(app);
    }

    /// Whether or not changes in render object size should automatically re-rasterize.
    pub fn autoresize(self: RenderHandle<Self>, app: &App) -> bool {
        self.get(app).autoresize
    }

    /// Sets [`autoresize`](Self::autoresize).
    pub fn set_autoresize(self: RenderHandle<Self>, app: &mut App, value: bool) {
        if value == self.autoresize(app) {
            return;
        }
        self.get_mut(app).autoresize = value;
        self.mark_needs_paint(app);
    }

    /// Dart's `_onRasterValueChanged`.
    fn on_raster_value_changed(self: RenderHandle<Self>, app: &mut App) {
        self.get_mut(app).disable_snapshot_attempt = false;
        self.clear_child_raster(app);
        self.mark_needs_paint(app);
    }

    /// Dart's `_childRaster?.dispose(); _childRaster = null; _childRasterSize = null;`.
    fn clear_child_raster(self: RenderHandle<Self>, app: &mut App) {
        let this = self.get_mut(app);
        this.child_raster = None;
        this.child_raster_size = None;
    }

    /// The `markNeedsPaint` tear-off, equal to itself across registrations.
    fn paint_listener(self: RenderHandle<Self>) -> Listener {
        Listener::handle_method(self.handle(), mark_needs_paint)
    }

    /// The `_onRasterValueChanged` tear-off, equal to itself across registrations.
    fn raster_value_changed_listener(self: RenderHandle<Self>) -> Listener {
        Listener::handle_method(self.handle(), on_raster_value_changed)
    }

    /// Dart's `painter.paint(context, offset, size, super.paint)`: the painter paints the child
    /// live, through the proxy box's own paint.
    fn paint_with_painter(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        let size = self.size(app);
        self.painter(app)
            .paint(app, context, offset, size, &mut |app, context, offset| {
                RenderProxyBoxMixin::paint(self, app, context, offset)
            });
    }
}

fn mark_needs_paint(this: Handle<RenderSnapshotWidget>, app: &mut App) {
    RenderHandle::from_handle(this).mark_needs_paint(app);
}

fn on_raster_value_changed(this: Handle<RenderSnapshotWidget>, app: &mut App) {
    RenderHandle::from_handle(this).on_raster_value_changed(app);
}

impl RenderObjectWithChildMixin for RenderSnapshotWidget {
    type ChildType = AnyRenderBox;

    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
        &self.get(app).child
    }

    fn child_data_mut(
        self: RenderHandle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
        &mut self.get_mut(app).child
    }
}

impl RenderProxyBoxMixin for RenderSnapshotWidget {}

impl RenderObject for RenderSnapshotWidget {
    waft_rendering::render_object_accessors!();

    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
        self.controller(app)
            .add_listener(app, self.raster_value_changed_listener());
        self.painter(app).add_listener(app, self.paint_listener());
        if let Some(child) = self.child(app) {
            child.as_object().attach(app, owner);
        }
    }

    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
        self.get_mut(app).disable_snapshot_attempt = false;
        self.controller(app)
            .remove_listener(app, &self.raster_value_changed_listener());
        self.painter(app)
            .remove_listener(app, &self.paint_listener());
        self.clear_child_raster(app);
        if let Some(child) = self.child(app) {
            child.as_object().detach(app);
        }
    }

    fn dispose(self: RenderHandle<Self>, app: &mut App) {
        self.controller(app)
            .remove_listener(app, &self.raster_value_changed_listener());
        self.painter(app)
            .remove_listener(app, &self.paint_listener());
        self.clear_child_raster(app);
        RenderObjectBase::dispose(self, app);
    }

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        RenderProxyBoxMixin::perform_layout(self, app);
    }

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        let size = self.size(app);
        if size.is_empty() {
            self.clear_child_raster(app);
            return;
        }
        if !self.controller(app).allow_snapshotting(app) || self.get(app).disable_snapshot_attempt {
            self.clear_child_raster(app);
            self.paint_with_painter(app, context, offset);
            return;
        }

        let this = self.get(app);
        if this.autoresize && Some(size) != this.last_cached_size && this.last_cached_size.is_some()
        {
            self.get_mut(app).child_raster = None;
        }

        // Dart rasterises the child here (`_paintAndDetachToImage`); without
        // `OffsetLayer.toImageSync` no raster is taken, so the painter paints the child live.
        let this = self.get(app);
        match (this.child_raster.clone(), this.child_raster_size) {
            (Some(child_raster), Some(child_raster_size)) => {
                let device_pixel_ratio = this.device_pixel_ratio;
                self.painter(app).paint_snapshot(
                    app,
                    context,
                    offset,
                    size,
                    &child_raster,
                    child_raster_size,
                    device_pixel_ratio,
                );
            }
            _ => self.paint_with_painter(app, context, offset),
        }
    }

    fn visit_children(
        self: RenderHandle<Self>,
        app: &App,
        visitor: &mut dyn FnMut(AnyRenderObject),
    ) {
        if let Some(child) = self.child(app) {
            visitor(child.as_object());
        }
    }
}

impl RenderBox for RenderSnapshotWidget {
    waft_rendering::render_box_accessors!();

    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
        RenderProxyBoxMixin::setup_parent_data(self, app, child);
    }

    fn apply_paint_transform(
        self: RenderHandle<Self>,
        app: &App,
        child: AnyRenderObject,
        transform: &mut Matrix4,
    ) {
        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
    }

    fn hit_test_children(
        self: RenderHandle<Self>,
        app: &mut App,
        result: &mut BoxHitTestResult<'_>,
        position: Offset,
    ) -> bool {
        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
    }

    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
    }

    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
    }

    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
    }

    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
    }

    fn compute_distance_to_actual_baseline(
        self: RenderHandle<Self>,
        app: &mut App,
        baseline: TextBaseline,
    ) -> Option<f64> {
        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
    }

    fn compute_dry_baseline(
        self: RenderHandle<Self>,
        app: &mut App,
        constraints: BoxConstraints,
        baseline: TextBaseline,
    ) -> Option<f64> {
        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
    }

    fn compute_dry_layout(
        self: RenderHandle<Self>,
        app: &mut App,
        constraints: BoxConstraints,
    ) -> Size {
        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
    }
}

/// A painter used to paint either a snapshot or the child widgets that
/// would be a snapshot.
///
/// The painter can call `notify_listeners` to have the [`SnapshotWidget`]
/// re-paint (re-using the same raster). This allows animations to be performed
/// without re-snapshotting of children. For certain scale or perspective changing
/// transforms, such as a rotation, this can be significantly faster than performing
/// the same animation at the widget level.
///
/// By default, the [`SnapshotWidget`] includes a delegate that draws the child raster
/// exactly as the child widgets would have been drawn. Nevertheless, this can
/// also be used to efficiently transform the child raster and apply complex paint
/// effects.
///
/// Dart's abstract `SnapshotPainter extends ChangeNotifier`: a painter is an arena object that
/// holds [`ChangeNotifierData`] and implements [`ChangeNotifier`], which gives it the
/// [`ListenableObject`] side this trait asks for; the default painter implements that side
/// itself, as Dart's `_DefaultSnapshotPainter implements SnapshotPainter` does.
pub trait SnapshotPainter: ListenableObject {
    /// Called whenever the `image` that represents a [`SnapshotWidget`]s child should be
    /// painted.
    ///
    /// The image is rasterized at the physical pixel resolution and should be scaled down by
    /// `pixel_ratio` to account for device independent pixels.
    ///
    /// The default painter paints the snapshot accounting for the fact that the image width
    /// and height will be given in physical pixels, while the image must be painted with
    /// device independent pixels. That is, the width and height of the image is the widget and
    /// height of the provided `size`, multiplied by the `pixel_ratio`. In addition, the actual
    /// size of the scene captured by the `image` is not the image's width or height, but
    /// indeed `source_size`, because the former is a rounded inaccurate integer.
    #[allow(clippy::too_many_arguments)]
    fn paint_snapshot(
        self: Handle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
        image: &Image,
        source_size: Size,
        pixel_ratio: f64,
    );

    /// Paint the child via `painter`, applying any effects that would have been painted
    /// in [`paint_snapshot`](Self::paint_snapshot).
    ///
    /// This method is called when snapshotting is disabled, or when
    /// [`SnapshotMode::Permissive`] is used and a child platform view prevents snapshotting.
    ///
    /// The `offset` and `size` are the location and dimensions of the render object.
    fn paint(
        self: Handle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
        painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
    );

    /// Called whenever a new instance of the snapshot widget delegate class is
    /// provided to the [`SnapshotWidget`] object, or any time that a new
    /// [`SnapshotPainter`] object is created with a new instance of the
    /// delegate class (which amounts to the same thing, because the latter is
    /// implemented in terms of the former).
    ///
    /// If the new instance represents different information than the old
    /// instance, then the method should return true, otherwise it should return
    /// false.
    ///
    /// If the method returns false, then the [`paint`](Self::paint) call might be optimized
    /// away.
    ///
    /// It's possible that the [`paint`](Self::paint) method will get called even if
    /// [`should_repaint`](Self::should_repaint) returns false (e.g. if an ancestor or
    /// descendant needed to be repainted). It's also possible that the [`paint`](Self::paint)
    /// method will get called without [`should_repaint`](Self::should_repaint) being called at
    /// all (e.g. if the box changes size).
    ///
    /// Changing the delegate will not cause the child image retained by the
    /// [`SnapshotWidget`] to be updated. Instead, [`SnapshotController::clear`] can
    /// be used to force the generation of a new image.
    ///
    /// The `old_painter` argument is of the same type as this painter: Dart's `covariant`
    /// parameter, reached with [`AnySnapshotPainter::downcast`].
    fn should_repaint(self: Handle<Self>, app: &App, old_painter: AnySnapshotPainter) -> bool;

    /// The type-erased `SnapshotPainter` handle. Free: the vtable is a `const`, and the id is
    /// copied.
    fn as_snapshot_painter(self: Handle<Self>) -> AnySnapshotPainter {
        AnySnapshotPainter {
            id: self.id(),
            vtable: const { &SnapshotPainterVTable::of::<Self>() },
        }
    }
}

/// The dispatch signature of [`SnapshotPainter::paint_snapshot`].
type PaintSnapshotFn =
    fn(&mut App, HandleId, &mut PaintingContext, Offset, Size, &Image, Size, f64);

/// The dispatch signature of [`SnapshotPainter::paint`].
type PaintFn = fn(
    &mut App,
    HandleId,
    &mut PaintingContext,
    Offset,
    Size,
    &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
);

/// The vtable of an erased [`AnySnapshotPainter`]: one `&'static` table per concrete
/// [`SnapshotPainter`] type.
struct SnapshotPainterVTable {
    runtime_type: fn() -> TypeId,
    type_name: fn() -> &'static str,
    add_listener: fn(&mut App, HandleId, Listener),
    remove_listener: fn(&mut App, HandleId, &Listener),
    paint_snapshot: PaintSnapshotFn,
    paint: PaintFn,
    should_repaint: fn(&App, HandleId, AnySnapshotPainter) -> bool,
}

/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
    Handle::from_id(id)
}

impl SnapshotPainterVTable {
    const fn of<T: SnapshotPainter>() -> SnapshotPainterVTable {
        SnapshotPainterVTable {
            runtime_type: TypeId::of::<T>,
            type_name: std::any::type_name::<T>,
            add_listener: |app, id, listener| {
                ListenableObject::add_listener(resolve::<T>(id), app, listener)
            },
            remove_listener: |app, id, listener| {
                ListenableObject::remove_listener(resolve::<T>(id), app, listener)
            },
            paint_snapshot: |app, id, context, offset, size, image, source_size, pixel_ratio| {
                T::paint_snapshot(
                    resolve(id),
                    app,
                    context,
                    offset,
                    size,
                    image,
                    source_size,
                    pixel_ratio,
                )
            },
            paint: |app, id, context, offset, size, painter| {
                T::paint(resolve(id), app, context, offset, size, painter)
            },
            should_repaint: |app, id, old_painter| T::should_repaint(resolve(id), app, old_painter),
        }
    }
}

/// Erased [`SnapshotPainter`]: what a field or parameter Dart types as `SnapshotPainter`
/// becomes.
///
/// Equality is Dart's `==` on an object reference.
#[derive(Clone, Copy)]
pub struct AnySnapshotPainter {
    id: HandleId,
    vtable: &'static SnapshotPainterVTable,
}

/// A field Dart types as the erased object, kept: AnySnapshotPainter with its count.
pub type SnapshotPainterRef = Retained<AnySnapshotPainter>;

waft_foundation::erased_handle!(AnySnapshotPainter: SnapshotPainter => SnapshotPainter::as_snapshot_painter);

impl AnySnapshotPainter {
    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

    /// Dart's `runtimeType`.
    pub fn runtime_type(self) -> TypeId {
        (self.vtable.runtime_type)()
    }

    /// Dart's `painter as P`: the typed handle when this painter is a `P`, else `None`.
    pub fn downcast<P: 'static>(self, app: &App) -> Option<Handle<P>> {
        app.handle::<P>(self.id)
    }

    /// See [`SnapshotPainter::paint_snapshot`].
    #[allow(clippy::too_many_arguments)]
    pub fn paint_snapshot(
        self,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
        image: &Image,
        source_size: Size,
        pixel_ratio: f64,
    ) {
        (self.vtable.paint_snapshot)(
            app,
            self.id,
            context,
            offset,
            size,
            image,
            source_size,
            pixel_ratio,
        )
    }

    /// See [`SnapshotPainter::paint`].
    pub fn paint(
        self,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
        painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
    ) {
        (self.vtable.paint)(app, self.id, context, offset, size, painter)
    }

    /// See [`SnapshotPainter::should_repaint`].
    pub fn should_repaint(self, app: &App, old_painter: AnySnapshotPainter) -> bool {
        (self.vtable.should_repaint)(app, self.id, old_painter)
    }
}

impl Debug for AnySnapshotPainter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
    }
}

impl Listenable for AnySnapshotPainter {
    fn add_listener(&self, app: &mut App, listener: Listener) {
        (self.vtable.add_listener)(app, self.id, listener)
    }

    fn remove_listener(&self, app: &mut App, listener: &Listener) {
        (self.vtable.remove_listener)(app, self.id, listener)
    }
}

/// Flutter's private `_DefaultSnapshotPainter`: paints the child as it would paint itself, and
/// the snapshot exactly over the render object. It never notifies, so it keeps no listeners.
///
/// Dart's `const` constructor makes every default painter one object; here it is the app's
/// singleton.
#[derive(Debug, Default)]
struct DefaultSnapshotPainter;

impl ListenableObject for DefaultSnapshotPainter {
    fn add_listener(self: Handle<Self>, _app: &mut App, _listener: Listener) {}

    fn remove_listener(self: Handle<Self>, _app: &mut App, _listener: &Listener) {}
}

impl SnapshotPainter for DefaultSnapshotPainter {
    fn paint(
        self: Handle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        _size: Size,
        painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
    ) {
        painter(app, context, offset);
    }

    fn paint_snapshot(
        self: Handle<Self>,
        _app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
        image: &Image,
        source_size: Size,
        _pixel_ratio: f64,
    ) {
        let src = Rect::from_ltwh(0.0, 0.0, source_size.width(), source_size.height());
        let dst = Rect::from_ltwh(offset.dx(), offset.dy(), size.width(), size.height());
        // Valo's default sampling, linear with linear mipmaps, is Dart's `FilterQuality.medium`.
        let sampling = Sampling::default();
        context.canvas().draw_image_rect(
            image,
            src.into(),
            dst.into(),
            sampling,
            &Paint::default(),
        );
    }

    fn should_repaint(self: Handle<Self>, _app: &App, _old_painter: AnySnapshotPainter) -> bool {
        false
    }
}

#[cfg(test)]
mod tests {
    use std::any::Any;
    use std::cell::{Cell, RefCell};
    use std::marker::PhantomData;
    use std::rc::Rc;
    use waft_foundation::Ref;

    use waft_embedder::{Canvas, Color};
    use waft_foundation::AppCell;
    use waft_painting::TextDirection;
    use waft_rendering::{
        AnyLayer, CustomPainter, LayerHandle, OpacityLayer, PictureLayer, TransformLayer,
    };

    use super::*;
    use crate::framework::IntoWidget;
    use crate::test_harness::Harness;
    use crate::widgets::basic::{
        Center, CustomPaint, Directionality, RepaintBoundary, SizedBox, StateSetter,
        StatefulBuilder,
    };
    use crate::widgets::container::Container;
    use crate::widgets::media_query::MediaQueryData;

    const YELLOW: Color = Color::new(0xFFAABB11);

    struct First;
    struct Second;

    /// Flutter's `TestPainter`, and with `Second` its `TestPainter2`: a painter of another
    /// runtime type that behaves the same.
    struct TestPainterOf<M: 'static> {
        change_notifier: ChangeNotifierData,
        count: u32,
        should_repaint_value: bool,
        last_image: Option<Image>,
        added_listener_count: u32,
        removed_listener_count: u32,
        marker: PhantomData<M>,
    }

    type TestPainter = TestPainterOf<First>;
    type TestPainter2 = TestPainterOf<Second>;

    impl<M: 'static> TestPainterOf<M> {
        fn new(app: &mut App) -> Ref<TestPainterOf<M>> {
            app.create(TestPainterOf {
                change_notifier: ChangeNotifierData::new(),
                count: 0,
                should_repaint_value: false,
                last_image: None,
                added_listener_count: 0,
                removed_listener_count: 0,
                marker: PhantomData,
            })
        }
    }

    impl<M: 'static> ChangeNotifier for TestPainterOf<M> {
        fn change_notifier_data(&self) -> &ChangeNotifierData {
            &self.change_notifier
        }

        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
            &mut self.change_notifier
        }

        fn will_add_listener(self: Handle<Self>, app: &mut App) {
            app.get_mut(self).added_listener_count += 1;
        }

        fn did_remove_listener(self: Handle<Self>, app: &mut App) {
            app.get_mut(self).removed_listener_count += 1;
        }
    }

    impl<M: 'static> SnapshotPainter for TestPainterOf<M> {
        fn paint_snapshot(
            self: Handle<Self>,
            app: &mut App,
            _context: &mut PaintingContext,
            _offset: Offset,
            _size: Size,
            image: &Image,
            _source_size: Size,
            _pixel_ratio: f64,
        ) {
            let this = app.get_mut(self);
            this.count += 1;
            this.last_image = Some(image.clone());
        }

        fn paint(
            self: Handle<Self>,
            app: &mut App,
            _context: &mut PaintingContext,
            _offset: Offset,
            _size: Size,
            _painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
        ) {
            app.get_mut(self).count += 1;
        }

        fn should_repaint(self: Handle<Self>, app: &App, old_painter: AnySnapshotPainter) -> bool {
            debug_assert!(old_painter.downcast::<Self>(app).is_some());
            app.get(self).should_repaint_value
        }
    }

    /// The shape of Material's zoom painters: the child painted through a transform and an
    /// opacity layer the painter keeps across paints.
    struct LayeredPainter {
        change_notifier: ChangeNotifierData,
        opacity_handle: LayerHandle<Handle<OpacityLayer>>,
        transform_handle: LayerHandle<Handle<TransformLayer>>,
    }

    impl ChangeNotifier for LayeredPainter {
        fn change_notifier_data(&self) -> &ChangeNotifierData {
            &self.change_notifier
        }

        fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
            &mut self.change_notifier
        }
    }

    impl SnapshotPainter for LayeredPainter {
        fn paint_snapshot(
            self: Handle<Self>,
            _app: &mut App,
            _context: &mut PaintingContext,
            _offset: Offset,
            _size: Size,
            _image: &Image,
            _source_size: Size,
            _pixel_ratio: f64,
        ) {
        }

        fn paint(
            self: Handle<Self>,
            app: &mut App,
            context: &mut PaintingContext,
            offset: Offset,
            _size: Size,
            painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
        ) {
            let old_transform = app.get(self).transform_handle.layer();
            let transform = context.push_transform(
                app,
                true,
                offset,
                Matrix4::IDENTITY,
                |app, context, offset| {
                    let old_opacity = app.get(self).opacity_handle.layer();
                    let opacity = context.push_opacity(app, offset, 128, painter, old_opacity);
                    LayerHandle::set_layer(
                        app,
                        |app| &mut app.get_mut(self).opacity_handle,
                        Some(opacity),
                    );
                },
                old_transform,
            );
            LayerHandle::set_layer(
                app,
                |app| &mut app.get_mut(self).transform_handle,
                transform,
            );
        }

        fn should_repaint(
            self: Handle<Self>,
            _app: &App,
            _old_painter: AnySnapshotPainter,
        ) -> bool {
            false
        }
    }

    /// Counts the paints of the child it stands in for.
    struct ChildPaints(Rc<Cell<u32>>);

    impl CustomPainter for ChildPaints {
        fn paint(&self, _app: &mut App, _canvas: &mut Canvas, _size: Size) {
            self.0.set(self.0.get() + 1);
        }

        fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
            false
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    /// Flutter's `TestDependencies`: a text direction and a media query of `device_pixel_ratio`.
    fn test_dependencies<K>(device_pixel_ratio: f64, child: impl IntoWidget<K>) -> WidgetRef {
        let query = MediaQuery::new(
            MediaQueryData::new().device_pixel_ratio(device_pixel_ratio),
            child,
        )
        .into_widget();
        Directionality::new(TextDirection::Ltr, query).into_widget()
    }

    /// A centred 100 x 100 box under a snapshot widget.
    fn centered(snapshot: SnapshotWidget) -> WidgetRef {
        Center::new()
            .child(test_dependencies(1.0, snapshot))
            .into_widget()
    }

    fn sized_box(width: f64, height: f64) -> Option<WidgetRef> {
        Some(SizedBox::new().width(width).height(height).into_widget())
    }

    /// Flutter's `tester.layers`: the layer tree from the root, depth first.
    fn layers(app: &App, harness: &Harness) -> Vec<AnyLayer> {
        harness.layers(app)
    }

    #[test]
    fn changing_the_device_pixel_ratio_does_not_repaint_if_snapshotting_is_not_enabled() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, false);
        let painter = TestPainter::new(&mut app);
        let device_pixel_ratio = Rc::new(Cell::new(1.0));
        let local_set_state: Rc<RefCell<Option<StateSetter>>> = Rc::default();
        let harness = Harness::mount(
            &mut app,
            StatefulBuilder::new({
                let (device_pixel_ratio, local_set_state) =
                    (Rc::clone(&device_pixel_ratio), Rc::clone(&local_set_state));
                let painter = painter.clone();
                move |_app, _context, set_state| {
                    *local_set_state.borrow_mut() = Some(set_state);
                    Center::new()
                        .child(test_dependencies(
                            device_pixel_ratio.get(),
                            SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
                                .painter(painter.erase()),
                        ))
                        .into_widget()
                }
            })
            .into_widget(),
        );
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 1);

        let set_state = local_set_state.borrow().clone().expect("the builder ran");
        set_state(&mut app, &mut |_app| device_pixel_ratio.set(2.0));
        harness.pump(&mut app);

        // Not repainted as dpr was not used.
        assert_eq!(app.get(&painter).count, 1);
    }

    #[test]
    fn the_snapshot_widget_paints_its_child_as_a_single_picture_layer() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, true);
        let child = Container::new().width(100.0).height(100.0).color(YELLOW);
        let harness = Harness::mount(
            &mut app,
            RepaintBoundary::new()
                .child(centered(SnapshotWidget::new(
                    controller.clone(),
                    Some(child.into_widget()),
                )))
                .into_widget(),
        );
        harness.pump(&mut app);

        let found = layers(&app, &harness);
        assert_eq!(found.len(), 3);
        assert!(app.handle::<PictureLayer>(found[2].id()).is_some());

        controller.set_allow_snapshotting(&mut app, false);
        harness.pump(&mut app);

        let found = layers(&app, &harness);
        assert_eq!(found.len(), 3);
        assert!(app.handle::<PictureLayer>(found[2].id()).is_some());
    }

    #[test]
    fn the_snapshot_widget_can_update_the_painter_type() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, true);
        let painter1 = TestPainter::new(&mut app);
        let painter2 = TestPainter2::new(&mut app);
        let harness = Harness::mount(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), Some(SizedBox::new().into_widget()))
                    .painter(painter1.erase()),
            ),
        );
        harness.pump(&mut app);

        harness.set_child(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), Some(SizedBox::new().into_widget()))
                    .painter(painter2.erase()),
            ),
        );
        harness.pump(&mut app);
    }

    #[test]
    fn a_child_with_an_empty_size_does_not_fail_to_paint() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, true);
        let painter = TestPainter::new(&mut app);
        let harness = Harness::mount(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), Some(SizedBox::new().into_widget()))
                    .painter(painter.erase()),
            ),
        );
        harness.pump(&mut app);

        assert_eq!(app.get(&painter).count, 0, "an empty box paints nothing");
    }

    #[test]
    fn a_controller_notification_repaints_the_snapshot_widget() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, false);
        let painter = TestPainter::new(&mut app);
        let harness = Harness::mount(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
                    .painter(painter.erase()),
            ),
        );
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 1);

        controller.clear(&mut app);
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 2);

        controller.set_allow_snapshotting(&mut app, true);
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 3);

        controller.set_allow_snapshotting(&mut app, true);
        harness.pump(&mut app);
        assert_eq!(
            app.get(&painter).count,
            3,
            "an unchanged value does not notify"
        );
    }

    #[test]
    fn with_snapshotting_allowed_the_painter_paints_the_child_live() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, true);
        let painter = TestPainter::new(&mut app);
        let harness = Harness::mount(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
                    .painter(painter.erase()),
            ),
        );
        harness.pump(&mut app);

        assert_eq!(app.get(&painter).count, 1);
        assert!(
            app.get(&painter).last_image.is_none(),
            "no raster is taken until `toImageSync` lands"
        );
    }

    #[test]
    fn the_painter_is_listened_to_while_attached() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, false);
        let painter = TestPainter::new(&mut app);
        let harness = Harness::mount(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
                    .painter(painter.erase()),
            ),
        );
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).added_listener_count, 1);
        assert_eq!(app.get(&painter).count, 1);

        painter.notify_listeners(&mut app);
        harness.pump(&mut app);
        assert_eq!(
            app.get(&painter).count,
            2,
            "a painter notification repaints"
        );

        harness.set_child(&mut app, SizedBox::new().into_widget());
        harness.pump(&mut app);
        assert_eq!(
            app.get(&painter).removed_listener_count,
            2,
            "detach and dispose each remove the listener"
        );
        assert!(!app.get(&painter).change_notifier.has_listeners());
        assert!(!app.get(&controller).change_notifier.has_listeners());
    }

    #[test]
    fn a_new_painter_of_the_same_type_repaints_only_when_it_asks() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, false);
        let painter1 = TestPainter::new(&mut app);
        let painter2 = TestPainter::new(&mut app);
        let painter3 = TestPainter::new(&mut app);
        app.get_mut(&painter3).should_repaint_value = true;
        let tree = |painter: Ref<TestPainter>| {
            centered(
                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
                    .painter(painter.erase()),
            )
        };
        let harness = Harness::mount(&mut app, tree(painter1.clone()));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter1).count, 1);

        harness.set_child(&mut app, tree(painter2.clone()));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter1).removed_listener_count, 1);
        assert_eq!(app.get(&painter2).added_listener_count, 1);
        assert_eq!(app.get(&painter2).count, 0, "should_repaint is false");

        harness.set_child(&mut app, tree(painter3.clone()));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter2).removed_listener_count, 1);
        assert_eq!(app.get(&painter3).added_listener_count, 1);
        assert_eq!(app.get(&painter3).count, 1, "should_repaint is true");
    }

    #[test]
    fn a_new_painter_of_another_type_repaints() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, false);
        let painter1 = TestPainter::new(&mut app);
        let painter2 = TestPainter2::new(&mut app);
        let harness = Harness::mount(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
                    .painter(painter1.erase()),
            ),
        );
        harness.pump(&mut app);

        harness.set_child(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
                    .painter(painter2.erase()),
            ),
        );
        harness.pump(&mut app);
        assert_eq!(app.get(&painter2).count, 1);
    }

    #[test]
    fn a_new_controller_repaints_only_when_allow_snapshotting_differs() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller1 = SnapshotController::new(&mut app, false);
        let controller2 = SnapshotController::new(&mut app, false);
        let controller3 = SnapshotController::new(&mut app, true);
        let painter = TestPainter::new(&mut app);
        let tree = |controller: Ref<SnapshotController>| {
            centered(
                SnapshotWidget::new(controller, sized_box(100.0, 100.0)).painter(painter.erase()),
            )
        };
        let harness = Harness::mount(&mut app, tree(controller1.clone()));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 1);

        harness.set_child(&mut app, tree(controller2.clone()));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 1);
        assert!(!app.get(&controller1).change_notifier.has_listeners());
        assert!(app.get(&controller2).change_notifier.has_listeners());

        harness.set_child(&mut app, tree(controller3.clone()));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 2);
        assert!(!app.get(&controller2).change_notifier.has_listeners());

        controller3.clear(&mut app);
        harness.pump(&mut app);
        assert_eq!(
            app.get(&painter).count,
            3,
            "the new controller is listened to"
        );
    }

    #[test]
    fn changing_the_mode_or_autoresize_repaints() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, false);
        let painter = TestPainter::new(&mut app);
        let tree = |mode: SnapshotMode, autoresize: bool| {
            centered(
                SnapshotWidget::new(controller.clone(), sized_box(100.0, 100.0))
                    .mode(mode)
                    .autoresize(autoresize)
                    .painter(painter.erase()),
            )
        };
        let harness = Harness::mount(&mut app, tree(SnapshotMode::Normal, false));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 1);

        harness.set_child(&mut app, tree(SnapshotMode::Permissive, false));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 2);

        harness.set_child(&mut app, tree(SnapshotMode::Permissive, true));
        harness.pump(&mut app);
        assert_eq!(app.get(&painter).count, 3);

        harness.set_child(&mut app, tree(SnapshotMode::Permissive, true));
        harness.pump(&mut app);
        assert_eq!(
            app.get(&painter).count,
            3,
            "unchanged values do not repaint"
        );
    }

    #[test]
    fn the_default_painter_paints_the_child() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, false);
        let child_paints = Rc::new(Cell::new(0));
        let child = CustomPaint::new()
            .painter(ChildPaints(Rc::clone(&child_paints)))
            .child(SizedBox::new().width(100.0).height(100.0));
        let harness = Harness::mount(
            &mut app,
            centered(SnapshotWidget::new(
                controller.clone(),
                Some(child.into_widget()),
            )),
        );
        harness.pump(&mut app);
        assert_eq!(child_paints.get(), 1);

        controller.set_allow_snapshotting(&mut app, true);
        harness.pump(&mut app);
        assert_eq!(
            child_paints.get(),
            2,
            "painted live while snapshotting is allowed"
        );
    }

    #[test]
    fn a_painter_paints_the_child_through_the_layers_it_pushes() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = SnapshotController::new(&mut app, true);
        let painter = app.create(LayeredPainter {
            change_notifier: ChangeNotifierData::new(),
            opacity_handle: LayerHandle::new(),
            transform_handle: LayerHandle::new(),
        });
        let child_paints = Rc::new(Cell::new(0));
        let child = CustomPaint::new()
            .painter(ChildPaints(Rc::clone(&child_paints)))
            .child(SizedBox::new().width(100.0).height(100.0));
        let harness = Harness::mount(
            &mut app,
            centered(
                SnapshotWidget::new(controller.clone(), Some(child.into_widget()))
                    .painter(painter.erase()),
            ),
        );
        harness.pump(&mut app);
        assert_eq!(child_paints.get(), 1);
        let transform = app.get(&painter).transform_handle.layer().expect("pushed");
        let opacity = app.get(&painter).opacity_handle.layer().expect("pushed");
        let found = layers(&app, &harness);
        let transform_at = found.iter().position(|layer| layer.id() == transform.id());
        let opacity_at = found.iter().position(|layer| layer.id() == opacity.id());
        assert!(transform_at.is_some() && opacity_at > transform_at);

        painter.notify_listeners(&mut app);
        harness.pump(&mut app);
        assert_eq!(child_paints.get(), 2);
        assert_eq!(
            app.get(&painter).transform_handle.layer(),
            Some(transform),
            "reused"
        );
        assert_eq!(
            app.get(&painter).opacity_handle.layer(),
            Some(opacity),
            "reused"
        );
    }
}