waft-widgets 0.4.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
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
//! Flutter counterpart: `widgets/view.dart` (`View`, `RawView`, the view scopes).
//!
//! `View` wraps its child in `MediaQuery::from_view`, a `FocusTraversalGroup` parented on the
//! root scope, and a `FocusScope` over its own scope node. `ViewCollection` and `ViewAnchor`
//! place further views beside or under a tree.

use std::any::Any;
use std::collections::HashSet;
use std::fmt;
use std::rc::Rc;

use waft_embedder::{ViewFocusDirection, ViewFocusEvent, ViewFocusState, ViewId, ViewRef};
use waft_foundation::{App, Handle, ListenableObject, Listener, ValueKey};
use waft_rendering::{AnyRenderObject, PipelineOwner, RenderHandle, RenderView, RendererBinding};
use waft_scheduler::{FrameTarget, SchedulerBinding};

use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
use crate::framework::{
    AnyElement, BuildContext, Element, ElementBase, ElementData, ElementLifecycle, InheritedWidget,
    IntoWidget, KeyRef, RenderObjectElement, RenderObjectElementData, RenderObjectElementWidget,
    RenderObjectWidget, RenderTreeRootElement, Slot, State, StateData, StatefulWidget,
    StatelessWidget, Widget, WidgetKind, WidgetRef, downcast_widget,
};
use crate::widgets::focus_manager::{FocusManager, FocusNodeLeaf, FocusScopeNode};
use crate::widgets::focus_scope::FocusScope;
use crate::widgets::focus_traversal::{
    AnyFocusTraversalPolicy, FocusTraversalGroup, FocusTraversalPolicy, ReadingOrderTraversalPolicy,
};
use crate::widgets::media_query::MediaQuery;

/// Bootstraps a render tree that is rendered into the provided `FlutterView`.
///
/// The content rendered into that view is determined by the provided
/// [`child`](Self::child). Descendants within the same `LookupBoundary` can look up the view
/// they are rendered into via [`View::of`] and [`View::maybe_of`].
///
/// The provided [`child`](Self::child) is wrapped in a `MediaQuery` constructed from the given
/// view, a `FocusScope`, and a [`RawView`] widget.
///
/// For most use cases, using `MediaQuery.of`, or its associated "...Of" methods are a more
/// appropriate way of obtaining the information that a `FlutterView` exposes. For example,
/// using `MediaQuery.sizeOf` will expose the _logical_ device size (`MediaQueryData.size`)
/// rather than the physical size (`FlutterView.physicalSize`). Similarly, while
/// `FlutterView.padding` conveys the information from the operating system, the
/// `MediaQueryData.padding` attribute (obtained from `MediaQuery.paddingOf`) further adjusts
/// this information to be aware of the context of the widget; e.g. the `Scaffold` widget
/// adjusts the values for its various children.
///
/// Each `FlutterView` can be associated with at most one [`View`] widget in the widget tree.
/// Two or more [`View`] widgets configured with the same `FlutterView` must never exist within
/// the same widget tree at the same time. This limitation is enforced by a `GlobalObjectKey`
/// that derives its identity from the [`view`](Self::view) provided to this widget.
///
/// Since the [`View`] widget bootstraps its own independent render tree, neither it nor any of
/// its descendants will insert a `RenderObject` into an existing render tree. Therefore, the
/// [`View`] widget can only be used in those parts of the widget tree where it is not required
/// to participate in the construction of the surrounding render tree. In other words, the
/// widget may only be used in a non-rendering zone of the widget tree (see
/// `WidgetsBinding` for a definition of rendering and non-rendering zones).
pub struct View {
    pub key: Option<KeyRef>,
    /// The `FlutterView` into which [`child`](Self::child) is drawn.
    pub view: ViewRef,
    /// The widget below this widget in the tree, which will be drawn into the
    /// [`view`](Self::view).
    pub child: WidgetRef,
}

impl View {
    /// Create a [`View`] widget to bootstrap a render tree that is rendered into the provided
    /// `FlutterView`.
    pub fn new<K>(view: ViewRef, child: impl IntoWidget<K>) -> View {
        View {
            key: None,
            view,
            child: child.into_widget(),
        }
    }

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

    /// Returns the `FlutterView` that the provided `context` will render into.
    ///
    /// Returns `None` if the `context` is not associated with a `FlutterView`.
    ///
    /// The method creates a dependency on the `context`, which will be informed when the
    /// identity of the `FlutterView` changes (i.e. the `context` is moved to render into a
    /// different `FlutterView` then before). The dependency is not triggered when the
    /// properties on the `FlutterView` itself change.
    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<ViewRef> {
        context
            .depend_on_inherited_widget_of_exact_type::<ViewScope>(app)
            .map(|scope| Rc::clone(&scope.view))
    }

    /// Returns the `FlutterView` that the provided `context` will render into.
    ///
    /// Throws if the `context` is not associated with a `FlutterView`.
    ///
    /// The method creates a dependency on the `context`, which will be informed when the
    /// identity of the `FlutterView` changes (i.e. the `context` is moved to render into a
    /// different `FlutterView` then before). The dependency is not triggered when the
    /// properties on the `FlutterView` itself change.
    pub fn of(app: &mut App, context: BuildContext) -> ViewRef {
        View::maybe_of(app, context).expect(
            "View.of() was called with a context that does not contain a View widget. No View \
             widget ancestor could be found starting from the context that was passed to \
             View.of(). This usually means that the provided context is not associated with a \
             View.",
        )
    }

    /// The id of the view `context` renders into, or `None` for a context in no view: above
    /// every `View`, in a test's tree without one, or no longer in the tree.
    ///
    /// Unlike [`View::maybe_of`], this creates no dependency, so it may be asked outside a build,
    /// as when a ticker is created or its state activated.
    pub fn maybe_id_of(app: &App, context: BuildContext) -> Option<ViewId> {
        if context.lifecycle(app) != ElementLifecycle::Active {
            return None;
        }
        context
            .get_inherited_widget_of_exact_type::<ViewScope>(app)
            .map(|scope| scope.view.id())
    }

    /// Returns the `PipelineOwner` parent to which a child `View` should attach its
    /// `PipelineOwner` to.
    ///
    /// If `context` has a `View` ancestor, it returns the `PipelineOwner` that manages the
    /// render tree of that view. If there is no `View` ancestor,
    /// `RendererBinding.rootPipelineOwner` is returned instead.
    pub fn pipeline_owner_of(app: &mut App, context: BuildContext) -> Handle<PipelineOwner> {
        let scoped = context
            .depend_on_inherited_widget_of_exact_type::<PipelineOwnerScope>(app)
            .map(|scope| scope.pipeline_owner);
        scoped.unwrap_or_else(|| RendererBinding::instance(app).root_pipeline_owner(app))
    }
}

impl fmt::Debug for View {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("View")
            .field("view", &self.view.id())
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for View {
    type State = ViewState;

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

    fn create_state(&self) -> ViewState {
        ViewState {
            state: StateData::new(),
            scope_node: None,
            policy: None,
            view_has_focus: false,
            observer: None,
            scope_listener: None,
        }
    }
}

/// The state of a [`View`], including synchronization with native view focus.
pub struct ViewState {
    state: StateData<View>,
    scope_node: Option<Handle<FocusScopeNode>>,
    policy: Option<AnyFocusTraversalPolicy>,
    /// Whether the native view owns focus, independently of its widget subtree.
    view_has_focus: bool,
    /// Retains the observer identity for removal on disposal.
    observer: Option<WidgetsBindingObserverRef>,
    /// Retains the bound callback identity for removal on disposal.
    scope_listener: Option<Listener>,
}

impl ViewState {
    /// The focus scope node this view's subtree is scoped by.
    fn scope_node(self: Handle<Self>, app: &App) -> Handle<FocusScopeNode> {
        app.get(self).scope_node.expect("created in init_state")
    }

    /// Requests native focus when the framework focuses a descendant of this view.
    fn scope_focus_change_listener(self: Handle<Self>, app: &mut App) {
        let has_focus = self.scope_node(app).has_focus(app);
        if app.get(self).view_has_focus == has_focus || !has_focus {
            return;
        }
        self.widget(app)
            .view
            .host()
            .request_focus_change(ViewFocusState::Focused, ViewFocusDirection::Forward);
    }
}

impl WidgetsBindingObserverObject for ViewState {
    fn did_change_view_focus(self: Handle<Self>, app: &mut App, event: ViewFocusEvent) {
        let view_id = self.widget(app).view.id();
        app.get_mut(self).view_has_focus = match event.state {
            ViewFocusState::Focused => event.view_id == view_id,
            ViewFocusState::Unfocused => false,
        };
        if event.view_id != view_id {
            return;
        }
        match event.state {
            ViewFocusState::Focused => {
                let scope = self.scope_node(app).as_node();
                let policy = app.get(self).policy.expect("created in init_state");
                let next_focus = match event.direction {
                    ViewFocusDirection::Forward => {
                        policy.find_first_focus(app, scope, true).unwrap_or(scope)
                    }
                    ViewFocusDirection::Backward => policy.find_last_focus(app, scope, true),
                    ViewFocusDirection::Undefined => scope,
                };
                next_focus.request_focus(app, None);
            }
            ViewFocusState::Unfocused => {
                FocusManager::instance(app)
                    .root_scope(app)
                    .request_scope_focus(app);
            }
        }
    }
}

impl State for ViewState {
    type Widget = View;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let scope_node = FocusScopeNode::new(app);
        scope_node.set_debug_label(app, Some("View Scope".to_string()));
        let policy = ReadingOrderTraversalPolicy::new(app).as_policy();
        let this = app.get_mut(self);
        this.scope_node = Some(scope_node);
        this.policy = Some(policy);
        let observer: WidgetsBindingObserverRef = Rc::new(self);
        WidgetsBinding::instance(app).add_observer(app, observer.clone());
        app.get_mut(self).observer = Some(observer);
        let listener = Listener::handle_method(self, ViewState::scope_focus_change_listener);
        scope_node.add_listener(app, listener.clone());
        app.get_mut(self).scope_listener = Some(listener);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        if let Some(observer) = app.get_mut(self).observer.take() {
            WidgetsBinding::instance(app).remove_observer(app, &observer);
        }
        if let Some(listener) = app.get_mut(self).scope_listener.take() {
            self.scope_node(app).remove_listener(app, &listener);
        }
        self.scope_node(app).dispose(app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let (view, child) = {
            let widget = self.widget(app);
            (Rc::clone(&widget.view), widget.child.clone())
        };
        let scope_node = self.scope_node(app);
        let policy = app.get(self).policy.expect("created in init_state");
        let root_scope = FocusManager::instance(app).root_scope(app);
        // Attach this view's focus subtree directly to the root scope rather than nesting it
        // under an enclosing view's scope (which happens when a view is rendered inside another
        // via a `ViewAnchor`). Each view is an independent focus root: nesting would otherwise
        // make an ancestor view report `has_focus` when a descendant view is focused.
        let scoped = FocusTraversalGroup::new(
            FocusScope::with_external_focus_node(child, scope_node).include_semantics(false),
        )
        .policy(policy)
        .parent_node(root_scope.as_node());
        let content = MediaQuery::from_view(None, Rc::clone(&view), scoped);
        RawView::new(view, content).into_widget()
    }
}

/// The lower level workhorse widget for [`View`] that bootstraps a render tree for a
/// `FlutterView`.
///
/// This widget does not have any dependencies on other widgets which is why it can be used
/// as a root widget for the widget tree.
///
/// The [`View`] widget wraps this widget in some additional widgets to expose information
/// about the `FlutterView` to the widget tree. It is not necessary to have a [`View`] widget
/// as the root of the tree, but only [`RawView`] widgets at the roots of the tree will not
/// have access to `MediaQuery` and other information exposed by the [`View`] widget.
pub struct RawView {
    pub key: Option<KeyRef>,
    /// The `FlutterView` into which [`child`](Self::child) is drawn.
    pub view: ViewRef,
    /// The widget below this widget in the tree, which will be drawn into the
    /// [`view`](Self::view).
    pub child: WidgetRef,
}

impl RawView {
    /// Creates a [`RawView`] widget to bootstrap a render tree that is rendered into the
    /// provided `FlutterView`.
    pub fn new<K>(view: ViewRef, child: impl IntoWidget<K>) -> RawView {
        RawView {
            key: None,
            view,
            child: child.into_widget(),
        }
    }

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

impl fmt::Debug for RawView {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawView")
            .field("view", &self.view.id())
            .finish_non_exhaustive()
    }
}

impl StatelessWidget for RawView {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        let view = Rc::clone(&self.view);
        let child = self.child.clone();
        RawViewInternal::new(
            Rc::clone(&self.view),
            Rc::new(
                move |_app: &mut App, _context: BuildContext, owner: Handle<PipelineOwner>| {
                    let scoped = PipelineOwnerScope::new(owner, child.clone());
                    ViewScope::new(Rc::clone(&view), scoped).into_widget()
                },
            ),
        )
        .into_widget()
    }
}

/// Dart's `_RawViewContentBuilder`.
type RawViewContentBuilder = Rc<dyn Fn(&mut App, BuildContext, Handle<PipelineOwner>) -> WidgetRef>;

/// Dart's `_RawViewInternal`: the render object widget behind [`RawView`], keyed by its view
/// so two views never share an element.
pub struct RawViewInternal {
    key: KeyRef,
    view: ViewRef,
    builder: RawViewContentBuilder,
}

impl RawViewInternal {
    fn new(view: ViewRef, builder: RawViewContentBuilder) -> RawViewInternal {
        RawViewInternal {
            key: Rc::new(ValueKey::new(view.id().0)),
            view,
            builder,
        }
    }

    fn into_widget(self) -> WidgetRef {
        Rc::new(self)
    }
}

impl fmt::Debug for RawViewInternal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawViewInternal")
            .field("view", &self.view.id())
            .finish_non_exhaustive()
    }
}

impl RenderObjectWidget for RawViewInternal {
    type RenderObject = RenderView;

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

    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
        RenderView::new(app, None, None, Rc::clone(&self.view)).as_object()
    }
}

impl Widget for RawViewInternal {
    fn key(&self) -> Option<&KeyRef> {
        Some(&self.key)
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        RawViewElement::create(app, this).as_element()
    }

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

    fn widget_type(&self) -> std::any::TypeId {
        std::any::TypeId::of::<RawViewInternal>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }
}

/// Dart's `_RawViewElement`: the root of a render tree, with its own `PipelineOwner`, which asks
/// for a frame of the element's view when a render object in it needs layout or paint.
pub struct RawViewElement {
    element: ElementData,
    render_object_element: RenderObjectElementData,
    /// Dart's `late final _pipelineOwner`, made when the element mounts, where Dart first reads
    /// it: its callbacks reach this element.
    pipeline_owner: Option<Handle<PipelineOwner>>,
    child: Option<AnyElement>,
    /// Is `None` if the view is currently not attached.
    parent_pipeline_owner: Option<Handle<PipelineOwner>>,
}

impl RawViewElement {
    fn create(app: &mut App, widget: WidgetRef) -> Handle<RawViewElement> {
        app.create(RawViewElement {
            element: ElementData::new(widget),
            render_object_element: RenderObjectElementData::default(),
            pipeline_owner: None,
            child: None,
            parent_pipeline_owner: None,
        })
    }

    /// Dart's initializer of `_pipelineOwner`. Semantics callbacks wait with accessibility.
    fn create_pipeline_owner(self: Handle<Self>, app: &mut App) -> Handle<PipelineOwner> {
        // The view is the widget's key, so it is this element's for its whole life.
        let view = Self::widget_of(self.as_element().widget(app)).view.id();
        PipelineOwner::new(
            app,
            Some(Listener::new(move |app| {
                SchedulerBinding::ensure_visual_update(app, FrameTarget::View(view));
            })),
            Some(Rc::new(move |app: &mut App, is_dirty: bool| {
                self.handle_flush_paint(app, is_dirty);
            })),
        )
    }

    fn handle_flush_paint(self: Handle<Self>, app: &mut App, is_dirty: bool) {
        if is_dirty {
            let root_node = self.pipeline_owner(app).root_node(app);
            if let Some(render_view) =
                root_node.and_then(|root_node| root_node.downcast::<RenderView>(app))
            {
                render_view.mark_needs_composite_frame(app);
            }
        }
    }

    /// The `RenderView` at the root of this view's render tree.
    pub fn render_view(self: Handle<Self>, app: &App) -> RenderHandle<RenderView> {
        self.typed_render_object(app)
    }

    /// The pipeline owner that lays out and paints this view's render tree.
    ///
    /// # Panics
    ///
    /// Before the element mounts.
    pub fn pipeline_owner(self: Handle<Self>, app: &App) -> Handle<PipelineOwner> {
        app.get(self)
            .pipeline_owner
            .expect("a RawViewElement makes its pipeline owner when it mounts")
    }

    fn update_child(self: Handle<Self>, app: &mut App) {
        let builder = Self::widget_of(self.as_element().widget(app))
            .builder
            .clone();
        let owner = self.pipeline_owner(app);
        let built = builder(app, self.as_element(), owner);
        let child = app.get(self).child;
        let child = self
            .as_element()
            .update_child(app, child, Some(built), None);
        app.get_mut(self).child = child;
    }

    fn attach_view(
        self: Handle<Self>,
        app: &mut App,
        parent_pipeline_owner: Option<Handle<PipelineOwner>>,
    ) {
        debug_assert!(app.get(self).parent_pipeline_owner.is_none());
        let parent_pipeline_owner = parent_pipeline_owner
            .unwrap_or_else(|| View::pipeline_owner_of(app, self.as_element()));
        let owner = self.pipeline_owner(app);
        parent_pipeline_owner.adopt_child(app, owner);
        let render_view = self.render_view(app);
        RendererBinding::instance(app).add_render_view(app, render_view);
        app.get_mut(self).parent_pipeline_owner = Some(parent_pipeline_owner);
    }

    fn detach_view(self: Handle<Self>, app: &mut App) {
        if let Some(parent_pipeline_owner) = app.get(self).parent_pipeline_owner {
            let render_view = self.render_view(app);
            RendererBinding::instance(app).remove_render_view(app, render_view);
            let owner = self.pipeline_owner(app);
            parent_pipeline_owner.drop_child(app, owner);
            app.get_mut(self).parent_pipeline_owner = None;
        }
    }
}

impl RenderObjectElementWidget for RawViewElement {
    type Widget = RawViewInternal;

    fn widget_of(widget: &WidgetRef) -> &RawViewInternal {
        downcast_widget::<RawViewInternal>(&**widget).expect("a RawViewElement holds its widget")
    }
}

impl RenderObjectElement for RawViewElement {
    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
        &app.get(self).render_object_element
    }

    fn render_object_element_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectElementData {
        &mut app.get_mut(self).render_object_element
    }
}

impl RenderTreeRootElement for RawViewElement {}

impl Element for RawViewElement {
    crate::element_accessors!();

    const IS_RENDER_OBJECT_ELEMENT: bool = true;

    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
        self.render_object_element_data(app).render_object()
    }

    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
        None
    }

    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
        let _ = app;
        false
    }

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

    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
        debug_assert!(app.get(self).child == Some(child));
        app.get_mut(self).child = None;
    }

    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        RenderObjectElement::mount(self, app, parent, new_slot);
        let owner = self.create_pipeline_owner(app);
        app.get_mut(self).pipeline_owner = Some(owner);
        debug_assert!(owner.root_node(app).is_none());
        let render_view = self.render_view(app);
        owner.set_root_node(app, Some(render_view.as_object()));
        self.attach_view(app, None);
        self.update_child(app);
        render_view.prepare_initial_frame(app);
    }

    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        RenderObjectElement::update(self, app, new_widget);
        self.update_child(app);
    }

    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::perform_rebuild(self, app);
        self.update_child(app);
    }

    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        ElementBase::did_change_dependencies(self, app);
        if app.get(self).parent_pipeline_owner.is_none() {
            return;
        }
        let new_parent_pipeline_owner = View::pipeline_owner_of(app, self.as_element());
        if Some(new_parent_pipeline_owner) != app.get(self).parent_pipeline_owner {
            self.detach_view(app);
            self.attach_view(app, Some(new_parent_pipeline_owner));
        }
    }

    fn activate(self: Handle<Self>, app: &mut App) {
        ElementBase::activate(self, app);
        let owner = self.pipeline_owner(app);
        debug_assert!(owner.root_node(app).is_none());
        let render_view = self.render_view(app);
        owner.set_root_node(app, Some(render_view.as_object()));
        self.attach_view(app, None);
    }

    fn deactivate(self: Handle<Self>, app: &mut App) {
        self.detach_view(app);
        let owner = self.pipeline_owner(app);
        debug_assert!(owner.root_node(app) == Some(self.render_view(app).as_object()));
        owner.set_root_node(app, None); // To satisfy the assert in the super class.
        RenderObjectElement::deactivate(self, app);
    }

    fn unmount(self: Handle<Self>, app: &mut App) {
        // Dart disposes its pipeline owner here; ours has no resources beyond the arena
        // slot, which goes with the element.
        let owner = self.pipeline_owner(app);
        RenderObjectElement::unmount(self, app);
        app.destroy(owner);
    }

    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
        RenderObjectElement::update_parent_data(self, app, parent_data_element);
    }

    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderTreeRootElement::update_slot(self, app, new_slot);
    }

    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderTreeRootElement::attach_render_object(self, app, new_slot);
    }

    fn detach_render_object(self: Handle<Self>, app: &mut App) {
        RenderTreeRootElement::detach_render_object(self, app);
    }

    fn insert_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        debug_assert!(slot.is_none());
        let render_view = self.render_view(app);
        render_view.set_child(app, Some(child.as_box().expect("a view holds a box")));
    }

    fn move_render_object_child(
        self: Handle<Self>,
        _app: &mut App,
        _child: AnyRenderObject,
        _old_slot: Option<Slot>,
        _new_slot: Option<Slot>,
    ) {
        debug_assert!(false, "a view has one child");
    }

    fn remove_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        debug_assert!(slot.is_none());
        let render_view = self.render_view(app);
        debug_assert!(render_view.child(app).map(|current| current.as_object()) == Some(child));
        render_view.set_child(app, None);
    }
}

/// Dart's `_ViewScope`: the view a subtree renders into.
pub struct ViewScope {
    pub view: ViewRef,
    pub child: WidgetRef,
}

impl ViewScope {
    /// Creates a `ViewScope`; Dart's arguments are all required.
    pub fn new<K>(view: ViewRef, child: impl IntoWidget<K>) -> ViewScope {
        ViewScope {
            view,
            child: child.into_widget(),
        }
    }
}

impl fmt::Debug for ViewScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ViewScope")
            .field("view", &self.view.id())
            .finish_non_exhaustive()
    }
}

impl InheritedWidget for ViewScope {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &ViewScope) -> bool {
        !std::ptr::addr_eq(Rc::as_ptr(&self.view), Rc::as_ptr(&old_widget.view))
    }
}

/// Dart's `_PipelineOwnerScope`: the pipeline owner a subtree's views attach to.
#[derive(Debug)]
pub struct PipelineOwnerScope {
    pub pipeline_owner: Handle<PipelineOwner>,
    pub child: WidgetRef,
}

impl PipelineOwnerScope {
    /// Creates a `PipelineOwnerScope`; Dart's arguments are all required.
    pub fn new<K>(
        pipeline_owner: Handle<PipelineOwner>,
        child: impl IntoWidget<K>,
    ) -> PipelineOwnerScope {
        PipelineOwnerScope {
            pipeline_owner,
            child: child.into_widget(),
        }
    }
}

impl InheritedWidget for PipelineOwnerScope {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &PipelineOwnerScope) -> bool {
        self.pipeline_owner != old_widget.pipeline_owner
    }
}

/// Dart's `_MultiChildComponentWidget`: views that each bootstrap a render tree of their
/// own, and at most one child that takes part in the surrounding render tree. Subclasses
/// choose what to make public.
pub struct MultiChildComponentWidget {
    key: Option<KeyRef>,
    views: Vec<WidgetRef>,
    child: Option<WidgetRef>,
}

impl MultiChildComponentWidget {
    fn new(key: Option<KeyRef>, views: Vec<WidgetRef>, child: Option<WidgetRef>) -> Self {
        MultiChildComponentWidget { key, views, child }
    }

    fn into_widget(self) -> WidgetRef {
        Rc::new(self)
    }
}

impl fmt::Debug for MultiChildComponentWidget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MultiChildComponentWidget")
            .field("views", &self.views.len())
            .field("has_child", &self.child.is_some())
            .finish()
    }
}

impl Widget for MultiChildComponentWidget {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        MultiChildComponentElement::create(app, this).as_element()
    }

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

    fn widget_type(&self) -> std::any::TypeId {
        std::any::TypeId::of::<MultiChildComponentWidget>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }
}

/// A collection of sibling [`View`]s.
///
/// This widget can only be used in places were a [`View`] widget is allowed, i.e. in a
/// non-rendering zone of the widget tree. In practical terms, it can be used at the root of
/// the widget tree outside of any [`View`] widget, as a child of a [`ViewAnchor`], or in the
/// `view` slot of a [`ViewAnchor`]. It cannot be used as a normal child of a widget that
/// expects a `RenderObject` as its child.
pub struct ViewCollection {
    pub key: Option<KeyRef>,
    /// The [`View`] widgets that are part of this collection.
    pub views: Vec<WidgetRef>,
}

impl ViewCollection {
    pub fn new(views: Vec<WidgetRef>) -> ViewCollection {
        ViewCollection { key: None, views }
    }

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

    pub fn into_widget(self) -> WidgetRef {
        Rc::new(self)
    }
}

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

impl Widget for ViewCollection {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        MultiChildComponentElement::create(app, this).as_element()
    }

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

    fn widget_type(&self) -> std::any::TypeId {
        std::any::TypeId::of::<ViewCollection>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }
}

/// Decorates a `child` widget with a side [`View`].
///
/// This widget must have a [`View`] ancestor, into which the `child` widget is rendered. The
/// `view` widget is rendered into a view of its own, while the `child` renders into the
/// enclosing one.
#[derive(Debug)]
pub struct ViewAnchor {
    pub key: Option<KeyRef>,
    /// The widget that defines the view anchored to this widget.
    pub view: Option<WidgetRef>,
    /// The widget below this widget in the tree, rendered into the enclosing view.
    pub child: WidgetRef,
}

impl ViewAnchor {
    pub fn new<K>(child: impl IntoWidget<K>) -> ViewAnchor {
        ViewAnchor {
            key: None,
            view: None,
            child: child.into_widget(),
        }
    }

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

    /// Dart `ViewAnchor(view:)`.
    pub fn view<K>(mut self, view: impl IntoWidget<K>) -> ViewAnchor {
        self.view = Some(view.into_widget());
        self
    }
}

impl StatelessWidget for ViewAnchor {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        // `LookupBoundary` around the view waits (`## Deferred`).
        MultiChildComponentWidget::new(
            None,
            self.view.iter().cloned().collect(),
            Some(self.child.clone()),
        )
        .into_widget()
    }
}

thread_local! {
    /// Dart's `_MultiChildComponentElement._viewSlot`: one object every view child is
    /// slotted with, told apart from a render slot by identity.
    static VIEW_SLOT: Rc<dyn Any> = Rc::new(());
}

fn view_slot() -> Slot {
    Slot::Custom(VIEW_SLOT.with(Rc::clone))
}

fn is_view_slot(slot: Option<&Slot>) -> bool {
    matches!(slot, Some(Slot::Custom(slot)) if VIEW_SLOT.with(|view_slot| Rc::ptr_eq(view_slot, slot)))
}

/// Dart's `_MultiChildComponentElement`.
pub struct MultiChildComponentElement {
    element: ElementData,
    view_elements: Vec<AnyElement>,
    forgotten_view_elements: HashSet<AnyElement>,
    child_element: Option<AnyElement>,
}

impl MultiChildComponentElement {
    fn create(app: &mut App, widget: WidgetRef) -> Handle<MultiChildComponentElement> {
        app.create(MultiChildComponentElement {
            element: ElementData::new(widget),
            view_elements: Vec::new(),
            forgotten_view_elements: HashSet::new(),
            child_element: None,
        })
    }

    /// The views and the child the widget carries, whichever of the two widget types it is.
    fn parts(widget: &WidgetRef) -> (Vec<WidgetRef>, Option<WidgetRef>) {
        if let Some(collection) = downcast_widget::<ViewCollection>(&**widget) {
            return (collection.views.clone(), None);
        }
        let widget = downcast_widget::<MultiChildComponentWidget>(&**widget)
            .expect("a MultiChildComponentElement holds a ViewCollection or a ViewAnchor's widget");
        (widget.views.clone(), widget.child.clone())
    }

    fn debug_assert_children(self: Handle<Self>, app: &App) -> bool {
        let (views, child) = Self::parts(self.as_element().widget(app));
        let this = app.get(self);
        // Each view widget must have a corresponding element.
        debug_assert!(this.view_elements.len() == views.len());
        // Iff there is a child widget, it must have a corresponding element.
        debug_assert!(this.child_element.is_none() == child.is_none());
        // The child element is not also a view element.
        debug_assert!(
            this.child_element
                .is_none_or(|child| !this.view_elements.contains(&child))
        );
        true
    }

    /// Dart's `_debugCheckMustAttachRenderObject`: in the [`ViewCollection`] configuration,
    /// no ancestor may expect a render object in this element's slot.
    fn debug_check_must_attach_render_object(
        self: Handle<Self>,
        app: &App,
        slot: Option<&Slot>,
    ) -> bool {
        if !cfg!(debug_assertions) || Self::parts(self.as_element().widget(app)).1.is_some() {
            return true;
        }
        let mut has_ancestor_render_object_element = false;
        let mut ancestor_wants_render_object = true;
        self.as_element()
            .visit_ancestor_elements(app, &mut |ancestor| {
                if !ancestor.debug_expects_render_object_for_slot(app, slot) {
                    ancestor_wants_render_object = false;
                    return false;
                }
                if ancestor.is_render_object_element() {
                    has_ancestor_render_object_element = true;
                    return false;
                }
                true
            });
        debug_assert!(
            !(has_ancestor_render_object_element && ancestor_wants_render_object),
            "A ViewCollection cannot be inserted into a slot its ancestor expects a render \
             object in; move it into the view property of a ViewAnchor widget or to the root \
             of the widget tree."
        );
        true
    }

    /// The body of `performRebuild`: the child in this element's own slot, the views in the
    /// view slot.
    fn update_children(self: Handle<Self>, app: &mut App) {
        let (views, child) = Self::parts(self.as_element().widget(app));
        let slot = self.as_element().slot(app);
        let child_element = app.get(self).child_element;
        let child_element = self
            .as_element()
            .update_child(app, child_element, child, slot);
        app.get_mut(self).child_element = child_element;

        let old_views = app.get(self).view_elements.clone();
        let is_forgotten =
            |app: &App, child: AnyElement| app.get(self).forgotten_view_elements.contains(&child);
        let slots: Vec<Option<Slot>> = views.iter().map(|_| Some(view_slot())).collect();
        let view_elements = self.as_element().update_children(
            app,
            &old_views,
            &views,
            Some(&is_forgotten),
            Some(&slots),
        );
        let this = app.get_mut(self);
        this.view_elements = view_elements;
        this.forgotten_view_elements.clear();
    }
}

impl Element for MultiChildComponentElement {
    crate::element_accessors!();

    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        ElementBase::attach_render_object(self, app, new_slot.clone());
        debug_assert!(self.debug_check_must_attach_render_object(app, new_slot.as_ref()));
    }

    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        ElementBase::mount(self, app, parent, new_slot.clone());
        debug_assert!(self.debug_check_must_attach_render_object(app, new_slot.as_ref()));
        debug_assert!(app.get(self).view_elements.is_empty());
        debug_assert!(app.get(self).child_element.is_none());
        self.update_children(app);
        ElementBase::perform_rebuild(self, app);
        debug_assert!(self.debug_assert_children(app));
    }

    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        ElementBase::update_slot(self, app, new_slot.clone());
        debug_assert!(self.debug_check_must_attach_render_object(app, new_slot.as_ref()));
    }

    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        // Cannot switch from ViewAnchor config to ViewCollection config.
        debug_assert!(
            Self::parts(&new_widget).1.is_none()
                == Self::parts(self.as_element().widget(app)).1.is_none()
        );
        ElementBase::update(self, app, new_widget);
        self.as_element().rebuild(app, true);
        debug_assert!(self.debug_assert_children(app));
    }

    fn debug_expects_render_object_for_slot(
        self: Handle<Self>,
        _app: &App,
        slot: Option<&Slot>,
    ) -> bool {
        !is_view_slot(slot)
    }

    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        self.update_children(app);
        ElementBase::perform_rebuild(self, app); // clears the dirty flag
        debug_assert!(self.debug_assert_children(app));
    }

    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
        let this = app.get_mut(self);
        if this.child_element == Some(child) {
            this.child_element = None;
        } else {
            debug_assert!(this.view_elements.contains(&child));
            debug_assert!(!this.forgotten_view_elements.contains(&child));
            this.forgotten_view_elements.insert(child);
        }
    }

    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        let this = app.get(self);
        if let Some(child) = this.child_element {
            visitor(child);
        }
        for child in &this.view_elements {
            if !this.forgotten_view_elements.contains(child) {
                visitor(*child);
            }
        }
    }

    fn debug_doing_build(self: Handle<Self>, _app: &App) -> bool {
        false // This element does not have a concept of "building".
    }

    fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
        app.get(self).child_element
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::rc::Rc;
    use std::time::Duration;

    use waft_embedder::ViewId;
    use waft_foundation::{App, AppCell, Handle};
    use waft_scheduler::{FrameCallback, SchedulerBinding, Ticker};
    use waft_test::TestPlatform;

    use crate::binding::WidgetsBinding;
    use crate::framework::{
        BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
    };
    use crate::test_harness::{
        binding_cell, binding_mount, binding_pump, binding_pump_view, pump_every_view,
    };
    use crate::widgets::basic::SizedBox;
    use crate::widgets::ticker_provider::{
        SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData,
    };

    /// A view's render tree lives under the view's own `PipelineOwner`, which asks for a frame of
    /// its view when a render object in it needs layout or paint.
    #[test]
    fn a_dirty_render_object_under_a_view_schedules_a_frame() {
        let cell = binding_cell();
        let app = cell.borrow();
        let key = Rc::new(GlobalKey::new());
        drop(app);
        binding_mount(
            &cell,
            SizedBox::new()
                .key(key.clone())
                .width(10.0)
                .height(10.0)
                .into_widget(),
        );
        let mut app = cell.borrow_mut();
        for _ in 0..5 {
            binding_pump(&mut app, std::time::Duration::from_millis(16));
        }
        assert!(
            !SchedulerBinding::has_scheduled_frame(&mut app),
            "the tree is idle before the probe"
        );
        let render_object = key
            .current_context(&mut app)
            .expect("mounted")
            .find_render_object(&app)
            .expect("a render object");

        render_object.mark_needs_paint(&mut app);
        assert!(SchedulerBinding::has_scheduled_frame(&mut app));

        binding_pump(&mut app, std::time::Duration::from_millis(32));
        assert!(!SchedulerBinding::has_scheduled_frame(&mut app));
        render_object.mark_needs_layout(&mut app);
        assert!(SchedulerBinding::has_scheduled_frame(&mut app));
    }

    /// Flutter view_test.dart: platform focus parks on the root and restores the view's history.
    #[test]
    fn platform_focus_enters_parks_and_restores_the_view() {
        use crate::{Focus, FocusManager, FocusNode, FocusNodeLeaf, Row};
        use waft_embedder::{
            ViewFocusDirection as Direction, ViewFocusEvent, ViewFocusState as State,
        };
        let cell = binding_cell();
        let (first, last) = {
            let mut app = cell.borrow_mut();
            (FocusNode::new(&mut app), FocusNode::new(&mut app))
        };
        binding_mount(
            &cell,
            crate::Directionality::new(
                waft_embedder::TextDirection::Ltr,
                Row::new().children(vec![
                    Focus::new(SizedBox::new().width(20.0).height(20.0))
                        .focus_node(first.as_node())
                        .into_widget(),
                    Focus::new(SizedBox::new().width(20.0).height(20.0))
                        .focus_node(last.as_node())
                        .into_widget(),
                ]),
            )
            .into_widget(),
        );
        let event = |state, direction| {
            let mut app = cell.borrow_mut();
            let view_id = crate::test_harness::platform_view(&app).id();
            WidgetsBinding::instance(&mut app).handle_view_focus_changed(
                &mut app,
                ViewFocusEvent {
                    view_id,
                    state,
                    direction,
                },
            );
            drop(app);
            cell.checkpoint();
        };
        event(State::Focused, Direction::Forward);
        assert!(first.has_primary_focus(&cell.borrow()));
        event(State::Unfocused, Direction::Undefined);
        {
            let mut app = cell.borrow_mut();
            assert!(
                FocusManager::instance(&mut app)
                    .root_scope(&app)
                    .has_primary_focus(&app)
            );
        }
        event(State::Focused, Direction::Undefined);
        assert!(first.has_primary_focus(&cell.borrow()));
        event(State::Unfocused, Direction::Undefined);
        event(State::Focused, Direction::Backward);
        assert!(last.has_primary_focus(&cell.borrow()));
        event(State::Unfocused, Direction::Undefined);
        event(State::Focused, Direction::Undefined);
        assert!(last.has_primary_focus(&cell.borrow()));
    }

    const FIRST: ViewId = ViewId(1);
    const SECOND: ViewId = ViewId(2);

    /// An app with the widgets binding, on a platform that gives it views [`FIRST`] and
    /// [`SECOND`].
    fn app_with_two_views() -> (Rc<AppCell>, Rc<TestPlatform>) {
        let platform = Rc::new(
            TestPlatform::new()
                .on(waft_embedder::TargetPlatform::MacOS)
                .with_views(&[FIRST, SECOND]),
        );
        let cell = AppCell::with_platform(platform.clone());
        WidgetsBinding::instance(&mut cell.borrow_mut());
        (cell, platform)
    }

    /// How many frames each of [`FIRST`] and [`SECOND`] was presented.
    fn presented(platform: &TestPlatform) -> [u32; 2] {
        [FIRST, SECOND].map(|view| platform.test_view(view).presented())
    }

    /// Attaches `root` as the whole tree and runs the first frame.
    /// `run_widget` and the timer turn that attaches the root and draws the warm-up frame.
    fn mount_root(cell: &AppCell, root: WidgetRef) {
        crate::binding::run_widget(&mut cell.borrow_mut(), root);
        cell.elapse(Duration::ZERO);
    }

    /// The elapsed times a `Ticking` widget's ticker ticked at.
    type Ticks = Rc<RefCell<Vec<Duration>>>;

    /// A widget whose ticker runs from its first build, recording the elapsed time of each tick.
    /// It builds its child, or a small box.
    #[derive(Debug)]
    struct Ticking {
        key: Option<KeyRef>,
        ticks: Ticks,
        child: Option<WidgetRef>,
    }

    impl Ticking {
        fn new(ticks: &Ticks) -> Ticking {
            Ticking {
                key: None,
                ticks: Rc::clone(ticks),
                child: None,
            }
        }

        fn key(mut self, key: KeyRef) -> Ticking {
            self.key = Some(key);
            self
        }

        fn child(mut self, child: WidgetRef) -> Ticking {
            self.child = Some(child);
            self
        }
    }

    impl StatefulWidget for Ticking {
        type State = TickingState;

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

        fn create_state(&self) -> TickingState {
            TickingState {
                state: StateData::new(),
                single_ticker_provider: SingleTickerProviderStateMixinData::new(),
                ticker: None,
            }
        }
    }

    struct TickingState {
        state: StateData<Ticking>,
        single_ticker_provider: SingleTickerProviderStateMixinData,
        ticker: Option<Handle<Ticker>>,
    }

    impl SingleTickerProviderStateMixin for TickingState {
        fn single_ticker_provider_data(
            self: Handle<Self>,
            app: &App,
        ) -> &SingleTickerProviderStateMixinData {
            &app.get(self).single_ticker_provider
        }

        fn single_ticker_provider_data_mut(
            self: Handle<Self>,
            app: &mut App,
        ) -> &mut SingleTickerProviderStateMixinData {
            &mut app.get_mut(self).single_ticker_provider
        }
    }

    impl State for TickingState {
        type Widget = Ticking;
        crate::state_accessors!();

        fn init_state(self: Handle<Self>, app: &mut App) {
            let ticks = Rc::clone(&self.widget(app).ticks);
            let ticker = SingleTickerProviderStateMixin::create_ticker(
                self,
                app,
                FrameCallback::new(move |_app, elapsed| ticks.borrow_mut().push(elapsed)),
            );
            let _ticking = ticker.start(app);
            app.get_mut(self).ticker = Some(ticker);
        }

        fn activate(self: Handle<Self>, app: &mut App) {
            SingleTickerProviderStateMixin::activate(self, app);
        }

        fn dispose(self: Handle<Self>, app: &mut App) {
            if let Some(ticker) = app.get_mut(self).ticker.take() {
                ticker.dispose(app);
            }
            SingleTickerProviderStateMixin::dispose(self, app);
        }

        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
            self.widget(app)
                .child
                .clone()
                .unwrap_or_else(|| SizedBox::new().width(10.0).height(10.0).into_widget())
        }
    }

    fn millis(ms: u64) -> Duration {
        Duration::from_millis(ms)
    }

    #[test]
    fn a_view_collection_bootstraps_one_render_tree_per_view() {
        use waft_rendering::RendererBinding;

        let (cell, platform) = app_with_two_views();
        mount_root(
            &cell,
            super::ViewCollection::new(vec![
                super::View::new(platform.test_view(FIRST), SizedBox::new()).into_widget(),
                super::View::new(platform.test_view(SECOND), SizedBox::new()).into_widget(),
            ])
            .into_widget(),
        );
        let mut app = cell.borrow_mut();
        let binding = RendererBinding::instance(&mut app);
        assert_eq!(binding.render_views(&app).len(), 2);
        assert_eq!(platform.test_view(FIRST).presented(), 1);
        assert_eq!(platform.test_view(SECOND).presented(), 1);
    }

    #[test]
    fn a_view_anchor_renders_its_child_in_place_and_its_view_beside_it() {
        use waft_rendering::RendererBinding;

        let (cell, platform) = app_with_two_views();
        mount_root(
            &cell,
            super::View::new(
                platform.test_view(FIRST),
                super::ViewAnchor::new(SizedBox::new().width(10.0).height(10.0)).view(
                    super::View::new(platform.test_view(SECOND), SizedBox::new()),
                ),
            )
            .into_widget(),
        );
        let mut app = cell.borrow_mut();
        let binding = RendererBinding::instance(&mut app);
        assert_eq!(binding.render_views(&app).len(), 2);
        assert_eq!(platform.test_view(FIRST).presented(), 1);
        assert_eq!(platform.test_view(SECOND).presented(), 1);
    }

    #[test]
    fn a_view_whose_frames_are_held_stays_idle_while_another_animates() {
        let (cell, platform) = app_with_two_views();
        let (shown, hidden) = (Ticks::default(), Ticks::default());
        mount_root(
            &cell,
            super::ViewCollection::new(vec![
                super::View::new(platform.test_view(FIRST), Ticking::new(&shown)).into_widget(),
                super::View::new(platform.test_view(SECOND), Ticking::new(&hidden)).into_widget(),
            ])
            .into_widget(),
        );
        let (hidden_ticks, hidden_presented) = (
            hidden.borrow().len(),
            platform.test_view(SECOND).presented(),
        );

        // The host holds the frames asked of a hidden window: only the shown view's come.
        for frame in 1..=5 {
            binding_pump_view(&mut cell.borrow_mut(), FIRST, millis(16 * frame));
        }
        assert_eq!(shown.borrow().len(), 1 + 5, "the shown view animates");
        assert_eq!(
            hidden.borrow().len(),
            hidden_ticks,
            "the hidden view's ticker waits"
        );
        assert_eq!(
            platform.test_view(SECOND).presented(),
            hidden_presented,
            "the hidden view draws nothing"
        );
        assert!(
            platform.has_frame_request(SECOND),
            "its ticker's request is held, not lost"
        );

        // Shown again, it is given the frame it asked for.
        binding_pump(&mut cell.borrow_mut(), millis(96));
        assert_eq!(hidden.borrow().len(), hidden_ticks + 1);
    }

    #[test]
    fn two_views_at_different_rates_each_animate_at_their_own() {
        let (cell, platform) = app_with_two_views();
        let (slow, fast) = (Ticks::default(), Ticks::default());
        mount_root(
            &cell,
            super::ViewCollection::new(vec![
                super::View::new(platform.test_view(FIRST), Ticking::new(&slow)).into_widget(),
                super::View::new(platform.test_view(SECOND), Ticking::new(&fast)).into_widget(),
            ])
            .into_widget(),
        );
        slow.borrow_mut().clear();
        fast.borrow_mut().clear();

        // The first view is on a 60 Hz screen, the second on a 120 Hz one. Both tickers started
        // in the warm-up frame, at the time the epoch then starts again from: the first frame
        // after it, the second view's at 8 ms. So each ticks at its own view's frames with the
        // time since 8 ms.
        for ms in (8..=48).step_by(8) {
            if ms % 16 == 0 {
                binding_pump_view(&mut cell.borrow_mut(), FIRST, millis(ms));
            }
            binding_pump_view(&mut cell.borrow_mut(), SECOND, millis(ms));
        }
        assert_eq!(*slow.borrow(), [millis(8), millis(24), millis(40)]);
        assert_eq!(
            *fast.borrow(),
            [0, 8, 16, 24, 32, 40].map(millis),
            "each ticks at its own view's frames"
        );
    }

    #[test]
    fn a_global_key_subtree_moved_to_another_view_keeps_its_state_and_ticks_there() {
        let (cell, platform) = app_with_two_views();
        let key = GlobalKey::new();
        let ticks = Ticks::default();
        let tree = |in_first: bool| -> WidgetRef {
            let ticking =
                || -> WidgetRef { Ticking::new(&ticks).key(Rc::new(key.clone())).into_widget() };
            let (first, second): (WidgetRef, WidgetRef) = if in_first {
                (ticking(), SizedBox::new().into_widget())
            } else {
                (SizedBox::new().into_widget(), ticking())
            };
            super::ViewCollection::new(vec![
                super::View::new(platform.test_view(FIRST), first).into_widget(),
                super::View::new(platform.test_view(SECOND), second).into_widget(),
            ])
            .into_widget()
        };
        mount_root(&cell, tree(true));
        let state = key
            .current_state::<TickingState>(&mut cell.borrow_mut())
            .expect("mounted in the first view");

        mount_root(&cell, tree(false));
        assert_eq!(
            key.current_state::<TickingState>(&mut cell.borrow_mut()),
            Some(state),
            "the same state, now in the second view"
        );

        let before = ticks.borrow().len();
        binding_pump_view(&mut cell.borrow_mut(), FIRST, millis(16));
        assert_eq!(
            ticks.borrow().len(),
            before,
            "no tick at the old view's frame"
        );
        binding_pump_view(&mut cell.borrow_mut(), SECOND, millis(16));
        assert_eq!(
            ticks.borrow().len(),
            before + 1,
            "it ticks at its new view's"
        );
    }

    #[test]
    fn an_anchored_view_paints_only_at_its_own_frame() {
        let (cell, platform) = app_with_two_views();
        let key = GlobalKey::new();
        mount_root(
            &cell,
            super::View::new(
                platform.test_view(FIRST),
                super::ViewAnchor::new(SizedBox::new().width(10.0).height(10.0)).view(
                    super::View::new(
                        platform.test_view(SECOND),
                        SizedBox::new().key(Rc::new(key.clone())),
                    ),
                ),
            )
            .into_widget(),
        );
        let mut app = cell.borrow_mut();
        let in_anchored = key
            .current_context(&mut app)
            .and_then(|context| context.find_render_object(&app))
            .expect("the anchored view's render object");
        // The frame after the warm-up frame presents each view again.
        pump_every_view(&mut app, millis(8));
        assert_eq!(presented(&platform), [2, 2]);
        platform.take_frame_requests();

        in_anchored.mark_needs_paint(&mut app);
        assert_eq!(
            platform.take_frame_requests(),
            [SECOND],
            "asked of the anchored view alone"
        );
        binding_pump_view(&mut app, FIRST, millis(16));
        assert_eq!(
            presented(&platform),
            [2, 2],
            "the enclosing view had nothing to paint, and left the anchored view alone"
        );
        assert!(in_anchored.debug_needs_paint(&app));

        binding_pump_view(&mut app, SECOND, millis(16));
        assert_eq!(presented(&platform), [2, 3]);
        assert!(!in_anchored.debug_needs_paint(&app));
    }

    #[test]
    fn a_request_for_another_view_made_during_a_frame_is_not_lost() {
        let (cell, platform) = app_with_two_views();
        let key = GlobalKey::new();
        mount_root(
            &cell,
            super::ViewCollection::new(vec![
                super::View::new(platform.test_view(FIRST), SizedBox::new()).into_widget(),
                super::View::new(
                    platform.test_view(SECOND),
                    SizedBox::new().key(Rc::new(key.clone())),
                )
                .into_widget(),
            ])
            .into_widget(),
        );
        let mut app = cell.borrow_mut();
        let in_second = key
            .current_context(&mut app)
            .and_then(|context| context.find_render_object(&app))
            .expect("the second view's render object");
        platform.take_frame_requests();

        SchedulerBinding::schedule_frame_callback(
            &mut app,
            FrameCallback::new(move |app, _time_stamp| in_second.mark_needs_paint(app)),
            Some(FIRST),
            false,
            true,
        );
        binding_pump(&mut app, millis(16));
        assert_eq!(
            platform.take_frame_requests(),
            [SECOND],
            "asked during the first view's frame"
        );
        binding_pump_view(&mut app, SECOND, millis(32));
        assert_eq!(platform.test_view(SECOND).presented(), 2);
    }

    /// Two views, each holding a keyed subtree, under a keyed subtree above both; answers the
    /// keys: above, in the first view, in the second.
    fn mount_keyed_views(cell: &AppCell, platform: &TestPlatform) -> [GlobalKey; 3] {
        let keys = [GlobalKey::new(), GlobalKey::new(), GlobalKey::new()];
        let keyed = |key: &GlobalKey, child: WidgetRef| -> WidgetRef {
            crate::KeyedSubtree::new(child)
                .key(Rc::new(key.clone()))
                .into_widget()
        };
        mount_root(
            cell,
            keyed(
                &keys[0],
                super::ViewCollection::new(vec![
                    super::View::new(
                        platform.test_view(FIRST),
                        keyed(&keys[1], SizedBox::new().into_widget()),
                    )
                    .into_widget(),
                    super::View::new(
                        platform.test_view(SECOND),
                        keyed(&keys[2], SizedBox::new().into_widget()),
                    )
                    .into_widget(),
                ])
                .into_widget(),
            ),
        );
        keys
    }

    /// Marks the element `key` is on dirty.
    fn mark_needs_build(app: &mut App, key: &GlobalKey) {
        key.current_context(app)
            .expect("mounted")
            .mark_needs_build(app);
    }

    #[test]
    fn a_dirty_element_asks_for_a_frame_of_its_own_view_alone() {
        let (cell, platform) = app_with_two_views();
        let [_, in_first, in_second] = mount_keyed_views(&cell, &platform);
        let mut app = cell.borrow_mut();
        platform.take_frame_requests();

        mark_needs_build(&mut app, &in_second);
        assert_eq!(platform.take_frame_requests(), [SECOND]);
        mark_needs_build(&mut app, &in_first);
        assert_eq!(
            platform.take_frame_requests(),
            [FIRST],
            "another view is asked too before the build pass, though one view was asked already"
        );

        binding_pump_view(&mut app, FIRST, millis(16));
        assert!(
            !in_second
                .current_context(&mut app)
                .expect("mounted")
                .dirty(&app),
            "the first view's frame built the second view's dirty element"
        );
    }

    #[test]
    fn a_dirty_element_above_every_view_asks_for_a_frame_of_each() {
        let (cell, platform) = app_with_two_views();
        let [above, _, _] = mount_keyed_views(&cell, &platform);
        let mut app = cell.borrow_mut();
        platform.take_frame_requests();

        mark_needs_build(&mut app, &above);
        assert_eq!(platform.take_frame_requests(), [FIRST, SECOND]);
    }

    #[test]
    fn a_post_frame_callback_for_no_view_runs_while_another_view_is_hidden() {
        let (cell, platform) = app_with_two_views();
        mount_keyed_views(&cell, &platform);
        let mut app = cell.borrow_mut();
        let ran = Rc::new(RefCell::new(Vec::new()));
        for (name, view) in [("no view", None), ("second view", Some(SECOND))] {
            let ran = Rc::clone(&ran);
            SchedulerBinding::add_post_frame_callback(
                &mut app,
                FrameCallback::new(move |_app, _time_stamp| ran.borrow_mut().push(name)),
                view,
            );
        }

        // The second view is hidden: the host gives frames to the first alone.
        binding_pump_view(&mut app, FIRST, millis(16));
        assert_eq!(*ran.borrow(), ["no view"]);
        binding_pump_view(&mut app, SECOND, millis(16));
        assert_eq!(*ran.borrow(), ["no view", "second view"]);
    }

    #[test]
    fn a_view_that_painted_nothing_presents_nothing() {
        let (cell, platform) = app_with_two_views();
        let [_, _, in_second] = mount_keyed_views(&cell, &platform);
        let mut app = cell.borrow_mut();
        // The frame after the warm-up frame presents each view again.
        pump_every_view(&mut app, millis(8));
        assert_eq!(presented(&platform), [2, 2]);

        in_second
            .current_context(&mut app)
            .and_then(|context| context.find_render_object(&app))
            .expect("the second view's render object")
            .mark_needs_paint(&mut app);
        pump_every_view(&mut app, millis(16));
        assert_eq!(
            presented(&platform),
            [2, 3],
            "the first view keeps showing its last frame"
        );
    }

    #[test]
    fn a_ticker_whose_widget_moves_to_another_view_while_its_view_is_hidden_ticks_there() {
        let (cell, platform) = app_with_two_views();
        let ticks = Ticks::default();
        let key = GlobalKey::new();
        let above = GlobalKey::new();
        let in_first = Rc::new(std::cell::Cell::new(true));
        let tree = {
            let (ticks, key, in_first) = (Rc::clone(&ticks), key.clone(), Rc::clone(&in_first));
            let platform = Rc::clone(&platform);
            crate::Builder::new(move |_app, _context| {
                let ticking = Ticking::new(&ticks).key(Rc::new(key.clone())).into_widget();
                let empty = || SizedBox::new().into_widget();
                let (first, second) = if in_first.get() {
                    (ticking, empty())
                } else {
                    (empty(), ticking)
                };
                super::ViewCollection::new(vec![
                    super::View::new(platform.test_view(FIRST), first).into_widget(),
                    super::View::new(platform.test_view(SECOND), second).into_widget(),
                ])
                .into_widget()
            })
            .key(Rc::new(above.clone()))
            .into_widget()
        };
        mount_root(&cell, tree);
        let mut app = cell.borrow_mut();
        binding_pump_view(&mut app, FIRST, millis(16));
        let state = key.current_state::<TickingState>(&mut app);

        // The first view is hidden from now on: the host gives the second view the frames it
        // asks for, and the first none. The second view's frame moves the widget, whose tick was
        // due at the first view's frame.
        in_first.set(false);
        mark_needs_build(&mut app, &above);
        let before = ticks.borrow().len();
        let mut second_view_frames = 0;
        for frame in 2..=5 {
            if platform.take_frame_request(SECOND) {
                second_view_frames += 1;
                binding_pump_view(&mut app, SECOND, millis(16 * frame));
            }
        }
        assert_eq!(
            key.current_state::<TickingState>(&mut app),
            state,
            "the same state"
        );
        assert_eq!(second_view_frames, 4, "the second view asks for each frame");
        assert_eq!(
            ticks.borrow().len(),
            before + 3,
            "it ticks at each of the second view's frames after the one that moved it"
        );
    }

    #[test]
    fn a_ticker_above_every_view_ticks_at_every_frame() {
        let (cell, platform) = app_with_two_views();
        let ticks = Ticks::default();
        mount_root(
            &cell,
            Ticking::new(&ticks)
                .child(
                    super::ViewCollection::new(vec![
                        super::View::new(platform.test_view(FIRST), SizedBox::new()).into_widget(),
                        super::View::new(platform.test_view(SECOND), SizedBox::new()).into_widget(),
                    ])
                    .into_widget(),
                )
                .into_widget(),
        );
        let mut app = cell.borrow_mut();
        ticks.borrow_mut().clear();

        // Both views are on one screen, then the second is on a screen of its own. The epoch
        // starts again at the first frame after the warm-up frame.
        pump_every_view(&mut app, millis(16));
        pump_every_view(&mut app, millis(32));
        binding_pump_view(&mut app, SECOND, millis(40));
        assert_eq!(*ticks.borrow(), [0, 16, 24].map(millis));
    }
}