gpui-fast 0.1.5

gpui: GPUI with gpui-fast rendering and layout optimizations
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
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
// Modified by Longbridge for gpui-fast.
//! Tests of views drawn again from what they drew on the last frame. See
//! [`crate::fast::retained`].

use crate::{
    AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
    Render, StyleRefinement, Styled as _, TestAppContext, Window, WindowHandle, div,
    prelude::FluentBuilder as _, px,
};
use std::{cell::Cell, rc::Rc};

struct Row {
    label: u32,
    builds: Rc<Cell<usize>>,
}

impl Render for Row {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        div()
            .size_full()
            .bg(crate::black())
            .hover(|style| style.bg(crate::white()))
            .child(format!("row {}", self.label))
    }
}

struct Rows {
    row: Entity<Row>,
    covered: bool,
}

impl Render for Rows {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .relative()
            .size(px(300.))
            .child(
                self.row
                    .clone()
                    .cached(StyleRefinement::default().w(px(100.)).h(px(20.))),
            )
            .when(self.covered, |this| {
                this.child(div().absolute().top_0().left_0().size(px(200.)).occlude())
            })
    }
}

fn window(cx: &mut TestAppContext) -> (WindowHandle<Rows>, Entity<Row>, Rc<Cell<usize>>) {
    let builds = Rc::new(Cell::new(0));
    let window = cx.add_window({
        let builds = builds.clone();
        move |_, cx| Rows {
            row: cx.new(|_| Row { label: 0, builds }),
            covered: false,
        }
    });
    let row = window.update(cx, |rows, _, _| rows.row.clone()).unwrap();
    (window, row, builds)
}

fn draw(cx: &mut TestAppContext, window: WindowHandle<Rows>) -> Vec<String> {
    cx.update_window(window.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.describe_rendered_frame()
    })
    .unwrap()
}

fn notify_parent(cx: &mut TestAppContext, window: WindowHandle<Rows>) {
    window.update(cx, |_, _, cx| cx.notify()).unwrap();
}

fn move_mouse(cx: &mut TestAppContext, window: WindowHandle<Rows>, x: f32, y: f32) {
    cx.update_window(window.into(), |_, window, cx| {
        window.simulate_mouse_move(crate::point(px(x), px(y)), cx);
    })
    .unwrap();
}

/// A cached view painted while the pointer was over something in it that
/// has a hover style is rendered again once the pointer leaves, even
/// though the element never saw the pointer arrive.
#[test]
fn a_cached_view_is_rendered_again_when_a_hover_it_was_painted_by_changes() {
    let mut cx = TestAppContext::single();
    let (window, _, builds) = window(&mut cx);
    move_mouse(&mut cx, window, 10., 10.);
    let hovered = draw(&mut cx, window);
    notify_parent(&mut cx, window);
    draw(&mut cx, window);
    let builds_before = builds.get();

    move_mouse(&mut cx, window, 250., 250.);
    let left = draw(&mut cx, window);
    assert_eq!(builds.get(), builds_before + 1);
    assert_ne!(hovered, left);
}

/// A cached view reused for a while keeps the layout nodes it was laid
/// out with, so rendering it again finds them all.
#[test]
fn a_reused_cached_view_keeps_its_layout_nodes() {
    let mut cx = TestAppContext::single();
    let (window, row, builds) = window(&mut cx);
    draw(&mut cx, window);
    for _ in 0..3 {
        notify_parent(&mut cx, window);
        draw(&mut cx, window);
    }
    assert_eq!(
        builds.get(),
        1,
        "the view is reused while its parent renders"
    );

    cx.update_window(window.into(), |_, window, _| window.reset_layout_stats())
        .unwrap();
    row.update(&mut cx, |row, cx| {
        row.label = 7;
        cx.notify();
    });
    draw(&mut cx, window);
    assert_eq!(builds.get(), 2);
    let stats = cx
        .update_window(window.into(), |_, window, _| window.layout_stats())
        .unwrap();
    assert_eq!(
        stats.nodes_created, 0,
        "the view's nodes should have been kept while it was reused"
    );
    assert!(stats.nodes_reused > 0);
}

/// Something drawn over a hovered cached view is found out only when the
/// view paints; it is rendered on the next frame, which is asked for.
#[test]
fn a_cached_view_covered_while_hovered_is_rendered_on_the_next_frame() {
    let mut cx = TestAppContext::single();
    let (window, _, builds) = window(&mut cx);
    move_mouse(&mut cx, window, 10., 10.);
    let hovered = draw(&mut cx, window);
    notify_parent(&mut cx, window);
    draw(&mut cx, window);
    let builds_before = builds.get();

    window
        .update(&mut cx, |rows, _, cx| {
            rows.covered = true;
            cx.notify();
        })
        .unwrap();
    let frame_asked_for = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, _| {
            !window.next_frame_callbacks.borrow().is_empty()
        })
        .unwrap()
    };
    let mut asked_for_a_frame = frame_asked_for(&mut cx);
    let mut look = None;
    for _ in 0..3 {
        if builds.get() > builds_before {
            break;
        }
        asked_for_a_frame |= frame_asked_for(&mut cx);
        look = Some(draw(&mut cx, window));
    }
    assert_eq!(builds.get(), builds_before + 1);
    assert!(
        asked_for_a_frame,
        "a frame should be asked for to render it"
    );
    assert_ne!(Some(hovered), look);
}

struct Counted {
    label: usize,
    model: Option<Entity<Model>>,
    builds: Rc<Cell<usize>>,
}

struct Model(usize);

impl Render for Counted {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        let model = self.model.as_ref().map_or(0, |model| model.read(cx).0);
        div()
            .flex()
            .flex_row()
            .child(format!("{} {}", self.label, model))
    }
}

struct Siblings {
    first: Entity<Counted>,
    second: Entity<Counted>,
    spacer: f32,
}

impl Render for Siblings {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .child(div().h(px(self.spacer)))
            .child(self.first.clone())
            .child(self.second.clone())
    }
}

struct SiblingsWindow {
    window: WindowHandle<Siblings>,
    first: Entity<Counted>,
    model: Entity<Model>,
    first_builds: Rc<Cell<usize>>,
    second_builds: Rc<Cell<usize>>,
}

fn siblings(cx: &mut TestAppContext) -> SiblingsWindow {
    let first_builds = Rc::new(Cell::new(0));
    let second_builds = Rc::new(Cell::new(0));
    let model = cx.new(|_| Model(0));
    let window = cx.add_window({
        let (first_builds, second_builds, model) =
            (first_builds.clone(), second_builds.clone(), model.clone());
        move |_, cx| Siblings {
            first: cx.new(|_| Counted {
                label: 1,
                model: None,
                builds: first_builds,
            }),
            second: cx.new(|_| Counted {
                label: 2,
                model: Some(model),
                builds: second_builds,
            }),
            spacer: 10.,
        }
    });
    let first = window.update(cx, |view, _, _| view.first.clone()).unwrap();
    SiblingsWindow {
        window,
        first,
        model,
        first_builds,
        second_builds,
    }
}

fn draw_siblings(cx: &mut TestAppContext, window: WindowHandle<Siblings>) -> Vec<String> {
    cx.update_window(window.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.describe_rendered_frame()
    })
    .unwrap()
}

/// A view that is not cached is drawn again from the
/// last frame while nothing it read changed, even when the view around it
/// is rendered again, and rendered again once something it read did.
#[test]
fn a_view_is_rendered_again_only_when_something_it_read_changed() {
    let mut cx = TestAppContext::single();
    let s = siblings(&mut cx);
    draw_siblings(&mut cx, s.window);
    assert_eq!((s.first_builds.get(), s.second_builds.get()), (1, 1));

    s.window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
    draw_siblings(&mut cx, s.window);
    assert_eq!(
        (s.first_builds.get(), s.second_builds.get()),
        (1, 1),
        "notifying the parent leaves its children alone"
    );

    s.first.update(&mut cx, |first, cx| {
        first.label = 3;
        cx.notify();
    });
    draw_siblings(&mut cx, s.window);
    assert_eq!((s.first_builds.get(), s.second_builds.get()), (2, 1));

    s.model.update(&mut cx, |model, cx| {
        model.0 = 5;
        cx.notify();
    });
    draw_siblings(&mut cx, s.window);
    assert_eq!(
        (s.first_builds.get(), s.second_builds.get()),
        (2, 2),
        "a model the view read changing renders it again, unobserved"
    );

    cx.update_window(s.window.into(), |_, window, _| window.refresh())
        .unwrap();
    draw_siblings(&mut cx, s.window);
    assert_eq!((s.first_builds.get(), s.second_builds.get()), (3, 3));
}

/// A view that moved is built again where it went, at the layout nodes it
/// kept, and draws what a window drawing from scratch draws.
#[test]
fn a_moved_view_is_built_again_at_its_layout() {
    let mut cx = TestAppContext::single();
    let s = siblings(&mut cx);
    draw_siblings(&mut cx, s.window);
    s.window
        .update(&mut cx, |view, _, cx| {
            view.spacer = 30.;
            cx.notify();
        })
        .unwrap();
    cx.update_window(s.window.into(), |_, window, _| window.reset_layout_stats())
        .unwrap();
    let moved = draw_siblings(&mut cx, s.window);
    assert_eq!((s.first_builds.get(), s.second_builds.get()), (2, 2));
    let stats = cx
        .update_window(s.window.into(), |_, window, _| window.layout_stats())
        .unwrap();
    assert_eq!(stats.nodes_created, 0, "the moved views keep their nodes");

    cx.update_window(s.window.into(), |_, window, _| {
        window.forget_retained_state()
    })
    .unwrap();
    assert_eq!(moved, draw_siblings(&mut cx, s.window));
}

/// With retention turned off, every view is rendered every frame.
#[test]
fn views_are_rendered_every_frame_without_retention() {
    let mut cx = TestAppContext::single();
    let s = siblings(&mut cx);
    cx.update_window(s.window.into(), |_, window, _| {
        window.set_view_retention(false)
    })
    .unwrap();
    draw_siblings(&mut cx, s.window);
    let before = (s.first_builds.get(), s.second_builds.get());
    s.window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
    draw_siblings(&mut cx, s.window);
    assert!(s.first_builds.get() > before.0 && s.second_builds.get() > before.1);
}

struct Sized {
    row: Entity<Row>,
    width: f32,
}

impl Render for Sized {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().child(
            self.row
                .clone()
                .cached(StyleRefinement::default().w(px(self.width)).h(px(20.))),
        )
    }
}

/// A cached view is rendered again when its bounds change or the window is
/// refreshed, and otherwise reused, showing what it showed.
#[test]
fn a_cached_view_is_rendered_again_only_when_it_has_to_be() {
    let mut cx = TestAppContext::single();
    let builds = Rc::new(Cell::new(0));
    let window = cx.add_window({
        let builds = builds.clone();
        move |_, cx| Sized {
            row: cx.new(|_| Row { label: 0, builds }),
            width: 100.,
        }
    });
    let draw = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.describe_rendered_frame()
        })
        .unwrap()
    };
    let change = |cx: &mut TestAppContext, f: fn(&mut Sized)| {
        window
            .update(cx, |view, _, cx| {
                f(view);
                cx.notify();
            })
            .unwrap()
    };

    let first = draw(&mut cx);
    assert_eq!(builds.get(), 1);
    change(&mut cx, |_| {});
    assert_eq!(first, draw(&mut cx), "a reused view shows what it showed");
    assert_eq!(builds.get(), 1);

    change(&mut cx, |view| view.width = 150.);
    draw(&mut cx);
    assert_eq!(builds.get(), 2, "new bounds render it again");

    cx.update_window(window.into(), |_, window, _| window.refresh())
        .unwrap();
    draw(&mut cx);
    assert_eq!(builds.get(), 3, "a refreshed window renders every view");

    cx.simulate_window_resize(window.into(), crate::size(px(800.), px(600.)));
    draw(&mut cx);
    change(&mut cx, |_| {});
    draw(&mut cx);
    assert_eq!(
        builds.get(),
        4,
        "a resize refreshes once, then it is reused"
    );
}

struct PopoverRow {
    builds: Rc<Cell<usize>>,
}

impl Render for PopoverRow {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        div().size_full().child(crate::deferred(
            div()
                .id("popover")
                .w(px(50.))
                .h(px(20.))
                .bg(crate::black())
                .hover(|style| style.bg(crate::white())),
        ))
    }
}

struct WithPopover {
    row: Entity<PopoverRow>,
}

impl Render for WithPopover {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().child(
            self.row
                .clone()
                .cached(StyleRefinement::default().w(px(100.)).h(px(20.))),
        )
    }
}

/// Something a cached view draws deferred, such as a popover, is prepainted
/// and painted after the view, but is part of what the view drew: the pointer
/// moving over it changes how the view looks.
#[test]
fn a_cached_view_is_rendered_again_when_the_pointer_moves_over_what_it_deferred() {
    let mut cx = TestAppContext::single();
    let builds = Rc::new(Cell::new(0));
    let window = cx.add_window({
        let builds = builds.clone();
        move |_, cx| WithPopover {
            row: cx.new(|_| PopoverRow { builds }),
        }
    });
    let draw = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.describe_rendered_frame()
        })
        .unwrap()
    };
    let move_to = |cx: &mut TestAppContext, x: f32, y: f32| {
        cx.update_window(window.into(), |_, window, cx| {
            window.simulate_mouse_move(crate::point(px(x), px(y)), cx);
        })
        .unwrap();
    };

    // The pointer starts out at the origin, over the popover.
    draw(&mut cx);
    assert_eq!(builds.get(), 1);
    move_to(&mut cx, 500., 500.);
    let away = draw(&mut cx);
    assert_eq!(
        builds.get(),
        2,
        "the pointer leaving the popover changes its look"
    );
    window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
    draw(&mut cx);
    assert_eq!(builds.get(), 2, "and nothing else does");

    move_to(&mut cx, 10., 10.);
    let over = draw(&mut cx);
    assert_eq!(builds.get(), 3, "the pointer coming back changes it again");
    assert_ne!(away, over);

    move_to(&mut cx, 500., 500.);
    let away_again = draw(&mut cx);
    assert_eq!(builds.get(), 4);
    assert_eq!(away, away_again);
}

/// An input handler that answers every question about its text with its
/// name, so a test can tell which one the platform was handed.
struct NamedInput(&'static str);

impl crate::InputHandler for NamedInput {
    fn selected_text_range(
        &mut self,
        _: bool,
        _: &mut Window,
        _: &mut crate::App,
    ) -> Option<crate::UTF16Selection> {
        None
    }
    fn marked_text_range(
        &mut self,
        _: &mut Window,
        _: &mut crate::App,
    ) -> Option<std::ops::Range<usize>> {
        None
    }
    fn text_for_range(
        &mut self,
        _: std::ops::Range<usize>,
        _: &mut Option<std::ops::Range<usize>>,
        _: &mut Window,
        _: &mut crate::App,
    ) -> Option<String> {
        Some(self.0.to_string())
    }
    fn replace_text_in_range(
        &mut self,
        _: Option<std::ops::Range<usize>>,
        _: &str,
        _: &mut Window,
        _: &mut crate::App,
    ) {
    }
    fn replace_and_mark_text_in_range(
        &mut self,
        _: Option<std::ops::Range<usize>>,
        _: &str,
        _: Option<std::ops::Range<usize>>,
        _: &mut Window,
        _: &mut crate::App,
    ) {
    }
    fn unmark_text(&mut self, _: &mut Window, _: &mut crate::App) {}
    fn bounds_for_range(
        &mut self,
        _: std::ops::Range<usize>,
        _: &mut Window,
        _: &mut crate::App,
    ) -> Option<crate::Bounds<crate::Pixels>> {
        None
    }
    fn character_index_for_point(
        &mut self,
        _: crate::Point<crate::Pixels>,
        _: &mut Window,
        _: &mut crate::App,
    ) -> Option<usize> {
        None
    }
}

pub(super) fn text_input(focus: crate::FocusHandle, name: &'static str) -> impl IntoElement {
    crate::canvas(
        |_, _, _| {},
        move |_, _, window, cx| window.handle_input(&focus, NamedInput(name), cx),
    )
    .size_full()
}

struct Field {
    focus: crate::FocusHandle,
    builds: Rc<Cell<usize>>,
}

impl Render for Field {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        text_input(self.focus.clone(), "inside")
    }
}

struct Inputs {
    field: Entity<Field>,
    outside: crate::FocusHandle,
    cached_first: bool,
}

impl Render for Inputs {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        let cached = self
            .field
            .clone()
            .cached(StyleRefinement::default().w(px(100.)).h(px(20.)))
            .into_any_element();
        let outside = div()
            .w(px(100.))
            .h(px(20.))
            .child(text_input(self.outside.clone(), "outside"))
            .into_any_element();
        let children = if self.cached_first {
            [cached, outside]
        } else {
            [outside, cached]
        };
        div().children(children)
    }
}

/// The input handler of a focused field inside a reused cached view is
/// handed to the platform on every frame, and a field focused elsewhere
/// takes over.
#[test]
fn a_reused_cached_view_hands_the_platform_its_input_handler() {
    for cached_first in [true, false] {
        let mut cx = TestAppContext::single();
        let builds = Rc::new(Cell::new(0));
        let window = cx.add_window({
            let builds = builds.clone();
            move |_, cx| Inputs {
                field: cx.new(|cx| Field {
                    focus: cx.focus_handle(),
                    builds,
                }),
                outside: cx.focus_handle(),
                cached_first,
            }
        });
        let (inside, outside) = window
            .update(&mut cx, |view, _, cx| {
                (view.field.read(cx).focus.clone(), view.outside.clone())
            })
            .unwrap();
        let draw = |cx: &mut TestAppContext| {
            cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
                .unwrap()
        };
        // Asked outside of any update, as the platform asks it.
        let handed = |cx: &mut TestAppContext| {
            let mut handler = cx
                .update_window(window.into(), |_, window, _| {
                    window.platform_window.take_input_handler()
                })
                .unwrap()?;
            let name = handler.text_for_range(0..1, &mut None);
            cx.update_window(window.into(), |_, window, _| {
                window.platform_window.set_input_handler(handler)
            })
            .unwrap();
            name
        };
        let focus = |cx: &mut TestAppContext, handle: &crate::FocusHandle| {
            cx.update_window(window.into(), |_, window, cx| window.focus(handle, cx))
                .unwrap()
        };

        focus(&mut cx, &inside);
        draw(&mut cx);
        assert_eq!(handed(&mut cx).as_deref(), Some("inside"));
        let builds_then = builds.get();
        for _ in 0..3 {
            window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
            draw(&mut cx);
            assert_eq!(handed(&mut cx).as_deref(), Some("inside"));
        }
        assert_eq!(builds.get(), builds_then, "the cached view was reused");

        focus(&mut cx, &outside);
        draw(&mut cx);
        assert_eq!(handed(&mut cx).as_deref(), Some("outside"));
        window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
        draw(&mut cx);
        assert_eq!(handed(&mut cx).as_deref(), Some("outside"));

        focus(&mut cx, &inside);
        draw(&mut cx);
        window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
        draw(&mut cx);
        assert_eq!(handed(&mut cx).as_deref(), Some("inside"));
    }
}

/// A card whose width comes from the column it sits in, not from its content.
struct Card;

impl Render for Card {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .items_center()
            .child(div().h(px(10.)).bg(crate::black()).child("card"))
    }
}

struct Stretched {
    card: Entity<Card>,
    spacer: f32,
}

impl Render for Stretched {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .w(px(300.))
            .child(div().h(px(self.spacer)))
            .child(self.card.clone())
    }
}

/// A view stretched by the column it is in keeps that width when it moves,
/// as when a scrolled list moves every view in it: it is laid out again at
/// the size its parent gave it, not at the size its content asks for.
#[test]
fn a_moved_view_keeps_the_size_its_parent_gave_it() {
    let mut cx = TestAppContext::single();
    let window = cx.add_window(|_, cx| Stretched {
        card: cx.new(|_| Card),
        spacer: 10.,
    });
    let draw = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.describe_rendered_frame()
        })
        .unwrap()
    };
    draw(&mut cx);
    window
        .update(&mut cx, |view, _, cx| {
            view.spacer = 30.;
            cx.notify();
        })
        .unwrap();
    let moved = draw(&mut cx);
    cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
        .unwrap();
    assert_eq!(moved, draw(&mut cx));
}

/// A view that read a model updated without being notified is built again
/// when the view around it is, as upstream builds every view under a
/// notified one again: a view often changes a model it renders and notifies
/// only itself.
#[test]
fn a_view_is_rendered_again_when_a_model_it_read_was_updated_without_a_notify() {
    let mut cx = TestAppContext::single();
    let s = siblings(&mut cx);
    draw_siblings(&mut cx, s.window);
    assert_eq!((s.first_builds.get(), s.second_builds.get()), (1, 1));

    s.model.update(&mut cx, |model, _| model.0 = 7);
    s.window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
    let updated = draw_siblings(&mut cx, s.window);
    assert_eq!(
        (s.first_builds.get(), s.second_builds.get()),
        (1, 2),
        "only the view that read the model is built again"
    );

    s.window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
    draw_siblings(&mut cx, s.window);
    assert_eq!(
        (s.first_builds.get(), s.second_builds.get()),
        (1, 2),
        "an update is seen once"
    );

    cx.update_window(s.window.into(), |_, window, _| {
        window.forget_retained_state()
    })
    .unwrap();
    assert_eq!(updated, draw_siblings(&mut cx, s.window));
}

/// A view built again keeps the measurements of the text that did not
/// change, rather than measuring and laying it out again. Text that changed
/// is measured again, but leaves its node clean when it measures the same
/// under every constraint Taffy measured it under, and dirties it otherwise.
#[test]
fn text_that_did_not_change_keeps_its_measurement() {
    let mut cx = TestAppContext::single();
    let s = siblings(&mut cx);
    draw_siblings(&mut cx, s.window);
    let stats = |cx: &mut TestAppContext| {
        cx.update_window(s.window.into(), |_, window, _| window.layout_stats())
            .unwrap()
    };
    let reset = |cx: &mut TestAppContext| {
        cx.update_window(s.window.into(), |_, window, _| window.reset_layout_stats())
            .unwrap()
    };

    reset(&mut cx);
    s.window
        .update(&mut cx, |view, _, cx| {
            view.spacer = 30.;
            cx.notify();
        })
        .unwrap();
    draw_siblings(&mut cx, s.window);
    let after_move = stats(&mut cx);
    assert_eq!(
        after_move.measure_rebinds, 0,
        "moved text is not measured again"
    );
    assert_eq!(after_move.measurements_kept, 2);

    reset(&mut cx);
    s.first.update(&mut cx, |first, cx| {
        first.label = 9;
        cx.notify();
    });
    draw_siblings(&mut cx, s.window);
    let after_change = stats(&mut cx);
    assert_eq!(
        (
            after_change.measure_rebinds,
            after_change.measurements_replayed
        ),
        (0, 1),
        "changed text of the same size leaves its node clean"
    );

    reset(&mut cx);
    s.first.update(&mut cx, |first, cx| {
        first.label = 12345;
        cx.notify();
    });
    let changed = draw_siblings(&mut cx, s.window);
    let after_change = stats(&mut cx);
    assert_eq!(
        (
            after_change.measure_rebinds,
            after_change.measurements_replayed
        ),
        (1, 0),
        "changed text of another size is measured again"
    );

    cx.update_window(s.window.into(), |_, window, _| {
        window.forget_retained_state()
    })
    .unwrap();
    assert_eq!(changed, draw_siblings(&mut cx, s.window));
}

/// A view that reads what a nested view holds, as a gallery reads the name of
/// the page it shows.
struct Reader {
    child: Entity<Counted>,
    builds: Rc<Cell<usize>>,
}

impl Render for Reader {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        let label = self.child.read(cx).label;
        div()
            .flex()
            .flex_col()
            .child(format!("showing {label}"))
            .child(self.child.clone())
    }
}

/// A view notified without being updated, as a scroll wheel or a dragged
/// scrollbar notifies it, is drawn again on its own: a view that read it is
/// drawn around it from last frame. Once it is updated, what that view read
/// may have changed, and it is built again.
#[test]
fn a_view_that_read_a_notified_view_is_built_again_only_if_it_was_updated() {
    let mut cx = TestAppContext::single();
    let reader_builds = Rc::new(Cell::new(0));
    let child_builds = Rc::new(Cell::new(0));
    let window = cx.add_window({
        let (reader_builds, child_builds) = (reader_builds.clone(), child_builds.clone());
        move |_, cx| Reader {
            child: cx.new(|_| Counted {
                label: 1,
                model: None,
                builds: child_builds,
            }),
            builds: reader_builds,
        }
    });
    let child = window.read_with(&cx, |view, _| view.child.clone()).unwrap();
    let draw = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.describe_rendered_frame()
        })
        .unwrap()
    };
    draw(&mut cx);
    let first = (reader_builds.get(), child_builds.get());

    cx.update(|cx| cx.notify(child.entity_id()));
    draw(&mut cx);
    assert_eq!(
        (reader_builds.get(), child_builds.get()),
        (first.0, first.1 + 1),
        "a notification alone changes nothing the reader read"
    );

    child.update(&mut cx, |child, cx| {
        child.label = 2;
        cx.notify();
    });
    let updated = draw(&mut cx);
    assert_eq!(
        (reader_builds.get(), child_builds.get()),
        (first.0 + 1, first.1 + 2)
    );
    cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
        .unwrap();
    assert_eq!(updated, draw(&mut cx));
}

/// The state of a view a component renders, written by the component as it
/// is rendered, the way a list or tree component hands its item renderer to
/// the view that draws the items.
struct Painter {
    color: crate::Hsla,
}

impl Render for Painter {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().size(px(40.)).bg(self.color)
    }
}

/// A component that writes what it was given into its view's state, without
/// notifying it, and renders the view.
#[derive(IntoElement)]
struct Paint {
    painter: Entity<Painter>,
    color: crate::Hsla,
}

impl crate::RenderOnce for Paint {
    fn render(self, _: &mut Window, cx: &mut crate::App) -> impl IntoElement {
        let color = self.color;
        self.painter.update(cx, |painter, _| painter.color = color);
        self.painter
    }
}

struct PaintHost {
    painter: Entity<Painter>,
    red: bool,
}

impl Render for PaintHost {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().size(px(300.)).child(Paint {
            painter: self.painter.clone(),
            color: if self.red {
                crate::red()
            } else {
                crate::blue()
            },
        })
    }
}

fn backgrounds(cx: &mut TestAppContext, window: crate::AnyWindowHandle) -> Vec<String> {
    cx.update_window(window, |_, window, cx| {
        window.draw(cx).clear(cx);
        window
            .painted_quads()
            .iter()
            .map(|quad| format!("{:?} {:?}", quad.bounds, quad.background))
            .collect()
    })
    .unwrap()
}

/// A view whose state a component wrote while the window drew, as it was
/// rendered, is drawn with what was written: the write changed what the view
/// reads, notified or not.
#[test]
fn a_view_written_while_the_window_draws_is_rendered_again() {
    let mut cx = TestAppContext::single();
    let window = cx.add_window(|_, cx| PaintHost {
        painter: cx.new(|_| Painter {
            color: crate::blue(),
        }),
        red: false,
    });
    let blue = backgrounds(&mut cx, window.into());
    assert_eq!(blue, backgrounds(&mut cx, window.into()));

    window
        .update(&mut cx, |host, _, cx| {
            host.red = true;
            cx.notify();
        })
        .unwrap();
    let red = backgrounds(&mut cx, window.into());
    assert_ne!(blue, red, "the painter was drawn with the color written");
    let again = backgrounds(&mut cx, window.into());
    assert_eq!(red, again, "and nothing wrote it since");

    // The host writing its painter as it is built is part of building it:
    // it does not make the host itself out of date.
    let reused = cx
        .update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.draw(cx).clear(cx);
            window.next_frame.retained.reused_any() || window.rendered_frame.retained.reused_any()
        })
        .unwrap();
    assert!(reused, "a frame where nothing changed reuses the views");
}

/// An element of its own that asks whether its hitbox is hovered while it is
/// painted — not a hover style — makes the view it is in depend on the answer.
struct HoverProbe;

impl Render for HoverProbe {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div().size(px(300.)).child(
            crate::canvas(
                |bounds, window, _| window.insert_hitbox(bounds, crate::HitboxBehavior::Normal),
                |bounds, hitbox, window, _| {
                    let color = if hitbox.is_hovered(window) {
                        crate::red()
                    } else {
                        crate::blue()
                    };
                    window.paint_quad(crate::fill(bounds, color));
                },
            )
            .size(px(100.)),
        )
    }
}

#[test]
fn a_view_is_rendered_again_when_a_hover_an_element_asked_about_changes() {
    let mut cx = TestAppContext::single();
    let window = cx.add_window(|_, _| HoverProbe);
    let move_to = |cx: &mut TestAppContext, x: f32, y: f32| {
        cx.update_window(window.into(), |_, window, cx| {
            window.simulate_mouse_move(crate::point(px(x), px(y)), cx);
        })
        .unwrap();
    };
    move_to(&mut cx, 250., 250.);
    backgrounds(&mut cx, window.into());
    let away = backgrounds(&mut cx, window.into());
    move_to(&mut cx, 10., 10.);
    let over = backgrounds(&mut cx, window.into());
    assert_ne!(
        away, over,
        "the pointer over the element changes how it looks"
    );
    move_to(&mut cx, 250., 250.);
    assert_eq!(away, backgrounds(&mut cx, window.into()));
}

/// A view that reads where the pointer is, or which modifiers are held, as it
/// renders depends on it.
struct PointerProbe;

impl Render for PointerProbe {
    fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        let x = window.mouse_position().x;
        let wide = window.modifiers().shift;
        div().size(px(300.)).child(
            div()
                .w(if wide { px(80.) } else { x })
                .h(px(10.))
                .bg(crate::red()),
        )
    }
}

#[test]
fn a_view_that_read_the_pointer_or_modifiers_is_rendered_again_when_they_change() {
    let mut cx = TestAppContext::single();
    let window = cx.add_window(|_, _| PointerProbe);
    let at = |cx: &mut TestAppContext, x: f32, modifiers: crate::Modifiers| {
        cx.update_window(window.into(), |_, window, cx| {
            window.dispatch_event(
                crate::PlatformInput::MouseMove(crate::MouseMoveEvent {
                    position: crate::point(px(x), px(5.)),
                    pressed_button: None,
                    modifiers,
                }),
                cx,
            );
        })
        .unwrap();
        backgrounds(cx, window.into())
    };
    let first = at(&mut cx, 20., crate::Modifiers::default());
    let moved = at(&mut cx, 60., crate::Modifiers::default());
    assert_ne!(first, moved, "the view reads where the pointer is");
    let shifted = at(
        &mut cx,
        60.,
        crate::Modifiers {
            shift: true,
            ..Default::default()
        },
    );
    assert_ne!(moved, shifted, "and which modifiers are held");
}

/// A text field that hands the platform its own input handler, and can
/// notify itself once while the window asks it whether it accepts text.
struct TextField {
    focus: crate::FocusHandle,
    notify_when_asked: Cell<bool>,
    builds: Rc<Cell<usize>>,
}

impl Render for TextField {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        let (focus, field) = (self.focus.clone(), cx.entity());
        crate::canvas(
            |_, _, _| {},
            move |bounds, _, window, cx| {
                window.handle_input(&focus, crate::ElementInputHandler::new(bounds, field), cx)
            },
        )
        .w(px(100.))
        .h(px(20.))
    }
}

impl crate::EntityInputHandler for TextField {
    fn text_for_range(
        &mut self,
        _: std::ops::Range<usize>,
        _: &mut Option<std::ops::Range<usize>>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<String> {
        None
    }
    fn selected_text_range(
        &mut self,
        _: bool,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<crate::UTF16Selection> {
        None
    }
    fn marked_text_range(
        &self,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<std::ops::Range<usize>> {
        None
    }
    fn unmark_text(&mut self, _: &mut Window, _: &mut Context<Self>) {}
    fn replace_text_in_range(
        &mut self,
        _: Option<std::ops::Range<usize>>,
        _: &str,
        _: &mut Window,
        _: &mut Context<Self>,
    ) {
    }
    fn replace_and_mark_text_in_range(
        &mut self,
        _: Option<std::ops::Range<usize>>,
        _: &str,
        _: Option<std::ops::Range<usize>>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) {
    }
    fn bounds_for_range(
        &mut self,
        _: std::ops::Range<usize>,
        _: crate::Bounds<crate::Pixels>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<crate::Bounds<crate::Pixels>> {
        None
    }
    fn character_index_for_point(
        &mut self,
        _: crate::Point<crate::Pixels>,
        _: &mut Window,
        _: &mut Context<Self>,
    ) -> Option<usize> {
        None
    }
    fn accepts_text_input(&self, _: &mut Window, cx: &mut Context<Self>) -> bool {
        if self.notify_when_asked.take() {
            cx.notify();
        }
        true
    }
}

/// A view that reads the text field it shows, as a form reads whether its
/// field is empty.
struct Form {
    field: Entity<TextField>,
    builds: Rc<Cell<usize>>,
}

impl Render for Form {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        let asks = self.field.read(cx).notify_when_asked.get();
        div()
            .flex()
            .flex_col()
            .child(format!("form {asks}"))
            .child(self.field.clone())
    }
}

/// A view around another, counting its builds.
struct Shell {
    child: crate::AnyView,
    builds: Rc<Cell<usize>>,
}

impl Render for Shell {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        div()
            .flex()
            .flex_col()
            .child("shell")
            .child(self.child.clone())
    }
}

/// The window asks the focused text field whether it accepts text, and how
/// it is configured, on every frame. That is not a change to the field: a
/// view that read it is not built again, even inside a notified view. A
/// field that notifies while it is asked has changed, and the view that read
/// it is built again.
#[test]
fn asking_the_focused_text_field_is_not_a_change_unless_it_notifies() {
    let mut cx = TestAppContext::single();
    let (form_builds, field_builds) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)));
    let window = cx.add_window({
        let (form_builds, field_builds) = (form_builds.clone(), field_builds.clone());
        move |_, cx| {
            let field = cx.new(|cx| TextField {
                focus: cx.focus_handle(),
                notify_when_asked: Cell::new(false),
                builds: field_builds,
            });
            Shell {
                child: cx
                    .new(|_| Form {
                        field,
                        builds: form_builds,
                    })
                    .into(),
                builds: Rc::new(Cell::new(0)),
            }
        }
    });
    let field = cx.update(|cx| {
        window
            .read(cx)
            .unwrap()
            .child
            .clone()
            .downcast::<Form>()
            .unwrap()
            .read(cx)
            .field
            .clone()
    });
    let draw = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.describe_rendered_frame()
        })
        .unwrap()
    };
    let focus = field.read_with(&cx, |field, _| field.focus.clone());
    cx.update_window(window.into(), |_, window, cx| window.focus(&focus, cx))
        .unwrap();
    draw(&mut cx);
    draw(&mut cx);
    let before = (form_builds.get(), field_builds.get());

    for _ in 0..3 {
        window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
        draw(&mut cx);
    }
    assert_eq!(
        (form_builds.get(), field_builds.get()),
        before,
        "being asked every frame changes nothing the form read"
    );

    field.read_with(&cx, |field, _| field.notify_when_asked.set(true));
    draw(&mut cx);
    let asked = (form_builds.get(), field_builds.get());
    let notified = draw(&mut cx);
    assert_eq!(
        (form_builds.get(), field_builds.get()),
        (asked.0 + 1, asked.1 + 1),
        "a field that notified while asked is built again, with the form that read it"
    );
    cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
        .unwrap();
    assert_eq!(notified, draw(&mut cx));
}

struct Ping;

impl crate::EventEmitter<Ping> for Model {}

/// A view that subscribes to a model it shows and ignores what it emits.
struct Subscriber {
    model: Entity<Model>,
    builds: Rc<Cell<usize>>,
    _subscription: crate::Subscription,
}

impl Render for Subscriber {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        div().child(format!("model {}", self.model.read(cx).0))
    }
}

struct Subscribers {
    first: Entity<Subscriber>,
    second: Entity<Subscriber>,
    bystander: Entity<Counted>,
}

impl Render for Subscribers {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .child(self.first.clone())
            .child(self.second.clone())
            .child(self.bystander.clone())
    }
}

/// Every subscriber of a model is updated for each event it emits, whether
/// it cares or not. A view updated that way, and not notified, is not built
/// again, nor is a view that read a model emitting without being notified,
/// unless it is inside a view notified since. A model updated and notified
/// is a change wherever it was read.
#[test]
fn a_view_updated_without_a_notify_is_built_again_only_inside_a_notified_view() {
    let mut cx = TestAppContext::single();
    let builds = Rc::new(Cell::new(0));
    let model = cx.new(|_| Model(0));
    let window = cx.add_window({
        let (builds, model) = (builds.clone(), model.clone());
        move |_, cx| {
            let mut subscriber = || {
                cx.new(|cx| Subscriber {
                    _subscription: cx.subscribe(&model, |_, _, _: &Ping, _| {}),
                    model: model.clone(),
                    builds: builds.clone(),
                })
            };
            Subscribers {
                first: subscriber(),
                second: subscriber(),
                bystander: cx.new(|_| Counted {
                    label: 0,
                    model: None,
                    builds: Rc::new(Cell::new(0)),
                }),
            }
        }
    });
    let bystander = window
        .read_with(&cx, |view, _| view.bystander.clone())
        .unwrap();
    let draw = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.describe_rendered_frame()
        })
        .unwrap()
    };
    let emit = |cx: &mut TestAppContext| model.update(cx, |_, cx| cx.emit(Ping));
    draw(&mut cx);
    assert_eq!(builds.get(), 2);

    emit(&mut cx);
    draw(&mut cx);
    assert_eq!(builds.get(), 2, "an ignored event changes nothing drawn");

    emit(&mut cx);
    bystander.update(&mut cx, |bystander, cx| {
        bystander.label += 1;
        cx.notify();
    });
    draw(&mut cx);
    assert_eq!(
        builds.get(),
        2,
        "nor does it when a sibling is notified and the parent is drawn around it"
    );

    emit(&mut cx);
    window.update(&mut cx, |_, _, cx| cx.notify()).unwrap();
    draw(&mut cx);
    assert_eq!(
        builds.get(),
        4,
        "inside a notified view, what was updated since is built again"
    );

    model.update(&mut cx, |model, cx| {
        model.0 = 3;
        cx.emit(Ping);
        cx.notify();
    });
    let changed = draw(&mut cx);
    assert_eq!(builds.get(), 6, "a model updated and notified has changed");
    cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
        .unwrap();
    assert_eq!(changed, draw(&mut cx));
}

struct Theme(usize);

impl crate::Global for Theme {}

/// A view that only asks whether the theme is set.
struct AsksForTheme(Rc<Cell<usize>>);

impl Render for AsksForTheme {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.0.set(self.0.get() + 1);
        div().child(format!("themed {}", cx.has_global::<Theme>()))
    }
}

/// A view that reads the theme.
struct ReadsTheme(Rc<Cell<usize>>);

impl Render for ReadsTheme {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.0.set(self.0.get() + 1);
        let theme = cx.try_global::<Theme>().map_or(0, |theme| theme.0);
        div().child(format!("theme {theme}"))
    }
}

struct Themed {
    asks: Entity<AsksForTheme>,
    reads: Entity<ReadsTheme>,
}

impl Render for Themed {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .child(self.asks.clone())
            .child(self.reads.clone())
    }
}

/// A view that only asked whether a global is set depends on that, not on
/// the global: writing to the global builds again the views that read it,
/// but not that one, which is built again when the global is set where it
/// was not or removed.
#[test]
fn a_view_that_asked_whether_a_global_is_set_is_built_again_only_when_that_changes() {
    let mut cx = TestAppContext::single();
    let (asks, reads) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)));
    cx.update(|cx| cx.set_global(Theme(0)));
    let window = cx.add_window({
        let (asks, reads) = (asks.clone(), reads.clone());
        move |_, cx| Themed {
            asks: cx.new(|_| AsksForTheme(asks)),
            reads: cx.new(|_| ReadsTheme(reads)),
        }
    });
    let draw = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.describe_rendered_frame()
        })
        .unwrap()
    };
    let builds = || (asks.get(), reads.get());
    draw(&mut cx);
    assert_eq!(builds(), (1, 1));

    cx.update(|cx| cx.global_mut::<Theme>().0 = 1);
    draw(&mut cx);
    assert_eq!(builds(), (1, 2), "global_mut writes the theme");

    cx.update_global::<Theme, _>(|theme, _| theme.0 = 2);
    draw(&mut cx);
    assert_eq!(builds(), (1, 3), "update_global writes the theme");

    cx.update(|cx| cx.set_global(Theme(3)));
    draw(&mut cx);
    assert_eq!(builds(), (1, 4), "setting a theme that was set writes it");

    cx.update(|cx| cx.remove_global::<Theme>());
    draw(&mut cx);
    assert_eq!(builds(), (2, 5), "removing it changes whether it is set");

    cx.update(|cx| cx.set_global(Theme(4)));
    let set = draw(&mut cx);
    assert_eq!(builds(), (3, 6), "setting it again changes that back");
    cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
        .unwrap();
    assert_eq!(set, draw(&mut cx));
}

/// Makes a window whose root is a counted [`Shell`] around `child`, and
/// returns it with the shell's build count.
fn shell(
    cx: &mut TestAppContext,
    child: impl FnOnce(&mut crate::App) -> crate::AnyView + 'static,
) -> (WindowHandle<Shell>, Rc<Cell<usize>>) {
    let builds = Rc::new(Cell::new(0));
    let window = cx.add_window({
        let builds = builds.clone();
        move |_, cx| Shell {
            child: child(cx),
            builds,
        }
    });
    (window, builds)
}

fn draw_shell(cx: &mut TestAppContext, window: WindowHandle<Shell>) -> Vec<String> {
    cx.update_window(window.into(), |_, window, cx| {
        window.draw(cx).clear(cx);
        window.describe_rendered_frame()
    })
    .unwrap()
}

/// A view of a fixed size whose colour comes from its tint and a model, so
/// a change to either repaints it without laying it out again.
struct Tinted {
    tint: usize,
    model: Option<Entity<Model>>,
    builds: Rc<Cell<usize>>,
}

impl Render for Tinted {
    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        let model = self.model.as_ref().map_or(0, |model| model.read(cx).0);
        let color = if (self.tint + model).is_multiple_of(2) {
            crate::black()
        } else {
            crate::white()
        };
        div().w(px(50.)).h(px(20.)).bg(color)
    }
}

/// A nested view that read a model changed since, with nothing notified
/// but the model, is built again on its own: the view around it, which read
/// the model only through it, is drawn around it from last frame.
#[test]
fn a_view_around_one_whose_model_changed_is_drawn_around_it() {
    let mut cx = TestAppContext::single();
    let inner_builds = Rc::new(Cell::new(0));
    let model = cx.new(|_| Model(0));
    let (window, outer_builds) = shell(&mut cx, {
        let (inner_builds, model) = (inner_builds.clone(), model.clone());
        move |cx| {
            cx.new(|_| Tinted {
                tint: 0,
                model: Some(model),
                builds: inner_builds,
            })
            .into()
        }
    });
    let before = draw_shell(&mut cx, window);
    assert_eq!((outer_builds.get(), inner_builds.get()), (1, 1));

    // The window draws as the update is flushed.
    model.update(&mut cx, |model, cx| {
        model.0 = 1;
        cx.notify();
    });
    assert_eq!((outer_builds.get(), inner_builds.get()), (1, 2));
    let changed = describe_shell(&mut cx, window);
    assert_ne!(before, changed);
    cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
        .unwrap();
    assert_eq!(changed, draw_shell(&mut cx, window));
}

/// A view drawn around a nested view hangs it off the dispatch node its
/// element had, copied from last frame, as building the view around it
/// would: drawn around it frame after frame, its dispatch tree is the one a
/// build gives, rather than a node deeper each frame.
#[test]
fn a_view_drawn_around_a_nested_view_keeps_its_dispatch_tree() {
    let mut cx = TestAppContext::single();
    let inner_builds = Rc::new(Cell::new(0));
    let model = cx.new(|_| Model(0));
    let (window, outer_builds) = shell(&mut cx, {
        let (inner_builds, model) = (inner_builds.clone(), model.clone());
        move |cx| {
            cx.new(|_| Tinted {
                tint: 0,
                model: Some(model),
                builds: inner_builds,
            })
            .into()
        }
    });
    let describe = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, _| {
            let tree = &window.rendered_frame.dispatch_tree;
            tree.nodes
                .iter()
                .map(|node| (node.parent.map(|parent| parent.0), node.view_id))
                .collect::<Vec<_>>()
        })
        .unwrap()
    };
    draw_shell(&mut cx, window);
    let built = describe(&mut cx);
    for value in 1..4 {
        model.update(&mut cx, |model, cx| {
            model.0 = value;
            cx.notify();
        });
        assert_eq!(
            describe(&mut cx),
            built,
            "after {value} frames drawn around"
        );
    }
    assert_eq!((outer_builds.get(), inner_builds.get()), (1, 4));
}

fn describe_shell(cx: &mut TestAppContext, window: WindowHandle<Shell>) -> Vec<String> {
    cx.update_window(window.into(), |_, window, _| {
        window.describe_rendered_frame()
    })
    .unwrap()
}

/// Two views side by side.
struct Pair {
    left: crate::AnyView,
    right: crate::AnyView,
}

impl Render for Pair {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .child(self.left.clone())
            .child(self.right.clone())
    }
}

/// A view drawn around a nested view built again has read what that view
/// read as of that frame: on a later frame, with nothing it read changed
/// since, it is drawn from last frame rather than built again, as when a
/// view beside it is notified.
#[test]
fn a_view_drawn_around_a_nested_view_is_reused_on_a_later_frame() {
    let mut cx = TestAppContext::single();
    let (outer_builds, inner_builds) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)));
    let model = cx.new(|_| Model(0));
    let tinted = |cx: &mut crate::App, model: Option<Entity<Model>>, builds| {
        cx.new(|_| Tinted {
            tint: 0,
            model,
            builds,
        })
    };
    let window = cx.add_window({
        let (outer_builds, inner_builds, model) =
            (outer_builds.clone(), inner_builds.clone(), model.clone());
        move |_, cx| {
            let inner = tinted(cx, Some(model), inner_builds);
            Pair {
                left: cx
                    .new(|_| Shell {
                        child: inner.into(),
                        builds: outer_builds,
                    })
                    .into(),
                right: tinted(cx, None, Rc::new(Cell::new(0))).into(),
            }
        }
    });
    let right = window
        .read_with(&cx, |pair, _| {
            pair.right.clone().downcast::<Tinted>().unwrap()
        })
        .unwrap();
    let draw = |cx: &mut TestAppContext| {
        cx.update_window(window.into(), |_, window, cx| {
            window.draw(cx).clear(cx);
            window.describe_rendered_frame()
        })
        .unwrap()
    };
    draw(&mut cx);
    // The window draws as each update is flushed.
    model.update(&mut cx, |model, cx| {
        model.0 = 1;
        cx.notify();
    });
    let builds_then = (outer_builds.get(), inner_builds.get());
    assert_eq!(builds_then, (1, 2), "the shell is drawn around the view");

    right.update(&mut cx, |right, cx| {
        right.tint = 1;
        cx.notify();
    });
    let later = cx
        .update_window(window.into(), |_, window, _| {
            window.describe_rendered_frame()
        })
        .unwrap();
    assert_eq!(
        (outer_builds.get(), inner_builds.get()),
        builds_then,
        "nothing the shell read changed since the frame it was drawn around the view"
    );
    cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
        .unwrap();
    assert_eq!(later, draw(&mut cx));
}

/// A view with something in it that has a hover style.
struct Hoverable(Rc<Cell<usize>>);

impl Render for Hoverable {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.0.set(self.0.get() + 1);
        div().child(
            div()
                .id("hoverable")
                .w(px(50.))
                .h(px(20.))
                .bg(crate::black())
                .hover(|style| style.bg(crate::white())),
        )
    }
}

/// The pointer moving onto or off something with a hover style builds again
/// the view it is in, and only that one: the views around it are drawn
/// around it from last frame.
#[test]
fn a_hover_inside_a_nested_view_builds_only_that_view_again() {
    let mut cx = TestAppContext::single();
    let inner_builds = Rc::new(Cell::new(0));
    let (window, outer_builds) = shell(&mut cx, {
        let inner_builds = inner_builds.clone();
        move |cx| cx.new(|_| Hoverable(inner_builds)).into()
    });
    let move_to = |cx: &mut TestAppContext, x: f32, y: f32| {
        cx.update_window(window.into(), |_, window, cx| {
            window.simulate_mouse_move(crate::point(px(x), px(y)), cx);
        })
        .unwrap();
    };
    move_to(&mut cx, 500., 500.);
    let away = draw_shell(&mut cx, window);
    let before = (outer_builds.get(), inner_builds.get());

    // The shell draws a line of text above the hoverable view.
    let hoverable = cx
        .update_window(window.into(), |_, window, _| {
            window
                .rendered_frame
                .hitboxes
                .last()
                .map(|hitbox| hitbox.bounds.center())
        })
        .unwrap()
        .expect("the hoverable element has a hitbox");
    move_to(&mut cx, hoverable.x.into(), hoverable.y.into());
    let over = draw_shell(&mut cx, window);
    assert_eq!(
        (outer_builds.get(), inner_builds.get()),
        (before.0, before.1 + 1)
    );
    assert_ne!(away, over);
    cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
        .unwrap();
    assert_eq!(over, draw_shell(&mut cx, window));

    move_to(&mut cx, 500., 500.);
    let away_again = draw_shell(&mut cx, window);
    assert_eq!(
        outer_builds.get(),
        before.0 + 1,
        "only the forgetting built it"
    );
    assert_eq!(away, away_again);
}

/// A view around a nested view, cached by the style it is cached with or
/// not.
struct AroundNested {
    child: Entity<Tinted>,
    cached: bool,
    builds: Rc<Cell<usize>>,
}

impl Render for AroundNested {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        let child = if self.cached {
            self.child
                .clone()
                .cached(StyleRefinement::default().w(px(50.)).h(px(20.)))
                .into_any_element()
        } else {
            self.child.clone().into_any_element()
        };
        div()
            .flex()
            .flex_col()
            .child("around")
            .child(child)
            .child("after")
    }
}

/// A nested view notified on its own, cached or not, is built again in the
/// gap where it was, a cached one at the style it is cached with: the view
/// around it is drawn around it from last frame, frame after frame, and the
/// frame is what one drawn from scratch is.
#[test]
fn a_view_around_a_notified_nested_view_is_drawn_around_it() {
    for cached in [false, true] {
        let mut cx = TestAppContext::single();
        let (outer_builds, child_builds) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)));
        let window = cx.add_window({
            let (outer_builds, child_builds) = (outer_builds.clone(), child_builds.clone());
            move |_, cx| AroundNested {
                child: cx.new(|_| Tinted {
                    tint: 0,
                    model: None,
                    builds: child_builds,
                }),
                cached,
                builds: outer_builds,
            }
        });
        let child = window.read_with(&cx, |view, _| view.child.clone()).unwrap();
        let draw = |cx: &mut TestAppContext| {
            cx.update_window(window.into(), |_, window, cx| {
                window.draw(cx).clear(cx);
                window.describe_rendered_frame()
            })
            .unwrap()
        };
        let mut last = draw(&mut cx);
        assert_eq!((outer_builds.get(), child_builds.get()), (1, 1));

        for tint in 1..4 {
            // The window draws as the update is flushed.
            child.update(&mut cx, |child, cx| {
                child.tint = tint;
                cx.notify();
            });
            let changed = cx
                .update_window(window.into(), |_, window, _| {
                    window.describe_rendered_frame()
                })
                .unwrap();
            assert_eq!(
                (outer_builds.get(), child_builds.get()),
                (1, tint + 1),
                "cached: {cached}, notified {tint} times"
            );
            assert_ne!(last, changed);
            last = changed;
        }
        cx.update_window(window.into(), |_, window, _| window.forget_retained_state())
            .unwrap();
        assert_eq!(last, draw(&mut cx), "cached: {cached}");
    }
}

/// A child outside its parent's Taffy tree, laid out during prepaint like
/// a uniform_list item. Keeping its parent must still run this placement.
struct RootPlacer(crate::AnyElement);

impl IntoElement for RootPlacer {
    type Element = Self;
    fn into_element(self) -> Self {
        self
    }
}

impl crate::Element for RootPlacer {
    type RequestLayoutState = ();
    type PrepaintState = ();
    fn id(&self) -> Option<crate::ElementId> {
        None
    }
    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }
    fn request_layout(
        &mut self,
        _: Option<&crate::GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        window: &mut Window,
        cx: &mut crate::App,
    ) -> (crate::LayoutId, ()) {
        let mut style = crate::Style::default();
        style.size.width = crate::relative(1.).into();
        style.size.height = crate::relative(1.).into();
        (window.request_layout(style, None, cx), ())
    }
    fn prepaint(
        &mut self,
        _: Option<&crate::GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        bounds: crate::Bounds<crate::Pixels>,
        _: &mut (),
        window: &mut Window,
        cx: &mut crate::App,
    ) {
        self.0
            .prepaint_as_root(bounds.origin, bounds.size.into(), window, cx);
    }
    fn paint(
        &mut self,
        _: Option<&crate::GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        _: crate::Bounds<crate::Pixels>,
        _: &mut (),
        _: &mut (),
        window: &mut Window,
        cx: &mut crate::App,
    ) {
        self.0.paint(window, cx);
    }
}

struct RootPlacedStatus(crate::SharedString);
impl Render for RootPlacedStatus {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .size_full()
            .flex()
            .items_center()
            .justify_center()
            .child(self.0.clone())
    }
}

#[derive(Clone, Copy)]
enum StatusPlacement {
    Flow,
    Root,
    List,
    VariableList,
    ContainerQuery,
    Deferred,
    Anchored,
}

struct StatusHost {
    status: Entity<RootPlacedStatus>,
    placement: StatusPlacement,
    list: crate::ListState,
}
impl Render for StatusHost {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        let child = div()
            .size_full()
            .child(self.status.clone())
            .into_any_element();
        let body = match self.placement {
            StatusPlacement::Flow => child,
            StatusPlacement::Root => RootPlacer(child).into_any_element(),
            StatusPlacement::VariableList => {
                let status = self.status.clone();
                crate::list(self.list.clone(), move |_, _, _| {
                    div().h(px(40.)).child(status.clone()).into_any_element()
                })
                .size_full()
                .into_any_element()
            }
            StatusPlacement::ContainerQuery => {
                crate::container_query(move |_, _, _| child).into_any_element()
            }
            StatusPlacement::Deferred => crate::deferred(child).into_any_element(),
            StatusPlacement::Anchored => crate::anchored()
                .position(crate::point(px(30.), px(40.)))
                .child(child)
                .into_any_element(),
            StatusPlacement::List => {
                let status = self.status.clone();
                crate::uniform_list("status-list", 1, move |_, _, _| {
                    vec![div().h(px(40.)).child(status.clone()).into_any_element()]
                })
                .size_full()
                .into_any_element()
            }
        };
        div()
            .size_full()
            .flex()
            .flex_col()
            .child("header")
            .child(div().flex_1().child(body))
    }
}

fn status_change_at_placement(placement: StatusPlacement) {
    let mut cx = TestAppContext::single();
    let status = cx.new(|_| RootPlacedStatus("Starting…".into()));
    // The shell exercises a splice around another splice, as in the real
    // application's WindowBorder / WorkspaceView / editor hierarchy.
    let (window, _) = shell(&mut cx, {
        let status = status.clone();
        move |cx| {
            cx.new(|_| StatusHost {
                status,
                placement,
                list: crate::ListState::new(1, crate::ListAlignment::Top, px(0.)),
            })
            .into()
        }
    });
    let before = draw_shell(&mut cx, window);
    for text in [
        "Session unavailable: a longer status",
        "Ready",
        "Another longer status",
    ] {
        status.update(&mut cx, |status, cx| {
            status.0 = text.into();
            cx.notify();
        });
        let changed = describe_shell(&mut cx, window);
        assert_ne!(before, changed);
        cx.update_window(window.into(), |_, window, _| {
            window.set_view_retention(false)
        })
        .unwrap();
        assert_eq!(
            changed,
            draw_shell(&mut cx, window),
            "retained output must match a full render"
        );
        cx.update_window(window.into(), |_, window, _| {
            window.set_view_retention(true)
        })
        .unwrap();
        draw_shell(&mut cx, window);
    }
}

#[test]
fn status_change_in_normal_flow_is_measured() {
    status_change_at_placement(StatusPlacement::Flow);
}
#[test]
fn status_change_under_prepaint_as_root_is_measured() {
    status_change_at_placement(StatusPlacement::Root);
}
#[test]
fn status_change_in_uniform_list_is_measured() {
    status_change_at_placement(StatusPlacement::List);
}

#[test]
fn status_change_in_variable_list_is_measured() {
    status_change_at_placement(StatusPlacement::VariableList);
}
#[test]
fn status_change_under_container_query_is_measured() {
    status_change_at_placement(StatusPlacement::ContainerQuery);
}
#[test]
fn status_change_under_deferred_is_measured() {
    status_change_at_placement(StatusPlacement::Deferred);
}
#[test]
fn status_change_under_anchored_is_measured() {
    status_change_at_placement(StatusPlacement::Anchored);
}

struct MixedDeferredViews {
    flow: Entity<Tinted>,
    overlay: Entity<Tinted>,
}

impl Render for MixedDeferredViews {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .size_full()
            .child(self.flow.clone())
            .child(crate::deferred(
                crate::anchored()
                    .position(crate::point(px(10.), px(10.)))
                    .child(div().w(px(200.)).h(px(40.)).child(self.overlay.clone())),
            ))
    }
}

/// Deferred view records follow the closed ancestor's subtree. Check the
/// notification frame itself: an extra draw can hide a stale copied overlay.
fn changed_flow_and_deferred_views_match_full_render(idle_first: bool) {
    let mut cx = TestAppContext::single();
    let flow_builds = Rc::new(Cell::new(0));
    let overlay_builds = Rc::new(Cell::new(0));
    let flow = cx.new(|_| Tinted {
        tint: 0,
        model: None,
        builds: flow_builds.clone(),
    });
    let overlay = cx.new(|_| Tinted {
        tint: 0,
        model: None,
        builds: overlay_builds.clone(),
    });
    let (window, _) = shell(&mut cx, {
        let (flow, overlay) = (flow.clone(), overlay.clone());
        move |cx| cx.new(|_| MixedDeferredViews { flow, overlay }).into()
    });
    draw_shell(&mut cx, window);
    if idle_first {
        draw_shell(&mut cx, window);
    }
    for tint in [1, 0, 1] {
        let before = (flow_builds.get(), overlay_builds.get());
        cx.update(|cx| {
            flow.update(cx, |view, cx| {
                view.tint = tint;
                cx.notify();
            });
            overlay.update(cx, |view, cx| {
                view.tint = tint;
                cx.notify();
            });
        });
        assert_eq!(
            flow_builds.get(),
            before.0 + 1,
            "the flow child rebuilt in the notification frame"
        );
        assert_eq!(
            overlay_builds.get(),
            before.1 + 1,
            "the deferred child must rebuild in the same frame"
        );
        let changed = describe_shell(&mut cx, window);
        cx.update_window(window.into(), |_, window, _| {
            window.set_view_retention(false)
        })
        .unwrap();
        assert_eq!(
            changed,
            draw_shell(&mut cx, window),
            "a splice must not replay a dirty deferred view"
        );
        cx.update_window(window.into(), |_, window, _| {
            window.set_view_retention(true)
        })
        .unwrap();
        draw_shell(&mut cx, window);
    }
}

#[test]
fn simultaneously_changed_flow_and_deferred_views_match_full_render() {
    changed_flow_and_deferred_views_match_full_render(false);
}

#[test]
fn simultaneously_changed_flow_and_reused_deferred_views_match_full_render() {
    changed_flow_and_deferred_views_match_full_render(true);
}

struct OffsetDependentParent {
    scroll: crate::ScrollHandle,
    child: Entity<Tinted>,
    builds: Rc<Cell<usize>>,
}

impl Render for OffsetDependentParent {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        let color = if self.scroll.offset().y < px(0.) {
            crate::white()
        } else {
            crate::black()
        };
        div().size_full().bg(color).child(self.child.clone())
    }
}

#[test]
fn a_parent_whose_scroll_offset_read_changed_is_not_spliced() {
    if !crate::fast::layers::COMPILED {
        return;
    }
    let mut cx = TestAppContext::single();
    let builds = Rc::new(Cell::new(0));
    let child = cx.new(|_| Tinted {
        tint: 0,
        model: None,
        builds: Rc::new(Cell::new(0)),
    });
    let scroll = crate::ScrollHandle::new();
    let (window, _) = shell(&mut cx, {
        let (scroll, child, builds) = (scroll.clone(), child.clone(), builds.clone());
        move |cx| {
            cx.new(|_| OffsetDependentParent {
                scroll,
                child,
                builds,
            })
            .into()
        }
    });
    draw_shell(&mut cx, window);
    let before = builds.get();
    cx.update(|cx| {
        scroll.set_offset(crate::point(px(0.), px(-20.)));
        child.update(cx, |child, cx| {
            child.tint = 1;
            cx.notify();
        });
    });
    let changed = describe_shell(&mut cx, window);
    assert_eq!(
        builds.get(),
        before + 1,
        "the parent's own offset read changed"
    );
    cx.update_window(window.into(), |_, window, _| {
        window.set_view_retention(false)
    })
    .unwrap();
    assert_eq!(changed, draw_shell(&mut cx, window));
}

struct GrowingFixedView {
    extra: Rc<Cell<bool>>,
    builds: Rc<Cell<usize>>,
}

impl Render for GrowingFixedView {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        self.builds.set(self.builds.get() + 1);
        div()
            .relative()
            .w(px(100.))
            .h(px(40.))
            .child(div().id("base").size_full())
            .when(self.extra.get(), |this| {
                this.child(
                    div()
                        .id("extra")
                        .absolute()
                        .top_0()
                        .left_0()
                        .size(px(10.))
                        .bg(crate::white()),
                )
            })
    }
}

#[test]
fn new_layout_nodes_in_a_spliced_gap_survive_idle_frames() {
    let mut cx = TestAppContext::single();
    let builds = Rc::new(Cell::new(0));
    let extra = Rc::new(Cell::new(false));
    let child = cx.new(|_| GrowingFixedView {
        extra: extra.clone(),
        builds: builds.clone(),
    });
    let (window, outer_builds) = shell(&mut cx, {
        let child = child.clone();
        move |_| child.into()
    });
    draw_shell(&mut cx, window);
    extra.set(true);
    cx.update(|cx| cx.notify(child.entity_id()));
    let added = describe_shell(&mut cx, window);
    let nodes = cx
        .update_window(window.into(), |_, window, _| {
            window.layout_engine.as_ref().unwrap().node_count()
        })
        .unwrap();
    for _ in 0..3 {
        assert_eq!(added, draw_shell(&mut cx, window));
        assert_eq!(
            nodes,
            cx.update_window(window.into(), |_, window, _| window
                .layout_engine
                .as_ref()
                .unwrap()
                .node_count())
                .unwrap(),
            "a reused parent must retain the gap's new nodes"
        );
    }
    assert_eq!(
        outer_builds.get(),
        1,
        "the fixed-size parent can be spliced"
    );
    extra.set(false);
    cx.update(|cx| cx.notify(child.entity_id()));
    let removed = describe_shell(&mut cx, window);
    assert_ne!(added, removed);
    for _ in 0..3 {
        assert_eq!(removed, draw_shell(&mut cx, window));
        cx.update_window(window.into(), |_, window, _| {
            assert!(
                window
                    .rendered_frame
                    .element_states
                    .keys()
                    .all(|(id, _)| id.last() != Some(&crate::ElementId::from("extra"))),
                "removed element state must not be replayed by the parent"
            );
            assert_eq!(
                window.layout_engine.as_ref().unwrap().node_count(),
                nodes - 1
            );
        })
        .unwrap();
    }
    assert_eq!(outer_builds.get(), 1);
    assert_eq!(builds.get(), 3);
}