gpui-fast 0.1.3

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
// Modified by Longbridge for gpui-fast.
//! Rendering only the rows of a `uniform_list` or `list` its layer lacks (M6).
//!
//! A virtual list renders only the rows it shows. Its layer holds more: the
//! rows its viewport shows and two viewports' worth of rows on each side
//! (the overscan), each painted into the layer at its place in content
//! space and kept there by row. On a frame that only scrolled the list the
//! rows the layer holds are neither rendered, laid out, prepainted nor
//! painted: only the rows the scroll brought into the overscan are, and
//! those whose hover changed, and are added to the layer, whose tiles over
//! them become dirty (spec §8). Any other frame paints the rows afresh, as
//! a div's layer is.
//!
//! Each row the layer holds keeps what it handed the frame besides what it
//! drew: where its prepaint and paint records (hitboxes, listeners, element
//! states, dispatch nodes) lie in the frame last drawn, its hitboxes as
//! painted and the hovers it was painted by. A frame that keeps the row
//! carries those records into itself, its hitboxes moved by the scroll
//! since the row was painted, as [`crate::fast::layers::reuse`] carries a
//! div's content; a row whose hovers changed is rendered again, alone.
//!
//! The layer's content is one part per row (see
//! [`crate::fast::layers::scene::LayerContent`]), in the order of the rows,
//! and each row's tiles are hashed once, when it is painted: a frame adding
//! or changing rows hands the renderer the other rows as they were and
//! combines the hashes of the tiles they reach. Rows that left the overscan
//! are dropped a batch at a time (see [`retained_rows`]).
//!
//! The list elements call in here from a few hooks:
//!
//! - `uniform_list`: [`measure_item`], [`snap_item_offset`],
//!   [`begin_uniform_list`], [`render_rows`], [`row_indices`],
//!   [`prepaint_row`] and [`end_rows`] where it prepaints its rows;
//!   [`begin_paint_rows`], [`paint_row`] and [`end_paint_rows`] where it
//!   paints them.
//! - `list`: [`begin_list`], [`keeps_row`], [`snap_item_origin`],
//!   [`place_list_item`] and [`end_list`] where it lays out and prepaints
//!   its rows; [`begin_paint_list`], [`paint_row`] and [`end_paint_list`]
//!   where it paints them. A `list` has no element id: its layer is known by
//!   the id of the elements around it and its state.
//!
//! Between a list's prepaint and its paint, what the frame does with its
//! rows lives in its layer's [`LayerRows`]. While its rows prepaint and
//! paint, `WindowLayers::painting` is set, as for a div's layer, so that
//! nested views and scroll containers are painted into the layer.

use crate::{
    AnyElement, App, AvailableSpace, Bounds, ContentMask, ElementId, EntityId, GlobalElementId,
    Hitbox, HitboxId, PaintIndex, Pixels, Point, PrepaintStateIndex, Rgba, ScaledPixels, Scene,
    Size, TextStyle, TileCoord, Window,
    fast::{
        dependencies::{DependencyRecording, RenderDependencies, StateVersion},
        layers::{
            COMPILED, active, input, invalidate,
            paint::{self, Painting},
            policy::{self, Decision},
            record::LayerRecord,
            reuse,
            scene::{LayerContent, LayerPart, move_primitive},
            tiles::{combine_tile_hashes, dirty_tiles, part_tile_hashes},
        },
    },
    point, px,
    scene::{PaintOperation, Primitive},
    size,
};
use collections::FxHashMap;
use smallvec::SmallVec;
use std::{
    collections::{BTreeMap, BTreeSet},
    mem,
    ops::Range,
    rc::Rc,
};

/// Whether virtual lists get scroll layers.
pub(crate) const LIST_LAYERS: bool = true;

/// The rows of a list's layer, and what the frame being drawn does with
/// them.
#[derive(Default)]
pub(crate) struct LayerRows {
    /// Whether the layer is a list's, which a scroll extends by the rows it
    /// uncovers instead of painting it again.
    pub(crate) list: bool,
    /// How many rows frames that kept the rows the layer held added to it
    /// since its rows were last painted afresh. What the rows read is kept
    /// for the whole layer, not by row, so it only grows on those frames:
    /// past [`REPAINT_AFTER_ADDED`] times the rows the layer is to hold, the
    /// rows are painted afresh.
    added_since_repaint: usize,
    /// The rows the layer holds, by index.
    rows: BTreeMap<usize, Row>,
    /// A uniform list's measured item, as last measured.
    measured: Option<Measured>,
    /// The layer's translation in the last frame that drew its rows.
    last_translation: Option<Point<ScaledPixels>>,
    /// The rows the list showed in the last frame that drew it, and that
    /// frame: the rows whose element states it kept alive, as a list
    /// without a layer does. See [`sort_rows`].
    visible: Option<(u64, Range<usize>)>,
    /// What the frame being drawn does with the list's rows, from its
    /// prepaint to its paint.
    frame: Option<RowsFrame>,
}

impl LayerRows {
    /// Ends the frame being drawn.
    pub(crate) fn finish_frame(&mut self) {
        self.frame = None;
    }

    fn clear(&mut self) {
        self.rows.clear();
        self.added_since_repaint = 0;
        self.last_translation = None;
    }

    /// Whether the rows the layer holds, `needed` of them from now on, are
    /// to be painted afresh for having added too many rows since they last
    /// were (see [`LayerRows::added_since_repaint`]).
    fn due_for_repaint(&self, needed: &Range<usize>) -> bool {
        self.added_since_repaint > needed.len().max(1) * REPAINT_AFTER_ADDED
    }

    /// The rows the layer holds.
    #[cfg(test)]
    pub(crate) fn held(&self) -> impl Iterator<Item = usize> + '_ {
        self.rows.keys().copied()
    }

    /// Moves the prepaint ranges of the rows the layer holds with `shift`,
    /// as the frame being drawn copies their records from the last one.
    pub(crate) fn follow_prepaint(
        &mut self,
        shift: &dyn Fn(&Range<PrepaintStateIndex>) -> Range<PrepaintStateIndex>,
    ) {
        for row in self.rows.values_mut() {
            row.prepaint = shift(&row.prepaint);
        }
    }

    /// Moves the paint ranges of the rows the layer holds with `shift`, as
    /// [`LayerRows::follow_prepaint`] moves their prepaint ranges.
    pub(crate) fn follow_paint(&mut self, shift: &dyn Fn(&Range<PaintIndex>) -> Range<PaintIndex>) {
        for row in self.rows.values_mut() {
            row.paint = shift(&row.paint);
        }
    }

    /// Whether a row the layer holds inserted the hitbox `id`.
    pub(crate) fn holds_hitbox(&self, id: HitboxId) -> bool {
        self.rows
            .values()
            .any(|row| row.hitboxes.iter().any(|hitbox| hitbox.id == id))
    }
}

/// How many times the rows a list's layer is to hold its frames that keep
/// rows may add before its rows are painted afresh.
const REPAINT_AFTER_ADDED: usize = 4;

#[cfg(test)]
thread_local! {
    static EXTENDED_FRAMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    static RENDERED_FOR_HOVER: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// How many frames on this thread composited a list's layer keeping the
/// rows it held.
#[cfg(test)]
pub(crate) fn extended_frames() -> usize {
    EXTENDED_FRAMES.with(|frames| frames.get())
}

/// How many rows a list's layer held that frames on this thread rendered
/// again because their hovers changed.
#[cfg(test)]
pub(crate) fn rows_rendered_for_hover() -> usize {
    RENDERED_FOR_HOVER.with(|rows| rows.get())
}

/// Counts a frame that composited a list's layer keeping the rows it held,
/// rendering `for_hover` of them again because their hovers changed.
fn count_extended_frame(for_hover: usize) {
    #[cfg(test)]
    {
        EXTENDED_FRAMES.with(|frames| frames.set(frames.get() + 1));
        RENDERED_FOR_HOVER.with(|rows| rows.set(rows.get() + for_hover));
    }
    let _ = for_hover;
}

/// A row as the layer holds it.
struct Row {
    /// The row's slot, as wide as the viewport, in content space.
    slot: Bounds<ScaledPixels>,
    /// What painting the row drew, in content space.
    part: LayerPart,
    /// The hash of what the row draws over each tile it reaches.
    tile_hashes: Vec<(TileCoord, u64)>,
    /// Whether the row painted a path, which tiles cannot hold.
    has_paths: bool,
    /// The layer's translation when the row was painted: its hitboxes, and
    /// the positions its closures and element states hold, are window
    /// positions at it.
    translation: Point<ScaledPixels>,
    /// The hitboxes the row inserted, as inserted, their masks clipped by
    /// the row's own clips but not by the viewport.
    hitboxes: Vec<Hitbox>,
    /// The hovers the row was painted by.
    hovers: Vec<(HitboxId, bool)>,
    /// What prepainting the row added to the frame last drawn.
    prepaint: Range<PrepaintStateIndex>,
    /// What painting the row added to the frame last drawn, the scene aside.
    paint: Range<PaintIndex>,
    /// Whether the row keeps element states.
    has_states: bool,
    /// The keys of the layout nodes laying the row out claimed: kept while
    /// the row is, so that rendering it again reuses them.
    layout_keys: Vec<u64>,
    /// Whether the row's element states were dropped, as a list without a
    /// layer drops them when the row leaves its viewport: the row is
    /// rendered afresh before it shows again. See [`sort_rows`].
    dropped: bool,
}

impl Row {
    /// How far the row's records lag behind where it shows with the layer's
    /// content moved by `translation`, in logical pixels.
    fn delta(&self, translation: Point<ScaledPixels>, scale_factor: f32) -> Point<Pixels> {
        point(
            px((translation.x.0 - self.translation.x.0) / scale_factor),
            px((translation.y.0 - self.translation.y.0) / scale_factor),
        )
    }
}

/// A uniform list's measured item, and what it was measured with besides
/// the item itself.
struct Measured {
    size: Size<Pixels>,
    rem_size: Pixels,
    text_style: TextStyle,
}

/// The rows a list renders into its layer this frame.
pub(crate) struct RowPlan {
    /// The rows to render, prepaint and paint into the layer, in order.
    pub(crate) render: Vec<Range<usize>>,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
    /// The rows are painted afresh.
    Repaint,
    /// The rows the layer holds stay; those it lacks are added.
    Extend,
}

/// What the frame being drawn does with a list's rows.
struct RowsFrame {
    mode: Mode,
    /// For a `list`, its state, to tell its hooks from a nested list's.
    list: Option<usize>,
    /// Whether the list leaves out the rows the layer holds when it lays
    /// out the rows it shows.
    skip_held: bool,
    /// The rows the layer is to hold after the frame, at least.
    needed: Range<usize>,
    /// The rows the layer may hold after the frame; those it holds outside
    /// are dropped.
    retain: Range<usize>,
    /// The rows the layer holds that are rendered again: their hovers
    /// changed, or they show again after their element states were dropped.
    stale: BTreeSet<usize>,
    /// The rows the list shows this frame.
    visible: Range<usize>,
    /// The rows the list showed last frame and no longer does, whose
    /// element states the frame drops. See [`sort_rows`].
    leaving: BTreeSet<usize>,
    /// The rows the layer holds whose records the frame carries, in order.
    carried: Vec<usize>,
    /// Where each row painted into the layer this frame lies, in window
    /// space.
    slots: BTreeMap<usize, Bounds<Pixels>>,
    /// The list's clip rect, in window space.
    viewport: Bounds<Pixels>,
    /// The part of the content the frame paints, in window space: the
    /// viewport and the rows around it.
    painted_region: Bounds<Pixels>,
    /// The offset the rows are painted at, snapped.
    scroll_offset: Point<Pixels>,
    /// How far the layer's content is moved into window space this frame.
    translation: Point<ScaledPixels>,
    prepaint_start: PrepaintStateIndex,
    prepaint_range: Range<PrepaintStateIndex>,
    /// The recording of what rendering and prepainting the rows reads.
    recording: Option<DependencyRecording>,
    dependencies: RenderDependencies,
    /// What prepainting each row painted into the layer added to the frame.
    row_prepaints: Vec<RowPrepaint>,
    /// The row being prepainted, where it began and how many hitbox masks
    /// the layer had noted then.
    open_row: Option<(usize, PrepaintStateIndex, usize)>,
    /// Where the recording of the layout keys the rows claim began, and
    /// where the last row prepainted ended in it.
    layout_keys: Option<(usize, usize)>,
    /// A uniform list's rows in the order it paints them, and how many it
    /// painted.
    order: Vec<usize>,
    next: usize,
    /// A `list`'s first row shown and where it lies, as it prepaints its rows.
    anchor: Option<(usize, Point<Pixels>)>,
    /// The rows a `list` prepainted itself.
    prepainted: Vec<usize>,
    /// The rows rendered and prepainted here for a `list`, painted after its
    /// own.
    extra: Vec<(usize, AnyElement)>,
    paint: Option<PaintState>,
}

/// What prepainting a row added to the frame, and the masks of its hitboxes
/// before they were clipped to the viewport.
struct RowPrepaint {
    row: usize,
    range: Range<PrepaintStateIndex>,
    masks: Vec<ContentMask<Pixels>>,
    /// The layout keys claimed since the row before it was prepainted: those
    /// laying it out claimed.
    layout_keys: Vec<u64>,
}

/// A list's rows being painted.
struct PaintState {
    /// The opaque colour under the viewport, if there is one; the rows are
    /// painted into the frame otherwise.
    background: Option<Rgba>,
    /// Whether rows are painted into the layer's scene, which the frame's is
    /// then swapped out for.
    swapped: bool,
    /// The frame's scene, swapped out for the layer's.
    scene: Scene,
    /// Where the rows' paint records begin in the frame, those carried
    /// included.
    records_start: PaintIndex,
    recording: Option<DependencyRecording>,
    /// The row being painted.
    current: Option<usize>,
    /// What each row painted into the layer's scene.
    spans: Vec<RowPaint>,
}

/// What painting a row into the layer drew and added to the frame.
struct RowPaint {
    row: usize,
    /// The row's operations in the layer's scene.
    operations: Range<usize>,
    paint: Range<PaintIndex>,
    hovers: Vec<(HitboxId, bool)>,
}

/// What a `uniform_list` does with its rows this frame: nothing new, or
/// render the plan's rows into its layer.
pub(crate) struct Rows(Option<RowPlan>);

/// The rows `visible` and `overscan` rows on each side, of `item_count`.
fn needed_rows(visible: &Range<usize>, overscan: usize, item_count: usize) -> Range<usize> {
    visible.start.saturating_sub(overscan).min(item_count)..(visible.end + overscan).min(item_count)
}

/// The rows of `needed` that `held` lacks, in runs.
fn plan(held: &BTreeSet<usize>, needed: Range<usize>) -> RowPlan {
    let mut render: Vec<Range<usize>> = Vec::new();
    for row in needed {
        if !held.contains(&row) {
            match render.last_mut() {
                Some(run) if run.end == row => run.end = row + 1,
                _ => render.push(row..row + 1),
            }
        }
    }
    RowPlan { render }
}

/// The rows a list's layer may hold after a frame that needs `needed`,
/// holding `held`: the rows it holds past `needed` are dropped a batch at a
/// time, once they are more than a quarter of `needed`, and kept until
/// then. Dropping a row changes every tile it reached, which is rasterized
/// again; dropping rows one a frame would rasterize a tile a frame for
/// nothing.
fn retained_rows(held: &BTreeSet<usize>, needed: &Range<usize>) -> Range<usize> {
    let (Some(first), Some(last)) = (held.first(), held.last()) else {
        return needed.clone();
    };
    let outside = held.iter().filter(|row| !needed.contains(row)).count();
    if outside > (needed.len() / 4).max(1) {
        needed.clone()
    } else {
        (*first).min(needed.start)..(*last + 1).max(needed.end)
    }
}

/// What a frame showing the rows `visible` of a list does with the rows its
/// layer `layer` holds, keeping them (`mode` is [`Mode::Extend`]) or not.
///
/// A list without a layer renders only the rows it shows, and the element
/// states of a row it no longer shows (a nested scroll offset, a hover
/// state) are dropped with the frame. Rows a layer holds are rendered before
/// they show and kept after, so that their element states would outlive
/// that; instead, a row leaving the viewport (`leaving`) is neither rendered
/// nor keeps its element states that frame, and is rendered afresh before
/// it shows again (see [`Row::dropped`]).
struct RowSort {
    /// The rows rendered again (see [`RowsFrame::stale`]).
    stale: BTreeSet<usize>,
    /// The rows not rendered: those the layer keeps, or, painted afresh,
    /// those leaving the viewport.
    unrendered: BTreeSet<usize>,
    leaving: BTreeSet<usize>,
}

fn sort_rows(
    window: &Window,
    layer: &crate::fast::layers::Layer,
    mode: Mode,
    translation: Point<ScaledPixels>,
    viewport: Bounds<Pixels>,
    visible: &Range<usize>,
) -> RowSort {
    let rows = &layer.rows;
    // A row the layer holds without element states has none to drop.
    let leaving: BTreeSet<usize> = match &rows.visible {
        Some((_, before)) => before
            .clone()
            .filter(|ix| !visible.contains(ix))
            .filter(|ix| rows.rows.get(ix).is_none_or(|row| row.has_states))
            .collect(),
        None => BTreeSet::new(),
    };
    match mode {
        Mode::Repaint => RowSort {
            stale: BTreeSet::new(),
            unrendered: leaving.clone(),
            leaving,
        },
        Mode::Extend => {
            // Only a row the list shows shows its hover; one it does not is
            // checked again before it shows.
            let mut stale = stale_rows(window, layer, translation, viewport);
            stale.retain(|row| visible.contains(row) && !leaving.contains(row));
            stale.extend(
                rows.rows
                    .range(visible.clone())
                    .filter(|(_, row)| row.dropped)
                    .map(|(ix, _)| *ix),
            );
            let unrendered = rows
                .rows
                .keys()
                .copied()
                .filter(|row| !stale.contains(row))
                .chain(leaving.iter().copied())
                .collect();
            RowSort {
                stale,
                unrendered,
                leaving,
            }
        }
    }
}

/// The rows the layer `layer` holds whose hovers will have changed when the
/// frame being drawn paints, with the layer's content moved by
/// `translation` and clipped to `viewport`: they are rendered again.
///
/// A frame hit tests the pointer against its own hitboxes between its
/// prepaint and its paint, and elements paint their hover styles by that.
/// Which rows to render again is decided before, as the rows prepaint: the
/// hit test is foretold from the last frame's hitboxes, those of the rows
/// moved to where they show now. Hitboxes outside the list are taken to stay
/// where they were; [`check_hovers`] catches a row whose hover the foretelling
/// missed.
fn stale_rows(
    window: &Window,
    layer: &crate::fast::layers::Layer,
    translation: Point<ScaledPixels>,
    viewport: Bounds<Pixels>,
) -> BTreeSet<usize> {
    let rows = &layer.rows.rows;
    if rows.values().all(|row| row.hovers.is_empty()) {
        return BTreeSet::new();
    }
    let Some(record) = layer.record.as_ref() else {
        return rows.keys().copied().collect();
    };
    let range = &record.prepaint_range;
    let rows_at = range.start.hitboxes_index..range.end.hitboxes_index;
    let hit = foretold_hit_test(window, rows, rows_at, translation, viewport);
    let hovered = |id: HitboxId| {
        window.captured_hitbox == Some(id) || (!window.last_input_was_keyboard() && hit.hovers(id))
    };
    rows.iter()
        .filter(|(_, row)| row.hovers.iter().any(|(id, was)| hovered(*id) != *was))
        .map(|(ix, _)| *ix)
        .collect()
}

/// A hit test of the pointer, as [`crate::Frame::hit_test`] does it: the
/// hitboxes under it, topmost first, and how many of them are hovered.
#[derive(Default)]
struct ForetoldHitTest {
    ids: SmallVec<[HitboxId; 8]>,
    hover_count: Option<usize>,
    blocked: bool,
}

impl ForetoldHitTest {
    /// Takes in `hitbox`, the next one down.
    fn visit(&mut self, hitbox: &Hitbox, position: Point<Pixels>) {
        if self.blocked {
            return;
        }
        let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
        if bounds.contains(&position) {
            self.ids.push(hitbox.id);
            if self.hover_count.is_none()
                && hitbox.behavior == crate::HitboxBehavior::BlockMouseExceptScroll
            {
                self.hover_count = Some(self.ids.len());
            }
            if hitbox.behavior == crate::HitboxBehavior::BlockMouse {
                self.blocked = true;
            }
        }
    }

    fn hovers(&self, id: HitboxId) -> bool {
        let count = self.hover_count.unwrap_or(self.ids.len());
        self.ids[..count].contains(&id)
    }
}

/// The hit test of the pointer the frame being drawn will make: the last
/// frame's hitboxes, those at `rows_at`, which the rows of `rows` inserted,
/// replaced by the rows' hitboxes moved to where the rows show with the
/// layer's content moved by `translation`, and clipped to `viewport`.
fn foretold_hit_test(
    window: &Window,
    rows: &BTreeMap<usize, Row>,
    rows_at: Range<usize>,
    translation: Point<ScaledPixels>,
    viewport: Bounds<Pixels>,
) -> ForetoldHitTest {
    let position = window.mouse_position;
    let scale_factor = window.scale_factor();
    let hitboxes = &window.rendered_frame.hitboxes;
    let rows_at = rows_at.start.min(hitboxes.len())..rows_at.end.min(hitboxes.len());
    let mut hit = ForetoldHitTest::default();
    for hitbox in hitboxes[rows_at.end..].iter().rev() {
        hit.visit(hitbox, position);
    }
    for row in rows.values().rev() {
        let delta = row.delta(translation, scale_factor);
        for hitbox in input::LayerInput::hitboxes_at(&row.hitboxes, delta, viewport)
            .collect::<SmallVec<[Hitbox; 4]>>()
            .iter()
            .rev()
        {
            hit.visit(hitbox, position);
        }
    }
    for hitbox in hitboxes[..rows_at.start].iter().rev() {
        hit.visit(hitbox, position);
    }
    hit
}

/// The size of a uniform list's measured item: `measure`d, unless the
/// frame only scrolls the list's layer, whose content, the measured item
/// included, is then as it was (spec §8).
pub(crate) fn measure_item(
    window: &mut Window,
    cx: &mut App,
    id: Option<&GlobalElementId>,
    measure: impl FnOnce(&mut Window, &mut App) -> Size<Pixels>,
) -> Size<Pixels> {
    if !LIST_LAYERS {
        return measure(window, cx);
    }
    if !COMPILED || window.fast_layers.layers.is_empty() {
        return measure(window, cx);
    }
    let Some(id) = id else {
        return measure(window, cx);
    };
    if let Some(size) = kept_item_size(window, cx, id) {
        return size;
    }
    let size = measure(window, cx);
    let rem_size = window.rem_size();
    let text_style = window.text_style();
    if let Some(layer) = window.fast_layers.layers.get_mut(id) {
        layer.rows.measured = Some(Measured {
            size,
            rem_size,
            text_style,
        });
    }
    size
}

/// The measured item's size as the layer of the list `id` keeps it, if the
/// frame only scrolls the layer.
fn kept_item_size(window: &Window, cx: &App, id: &GlobalElementId) -> Option<Size<Pixels>> {
    if paint::inside_layer(window) || !active(window, cx) {
        return None;
    }
    let layer = window.fast_layers.layers.get(id)?;
    let record = layer.record.as_ref()?;
    let measured = layer.rows.measured.as_ref()?;
    if !layer.rows.list
        || measured.rem_size != window.rem_size()
        || measured.text_style != window.text_style()
    {
        return None;
    }
    #[cfg(any(test, feature = "test-support"))]
    if let Some(decision) = window.fast_layers.forced_decision {
        return (decision == Decision::Composite).then_some(measured.size);
    }
    invalidate::scroll_only(window, cx, id, record).then_some(measured.size)
}

/// `scroll_offset`, a uniform list's offset about to place its rows, moved
/// to whole device pixels where layers are compiled, so that rows painted
/// into a layer and rows drawn without one land on the same pixels. See
/// [`paint::snap_scroll_offset`].
pub(crate) fn snap_item_offset(window: &Window, scroll_offset: Point<Pixels>) -> Point<Pixels> {
    if !LIST_LAYERS {
        return scroll_offset;
    }
    paint::snap_scroll_offset(window, scroll_offset)
}

/// Decides what the uniform list `id` does with its rows this frame, and
/// sets up rendering and prepainting them. The list's rows are
/// `item_height` tall, `item_count` of them from the top of
/// `padded_bounds`, scrolled by `scroll_offset`; it shows the rows
/// `visible`. A list flipped vertically keeps today's path.
#[allow(clippy::too_many_arguments)]
pub(crate) fn begin_uniform_list(
    window: &mut Window,
    cx: &mut App,
    id: Option<&GlobalElementId>,
    padded_bounds: Bounds<Pixels>,
    scroll_offset: Point<Pixels>,
    item_height: Pixels,
    item_count: usize,
    visible: &Range<usize>,
    y_flipped: bool,
) -> Rows {
    if !COMPILED || !LIST_LAYERS || y_flipped || item_height <= Pixels::ZERO {
        return Rows(None);
    }
    let Some(id) = id else {
        return Rows(None);
    };
    if paint::inside_layer(window) || !active(window, cx) {
        return Rows(None);
    }
    let viewport = window.content_mask().bounds;
    let content_size = size(padded_bounds.size.width, item_height * item_count);
    let decision = policy::decide(window, cx, id, padded_bounds, content_size, scroll_offset);
    let decision = input::decide(window, id, decision);
    if decision == Decision::Bypass {
        let frame = window.fast_layers.frame;
        if let Some(layer) = window.fast_layers.layers.get_mut(id) {
            layer.rows.visible = Some((frame, visible.clone()));
        }
        return Rows(None);
    }
    let overscan = (viewport.size.height * paint::OVERSCAN_VIEWPORTS / item_height)
        .ceil()
        .max(1.) as usize;
    let needed = needed_rows(visible, overscan, item_count);
    let layer = paint::layer_mut(window, id);
    let extends = decision == Decision::Composite
        && layer.rows.list
        && !layer.rows.due_for_repaint(&needed)
        && layer
            .record
            .as_ref()
            .is_some_and(|record| record.scroll_offset.x == scroll_offset.x);
    let mode = if extends { Mode::Extend } else { Mode::Repaint };

    let translation = paint::translation(window, scroll_offset);
    let RowSort {
        stale,
        unrendered,
        leaving,
    } = sort_rows(
        window,
        &window.fast_layers.layers[id],
        mode,
        translation,
        viewport,
        visible,
    );
    let (retain, carried) = match mode {
        Mode::Extend => {
            let retain = retained_rows(&unrendered, &needed);
            let carried = unrendered.range(retain.clone()).copied().collect();
            (retain, carried)
        }
        Mode::Repaint => (needed.clone(), Vec::new()),
    };
    let plan = plan(&unrendered, needed.clone());
    let slot = |row: usize| Bounds {
        origin: point(
            viewport.origin.x,
            padded_bounds.origin.y + scroll_offset.y + item_height * row,
        ),
        size: size(viewport.size.width, item_height),
    };
    let slots: BTreeMap<usize, Bounds<Pixels>> = plan
        .render
        .iter()
        .flat_map(|run| run.clone())
        .map(|row| (row, slot(row)))
        .collect();
    let mut painted_region = viewport;
    if !needed.is_empty() {
        painted_region = painted_region
            .union(&slot(needed.start))
            .union(&slot(needed.end - 1));
    }
    let order = slots.keys().copied().collect();
    let frame = RowsFrame {
        mode,
        list: None,
        skip_held: false,
        needed,
        retain,
        stale,
        visible: visible.clone(),
        leaving,
        carried,
        slots,
        viewport,
        painted_region,
        scroll_offset,
        translation,
        prepaint_start: window.prepaint_index(),
        prepaint_range: window.prepaint_index()..window.prepaint_index(),
        recording: Some(cx.begin_recording_dependencies()),
        dependencies: RenderDependencies::default(),
        row_prepaints: Vec::new(),
        open_row: None,
        layout_keys: Some(record_layout_keys(window)),
        order,
        next: 0,
        anchor: None,
        prepainted: Vec::new(),
        extra: Vec::new(),
        paint: None,
    };
    window.fast_layers.painting = Some(marker(id, &frame));
    paint::layer_mut(window, id).rows.frame = Some(frame);
    if mode == Mode::Extend {
        keep_reads(window, cx, id);
        carry_prepaint_rows(window, id);
    }
    Rows(Some(plan))
}

/// What the rows of a list that `frame` draws are prepainted and painted
/// in, in place of the list's own clip: the list's width, and as far above
/// and below as a row could ever be held.
///
/// A row's masks (its hitboxes', its primitives') are kept with it, moved
/// with the scroll, for as long as the layer holds it. The rows are painted
/// in their own space so that no edge of what they were painted in comes to
/// clip them once they have moved; the viewport clips them where they are
/// composited, as the list's own clip does without a layer. Only the rows
/// the layer is to hold are rendered, so nothing more is drawn for it.
fn rows_region(frame: &RowsFrame) -> Bounds<Pixels> {
    const REACH: Pixels = px(1_000_000.);
    let region = frame.painted_region.union(&frame.viewport);
    Bounds::from_corners(
        point(region.left(), region.top() - REACH),
        point(region.right(), region.bottom() + REACH),
    )
}

/// Tells the window that what the rows held by the layer of the list `id`
/// read is read again this frame, which renders them not: so that the
/// window stays told of their changes, a row view's notifications included,
/// as it is on today's path, where the list renders the rows it shows every
/// frame.
fn keep_reads(window: &Window, cx: &mut App, id: &GlobalElementId) {
    let Some(record) = window
        .fast_layers
        .layers
        .get(id)
        .and_then(|layer| layer.record.as_ref())
    else {
        return;
    };
    cx.replay_dependencies(&record.dependencies);
    cx.entities.extend_accessed(record.views.iter());
}

/// Carries into the frame being drawn the prepaint records of the rows the
/// layer of the list `id` keeps this frame, where prepainting them would add
/// them, their hitboxes moved by the scroll since each was painted.
fn carry_prepaint_rows(window: &mut Window, id: &GlobalElementId) {
    let scale_factor = window.scale_factor();
    let Some(layer) = window.fast_layers.layers.get_mut(id) else {
        return;
    };
    let Some(frame) = layer.rows.frame.as_ref() else {
        return;
    };
    let carried = frame.carried.clone();
    let leaving = frame.leaving.clone();
    let (translation, viewport) = (frame.translation, frame.viewport);
    // A tooltip shows where its element was when it was requested; a scroll
    // hides tooltips (spec §7, rule 5).
    let tooltips = layer.rows.last_translation == Some(translation);
    let mut rows = mem::take(&mut layer.rows.rows);
    for ix in &carried {
        let Some(row) = rows.get_mut(ix) else {
            continue;
        };
        let delta = row.delta(translation, scale_factor);
        let element_states = !row.dropped && !leaving.contains(ix);
        window.keep_retained_layout(&row.layout_keys);
        row.prepaint = reuse::carry_prepaint_records(
            window,
            &row.prepaint,
            &row.hitboxes,
            delta,
            viewport,
            tooltips,
            element_states,
        );
    }
    // Keeping the rows' layout nodes logged their keys: they are not the
    // next row's.
    let log_end = window.record_claimed_layout_keys();
    window.finish_recording_claimed_layout_keys(log_end);
    if let Some(layer) = window.fast_layers.layers.get_mut(id) {
        layer.rows.rows = rows;
        if let Some((_, mark)) = layer
            .rows
            .frame
            .as_mut()
            .and_then(|frame| frame.layout_keys.as_mut())
        {
            *mark = log_end;
        }
    }
}

/// Carries into the frame being drawn the paint records of the rows whose
/// prepaint records [`carry_prepaint_rows`] carried.
fn carry_paint_rows(window: &mut Window, id: &GlobalElementId) {
    let scale_factor = window.scale_factor();
    let Some(layer) = window.fast_layers.layers.get_mut(id) else {
        return;
    };
    let Some(frame) = layer.rows.frame.as_ref() else {
        return;
    };
    if frame.carried.is_empty() {
        return;
    }
    let carried = frame.carried.clone();
    let leaving = frame.leaving.clone();
    let (translation, viewport) = (frame.translation, frame.viewport);
    let mut rows = mem::take(&mut layer.rows.rows);
    for ix in &carried {
        let Some(row) = rows.get_mut(ix) else {
            continue;
        };
        let delta = row.delta(translation, scale_factor);
        let element_states = !row.dropped && !leaving.contains(ix);
        row.paint = reuse::carry_paint_records(window, &row.paint, delta, viewport, element_states);
    }
    if let Some(layer) = window.fast_layers.layers.get_mut(id) {
        layer.rows.rows = rows;
    }
}

/// What marks the rows of the list `id` as painting into its layer, for
/// nested views and scroll containers to tell.
fn marker(id: &GlobalElementId, frame: &RowsFrame) -> Painting {
    Painting {
        id: id.clone(),
        viewport: frame.viewport,
        painted_region: frame.painted_region,
        scene: Scene::default(),
        scroll_offset: frame.scroll_offset,
        translation: frame.translation,
        prepaint_range: frame.prepaint_start.clone()..frame.prepaint_start.clone(),
        recording: None,
        dependencies: RenderDependencies::default(),
        input: input::PaintingInput {
            list_region: Some(rows_region(frame)),
            ..Default::default()
        },
        view_layouts: FxHashMap::default(),
    }
}

/// Renders the rows a uniform list renders this frame with `render`: those
/// it shows, `visible`, on today's path, and the rows its layer lacks
/// otherwise, in order.
pub(crate) fn render_rows(
    rows: &Rows,
    visible: Range<usize>,
    mut render: impl FnMut(Range<usize>) -> SmallVec<[AnyElement; 64]>,
) -> SmallVec<[AnyElement; 64]> {
    let Some(plan) = &rows.0 else {
        return render(visible);
    };
    let mut items = SmallVec::new();
    for run in &plan.render {
        items.extend(render(run.clone()));
    }
    items
}

/// The indices of the rows [`render_rows`] rendered, in order.
pub(crate) fn row_indices(rows: &Rows, visible: Range<usize>) -> RowIndices {
    match &rows.0 {
        None => RowIndices::Visible(visible),
        Some(plan) => RowIndices::Planned(
            plan.render
                .iter()
                .flat_map(|run| run.clone())
                .collect::<Vec<_>>()
                .into_iter(),
        ),
    }
}

/// See [`row_indices`].
pub(crate) enum RowIndices {
    Visible(Range<usize>),
    Planned(std::vec::IntoIter<usize>),
}

impl Iterator for RowIndices {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        match self {
            RowIndices::Visible(range) => range.next(),
            RowIndices::Planned(rows) => rows.next(),
        }
    }
}

/// Prepaints a uniform list's row `ix` with `f`, noting what prepainting it
/// adds to the frame when it is painted into the list's layer.
pub(crate) fn prepaint_row<R>(
    window: &mut Window,
    cx: &mut App,
    ix: usize,
    f: impl FnOnce(&mut Window, &mut App) -> R,
) -> R {
    if !LIST_LAYERS || window.fast_layers.painting.is_none() {
        return f(window, cx);
    }
    let began = begin_row(window, None, ix);
    let result = f(window, cx);
    if began {
        end_row(window, None);
    }
    result
}

/// The frame of the list whose rows are prepainting into its layer, if it
/// is a `list` whose state has id `list`, or a uniform list for `None`.
fn prepainting_frame(window: &mut Window, list: Option<usize>) -> Option<&mut RowsFrame> {
    let id = window.fast_layers.painting.as_ref()?.id.clone();
    frame_mut(window, &id).filter(|frame| frame.list == list && frame.paint.is_none())
}

/// Notes that the row `ix` of the list whose rows are prepainting, a `list`
/// whose state has id `list` or a uniform list for `None`, begins to
/// prepaint. Returns whether it was noted: a row of a list nested in a row
/// is not.
fn begin_row(window: &mut Window, list: Option<usize>, ix: usize) -> bool {
    let start = window.prepaint_index();
    let masks = window
        .fast_layers
        .painting
        .as_ref()
        .map_or(0, |painting| painting.input.hitbox_masks.len());
    let Some(frame) = prepainting_frame(window, list) else {
        return false;
    };
    if frame.open_row.is_some() {
        return false;
    }
    frame.open_row = Some((ix, start, masks));
    true
}

/// Notes that the row [`begin_row`] noted is prepainted.
fn end_row(window: &mut Window, list: Option<usize>) {
    let end = window.prepaint_index();
    let Some(painting) = window.fast_layers.painting.as_ref() else {
        return;
    };
    let all_masks = &painting.input.hitbox_masks;
    let id = painting.id.clone();
    let Some(frame) = window
        .fast_layers
        .layers
        .get_mut(&id)
        .and_then(|layer| layer.rows.frame.as_mut())
        .filter(|frame| frame.list == list)
    else {
        return;
    };
    let Some((row, start, masks_start)) = frame.open_row.take() else {
        return;
    };
    let masks = all_masks
        .get(masks_start..)
        .map(<[_]>::to_vec)
        .unwrap_or_default();
    let engine = window.layout_engine.as_ref().unwrap();
    let layout_keys = match frame.layout_keys.as_mut() {
        Some((_, mark)) => {
            let keys = engine.claimed_keys_since(*mark).to_vec();
            *mark += keys.len();
            keys
        }
        None => Vec::new(),
    };
    frame.row_prepaints.push(RowPrepaint {
        row,
        range: start..end,
        masks,
        layout_keys,
    });
}

/// Starts recording the layout keys a list's rows claim, returning where
/// the recording starts, twice: where it began, and where the last row ended.
fn record_layout_keys(window: &mut Window) -> (usize, usize) {
    let start = window.record_claimed_layout_keys();
    (start, start)
}

/// Ends what [`begin_uniform_list`] began, once the rows are prepainted.
pub(crate) fn end_rows(window: &mut Window, cx: &mut App, rows: Rows) {
    if rows.0.is_none() {
        return;
    }
    let Some(painting) = window.fast_layers.painting.take() else {
        debug_assert!(false, "a list's rows ended without beginning");
        return;
    };
    finish_prepaint(window, cx, &painting.id);
}

/// Ends the prepaint of the rows of the list `id`: what it added to the
/// frame and read is the frame's.
fn finish_prepaint(window: &mut Window, cx: &mut App, id: &GlobalElementId) {
    let end = window.prepaint_index();
    let Some(frame) = frame_mut(window, id) else {
        return;
    };
    frame.prepaint_range = frame.prepaint_start.clone()..end;
    if let Some((start, _)) = frame.layout_keys.take() {
        window.finish_recording_claimed_layout_keys(start);
    }
    let Some(frame) = frame_mut(window, id) else {
        return;
    };
    let recording = frame.recording.take();
    if let Some(recording) = recording {
        let dependencies = without_owner(window, cx.finish_recording_dependencies(recording).all);
        if let Some(frame) = frame_mut(window, id) {
            frame.dependencies = dependencies;
        }
    }
}

/// `dependencies`, read by a list's rows, without the view holding the
/// list: a list renders its rows as that view, whose own changes, and
/// whether it was notified for anything but a scroll, are judged apart (see
/// [`invalidate::scroll_only`]).
fn without_owner(window: &Window, dependencies: RenderDependencies) -> RenderDependencies {
    invalidate::without_entity(&dependencies, invalidate::owner_view(window))
        .unwrap_or(dependencies)
}

fn frame_mut<'a>(window: &'a mut Window, id: &GlobalElementId) -> Option<&'a mut RowsFrame> {
    window
        .fast_layers
        .layers
        .get_mut(id)
        .and_then(|layer| layer.rows.frame.as_mut())
}

/// The id a `list` whose state `version` counts changes of has: the id of
/// the elements around it, and its state.
fn list_id(window: &Window, version: &StateVersion) -> GlobalElementId {
    let mut path: Vec<ElementId> = window.element_id_stack.to_vec();
    path.push(ElementId::NamedInteger(
        LIST_ID_NAME.into(),
        version.id() as u64,
    ));
    GlobalElementId::new(&path)
}

/// What the ids of the elements and views inside the scroll container `id`
/// start with: `id`, or for a `list`, which has no id of its own, the id of
/// the elements around it (see [`list_id`]).
pub(crate) fn content_prefix(id: &GlobalElementId) -> &[ElementId] {
    match id.split_last() {
        Some((ElementId::NamedInteger(name, _), around)) if name.as_ref() == LIST_ID_NAME => around,
        _ => id,
    }
}

/// Whether a view drawn into the rows the layer of the list `id` holds is
/// one `f` picks. A list's rows are rendered as it prepaints, not as the view
/// holding it renders, so their views are not among that view's nested ones;
/// the layer remembers them.
pub(crate) fn any_held_view(
    window: &Window,
    id: &GlobalElementId,
    f: impl Fn(EntityId) -> bool,
) -> bool {
    window
        .fast_layers
        .layers
        .get(id)
        .filter(|layer| layer.rows.list)
        .and_then(|layer| layer.record.as_ref())
        .is_some_and(|record| record.views.iter().copied().any(f))
}

/// The name of the last part of a `list`'s id.
const LIST_ID_NAME: &str = "fast-list";

/// The frame of the `list` whose rows are prepainting, if it is the one
/// whose state `version` counts changes of.
fn list_frame<'a>(window: &'a mut Window, version: &StateVersion) -> Option<&'a mut RowsFrame> {
    let id = window.fast_layers.painting.as_ref()?.id.clone();
    frame_mut(window, &id).filter(|frame| frame.list == Some(version.id()))
}

/// Decides what the `list` of `state`, laid out at `bounds`, does with its
/// rows this frame, before it lays them out and prepaints them.
pub(crate) fn begin_list(
    window: &mut Window,
    cx: &mut App,
    state: &crate::StateInner,
    bounds: Bounds<Pixels>,
) {
    if !COMPILED || !LIST_LAYERS || paint::inside_layer(window) || !active(window, cx) {
        return;
    }
    let version = state.version.clone();
    let id = list_id(window, &version);
    let viewport = window.content_mask().bounds.intersect(&bounds);
    let scroll_top = state.scroll_top(&state.logical_scroll_top());
    let scroll_offset = paint::snap_scroll_offset(window, point(px(0.), -scroll_top));
    // A list lays out its rows itself, and is not taken for changed when a
    // row is measured for the first time: its rows are checked where they
    // are placed.
    let decision = policy::decide(window, cx, &id, bounds, bounds.size, scroll_offset);
    let decision = input::decide(window, &id, decision);
    // Remembered as painted, for its scrolls to be told apart.
    invalidate::painted_list(window, &id, &version);
    if decision == Decision::Bypass {
        return;
    }
    let layer = paint::layer_mut(window, &id);
    let mode = if decision == Decision::Composite && layer.rows.list && layer.record.is_some() {
        Mode::Extend
    } else {
        Mode::Repaint
    };
    let frame = RowsFrame {
        mode,
        list: Some(version.id()),
        skip_held: mode == Mode::Extend && state.pending_scroll.is_none(),
        needed: 0..0,
        retain: 0..0,
        stale: BTreeSet::new(),
        visible: 0..0,
        leaving: BTreeSet::new(),
        carried: Vec::new(),
        slots: BTreeMap::new(),
        viewport,
        painted_region: viewport,
        scroll_offset,
        translation: Point::default(),
        prepaint_start: window.prepaint_index(),
        prepaint_range: window.prepaint_index()..window.prepaint_index(),
        recording: Some(cx.begin_recording_dependencies()),
        dependencies: RenderDependencies::default(),
        row_prepaints: Vec::new(),
        open_row: None,
        layout_keys: Some(record_layout_keys(window)),
        order: Vec::new(),
        next: 0,
        anchor: None,
        prepainted: Vec::new(),
        extra: Vec::new(),
        paint: None,
    };
    window.fast_layers.painting = Some(marker(&id, &frame));
    paint::layer_mut(window, &id).rows.frame = Some(frame);
    if mode == Mode::Extend {
        keep_reads(window, cx, &id);
    }
}

/// Whether a `list`, whose state `version` counts changes of, laying out the
/// rows it shows, leaves out its row `ix`, whose size it knows when
/// `measured`: the frame only scrolled its layer, which holds the row as it
/// is.
pub(crate) fn keeps_row(
    window: &Window,
    version: &StateVersion,
    ix: usize,
    measured: bool,
) -> bool {
    if !LIST_LAYERS {
        return false;
    }
    if !measured {
        return false;
    }
    let Some(painting) = window.fast_layers.painting.as_ref() else {
        return false;
    };
    let Some(layer) = window.fast_layers.layers.get(&painting.id) else {
        return false;
    };
    layer.rows.frame.as_ref().is_some_and(|frame| {
        frame.list == Some(version.id()) && frame.skip_held && layer.rows.rows.contains_key(&ix)
    })
}

/// Moves `origin`, where a `list` of `state` scrolled to `scroll_top` is
/// about to place its first row shown, up by how far it is scrolled into
/// that row, as the list does, but so that the list's offset from its first
/// row is a whole number of device pixels where layers are compiled (see
/// [`paint::snap_scroll_offset`]); and notes where the row lies, for the
/// list's layer.
pub(crate) fn snap_item_origin(
    window: &mut Window,
    state: &crate::StateInner,
    scroll_top: &crate::ListOffset,
    origin: &mut Point<Pixels>,
) {
    if !LIST_LAYERS {
        origin.y -= scroll_top.offset_in_item;
        return;
    }
    let offset = state.scroll_top(scroll_top);
    let snapped = paint::snap_scroll_offset(window, point(px(0.), offset)).y;
    origin.y -= scroll_top.offset_in_item + (snapped - offset);
    if let Some(frame) = list_frame(window, &state.version) {
        frame.anchor = Some((scroll_top.item_ix, *origin));
        // The list lays out its rows again, after an autoscroll.
        frame.prepainted.clear();
        frame.row_prepaints.clear();
        frame.open_row = None;
    }
}

/// Moves `origin`, where a `list` is about to prepaint its row `ix`, to
/// where the row lies, when it leaves out the rows its layer holds and so
/// cannot add up the rows before it; and notes that the row begins to
/// prepaint, the one before it prepainted.
pub(crate) fn place_list_item(
    window: &mut Window,
    state: &crate::StateInner,
    ix: usize,
    origin: &mut Point<Pixels>,
) {
    if !LIST_LAYERS {
        return;
    }
    let Some(id) = window.fast_layers.painting.as_ref().map(|p| p.id.clone()) else {
        return;
    };
    let list = Some(state.version.id());
    if frame_mut(window, &id).is_none_or(|frame| frame.list != list) {
        return;
    }
    end_row(window, list);
    begin_row(window, list, ix);
    let scale_factor = window.scale_factor();
    let Some(layer) = window.fast_layers.layers.get_mut(&id) else {
        return;
    };
    let rows = &mut layer.rows;
    let Some(frame) = rows.frame.as_mut() else {
        return;
    };
    frame.prepainted.push(ix);
    let Some((anchor, anchor_origin)) = frame.anchor else {
        return;
    };
    let heights = |row: usize| row_height(state, &rows.rows, row, scale_factor);
    if let Some(y) = row_top(anchor, anchor_origin.y, ix, heights) {
        origin.y = y;
    }
}

/// The height of a `list`'s row `row`: as the list measured it, or as the
/// layer holds it.
fn row_height(
    state: &crate::StateInner,
    rows: &BTreeMap<usize, Row>,
    row: usize,
    scale_factor: f32,
) -> Option<Pixels> {
    let mut cursor = state.items.cursor::<crate::Count>(());
    cursor.seek(&crate::Count(row), sum_tree::Bias::Right);
    cursor
        .item()
        .and_then(|item| item.size())
        .map(|size| size.height)
        .or_else(|| {
            rows.get(&row)
                .map(|held| px(held.slot.size.height.0 / scale_factor))
        })
}

/// The top of row `ix` of a list whose row `anchor` lies at `anchor_top`,
/// adding up the heights of the rows between them in order, as the list
/// does.
fn row_top(
    anchor: usize,
    anchor_top: Pixels,
    ix: usize,
    mut height: impl FnMut(usize) -> Option<Pixels>,
) -> Option<Pixels> {
    let mut top = anchor_top;
    if ix >= anchor {
        for row in anchor..ix {
            top += height(row)?;
        }
    } else {
        for row in (ix..anchor).rev() {
            top -= height(row)?;
        }
    }
    Some(top)
}

/// Ends the layout and prepaint of the rows of the `list` of `state`, laid
/// out at `bounds`: the rows around those it showed are rendered and
/// prepainted into its layer with `render_item`, as far as the layer is to
/// hold them, and the records of the rows it keeps are carried.
pub(crate) fn end_list(
    window: &mut Window,
    cx: &mut App,
    state: &crate::StateInner,
    render_item: &mut crate::RenderItemFn,
    bounds: Bounds<Pixels>,
) {
    if !LIST_LAYERS {
        return;
    }
    let list = Some(state.version.id());
    let id = match window.fast_layers.painting.as_ref() {
        Some(painting) => painting.id.clone(),
        None => {
            note_shown_without_layer(window, state, bounds);
            return;
        }
    };
    if frame_mut(window, &id).is_none_or(|frame| frame.list != list) {
        return;
    }
    end_row(window, list);
    let scale_factor = window.scale_factor();
    let Some(layer) = window.fast_layers.layers.get_mut(&id) else {
        return;
    };
    let rows = &mut layer.rows;
    let Some(frame) = rows.frame.as_mut() else {
        return;
    };
    let Some((anchor, anchor_origin)) = frame.anchor else {
        // No row was shown: nothing is painted into the layer.
        window.fast_layers.painting = None;
        finish_prepaint(window, cx, &id);
        if let Some(layer) = window.fast_layers.layers.get_mut(&id) {
            layer.rows.frame = None;
        }
        return;
    };
    let item_count = state.items.summary().count;
    let viewport = frame.viewport;

    // The rows the layer holds stay where they are only if the first row
    // shown lies at a whole number of device pixels from where the layer
    // holds it, and every row it holds is as tall as the list measures it;
    // and, once the rows around it are placed, if each row it keeps lands on
    // the pixels it would painted afresh (see [`held_rows_land_alike`]).
    let mut translation = None;
    if frame.mode == Mode::Extend
        && let Some(held) = rows.rows.get(&anchor)
    {
        let x = anchor_origin.x.0 * scale_factor - held.slot.origin.x.0;
        let y = anchor_origin.y.0 * scale_factor - held.slot.origin.y.0;
        let whole = |value: f32| (value - value.round()).abs() < 0.01;
        let heights_hold = rows.rows.iter().all(|(row, held)| {
            let mut cursor = state.items.cursor::<crate::Count>(());
            cursor.seek(&crate::Count(*row), sum_tree::Bias::Right);
            cursor
                .item()
                .and_then(|item| item.size())
                .is_none_or(|size| {
                    (size.height.0 * scale_factor - held.slot.size.height.0).abs() < 0.01
                })
        });
        let in_list = rows
            .rows
            .last_key_value()
            .is_none_or(|(last, _)| *last < item_count);
        if whole(x) && whole(y) && heights_hold && in_list {
            translation = Some(point(ScaledPixels(x.round()), ScaledPixels(y.round())));
        }
    }
    let frame = rows.frame.as_mut().unwrap();
    if translation.is_none() {
        frame.mode = Mode::Repaint;
    }
    let frame_translation = translation.unwrap_or_default();
    frame.translation = frame_translation;

    // The rows shown and two viewports' height of rows on each side.
    let extent = viewport.size.height * paint::OVERSCAN_VIEWPORTS;
    let (top, bottom) = (viewport.top() - extent, viewport.bottom() + extent);
    let available = crate::size(
        AvailableSpace::Definite(bounds.size.width),
        AvailableSpace::MinContent,
    );
    let mut rendered: FxHashMap<usize, AnyElement> = FxHashMap::default();
    let mut tops: BTreeMap<usize, (Pixels, Pixels)> = BTreeMap::new();
    let mut height_of = |row: usize,
                         window: &mut Window,
                         cx: &mut App,
                         rendered: &mut FxHashMap<usize, AnyElement>|
     -> Pixels {
        let rows = &window.fast_layers.layers[&id].rows.rows;
        if let Some(height) = row_height(state, rows, row, scale_factor) {
            return height;
        }
        let mut element = render_item(row, window, cx);
        let size =
            crate::fast::layout_key::layout_as_list_item(&mut element, row, available, window, cx);
        rendered.insert(row, element);
        size.height
    };
    let mut y = anchor_origin.y;
    let mut row = anchor;
    while row < item_count && y < bottom {
        let height = height_of(row, window, cx, &mut rendered);
        tops.insert(row, (y, height));
        y += height;
        row += 1;
    }
    let end = row;
    let mut y = anchor_origin.y;
    let mut row = anchor;
    while row > 0 && y > top {
        row -= 1;
        let height = height_of(row, window, cx, &mut rendered);
        y -= height;
        tops.insert(row, (y, height));
    }
    let needed = row..end;

    // The rows the list shows: those it renders without a layer.
    let visible = shown_rows(&tops, bounds);
    let layer = &window.fast_layers.layers[&id];
    let mode = layer
        .rows
        .frame
        .as_ref()
        .map_or(Mode::Repaint, |frame| frame.mode);
    let sort = sort_rows(window, layer, mode, frame_translation, viewport, &visible);
    let layer = &mut window.fast_layers.layers.get_mut(&id).unwrap().rows;
    let due_for_repaint = layer.due_for_repaint(&needed);
    let frame = layer.frame.as_mut().unwrap();
    frame.stale = sort.stale;
    frame.leaving = sort.leaving;
    frame.visible = visible;
    // The rows the list prepainted itself, those whose hovers changed among
    // them, are painted into the layer afresh.
    let prepainted: BTreeSet<usize> = frame.prepainted.iter().copied().collect();
    let kept: BTreeSet<usize> = match frame.mode {
        Mode::Extend => sort
            .unrendered
            .into_iter()
            .filter(|row| !prepainted.contains(row))
            .collect(),
        Mode::Repaint => BTreeSet::new(),
    };
    if frame.mode == Mode::Extend
        && (due_for_repaint
            || !held_rows_land_alike(
                &layer.rows,
                &kept,
                &needed,
                &tops,
                frame.translation,
                scale_factor,
            ))
    {
        frame.mode = Mode::Repaint;
    }
    let (held, unrendered) = match frame.mode {
        Mode::Extend => (kept.clone(), kept),
        // Painted afresh, but for the rows leaving the viewport.
        Mode::Repaint => (BTreeSet::new(), frame.leaving.clone()),
    };
    let plan = plan(&unrendered, needed.clone());
    let slot = |(top, height): (Pixels, Pixels)| Bounds {
        origin: point(anchor_origin.x, top),
        size: crate::size(bounds.size.width, height),
    };
    frame.slots = plan
        .render
        .iter()
        .flat_map(|run| run.clone())
        .map(|row| (row, slot(tops[&row])))
        .collect();
    frame.retain = match frame.mode {
        Mode::Extend => retained_rows(&held, &needed),
        Mode::Repaint => needed.clone(),
    };
    frame.carried = held.range(frame.retain.clone()).copied().collect();
    frame.needed = needed;
    let mut painted_region = viewport;
    if let (Some(first), Some(last)) = (tops.values().next(), tops.values().last()) {
        painted_region = painted_region.union(&slot(*first)).union(&slot(*last));
    }
    frame.painted_region = painted_region;
    if frame.mode == Mode::Repaint {
        // Content space is window space as the rows are painted now.
        frame.translation = Point::default();
        frame.stale.clear();
    }
    let to_prepaint: Vec<(usize, Pixels)> = frame
        .slots
        .iter()
        .filter(|(row, _)| !prepainted.contains(row))
        .map(|(row, slot)| (*row, slot.origin.y))
        .collect();
    if let Some(painting) = window.fast_layers.painting.as_mut() {
        painting.painted_region = painted_region;
    }
    carry_prepaint_rows(window, &id);

    let mut extra = Vec::with_capacity(to_prepaint.len());
    let mut unplaced = Vec::new();
    for (row, top) in to_prepaint {
        let mut element = match rendered.remove(&row) {
            Some(element) => element,
            None => {
                let mut element = render_item(row, window, cx);
                let size = crate::fast::layout_key::layout_as_list_item(
                    &mut element,
                    row,
                    available,
                    window,
                    cx,
                );
                let (_, height) = tops[&row];
                let hidden = top + height <= viewport.top() || top >= viewport.bottom();
                if hidden && (size.height.0 - height.0).abs() * scale_factor >= 0.01 {
                    // The list's size for the row is out of date (it was
                    // measured at another scale, say), and the list corrects
                    // it when it shows the row: the layer does not hold a row
                    // where it would not be then.
                    unplaced.push(row);
                    continue;
                }
                element
            }
        };
        let origin = point(anchor_origin.x, top);
        let began = begin_row(window, list, row);
        window.with_content_mask(Some(ContentMask { bounds }), |window| {
            element.prepaint_at(origin, window, cx);
        });
        if began {
            end_row(window, list);
        }
        extra.push((row, element));
    }
    if !extra.is_empty() {
        // Rows the list does not show ask for no autoscroll.
        window.take_autoscroll();
    }
    window.fast_layers.painting = None;
    finish_prepaint(window, cx, &id);
    if let Some(frame) = frame_mut(window, &id) {
        frame.extra = extra;
        for row in unplaced {
            frame.slots.remove(&row);
        }
    }
}

/// Whether each row of `rows` that a `list` keeps, those of `kept` in
/// `needed`, lands on the pixels it would if painted afresh when its content
/// is moved by `translation`: the row lies at `tops` (its top and height),
/// at the same fraction of a device pixel as it does moved, and neither its
/// top nor its bottom lies half way between device pixels.
///
/// A row's edges are rounded to device pixels as the row is painted, half
/// way toward zero. Rounding a position and then moving it by whole device
/// pixels lands where rounding the moved position does, unless the position
/// is half way: its rounding then depends on its sign, which the move can
/// flip, and on the last bits of how the list added up the rows' heights,
/// which differ from frame to frame. Rows whose height is not a whole number
/// of device pixels (30 px at a scale of 1.25) put edges there.
fn held_rows_land_alike(
    rows: &BTreeMap<usize, Row>,
    kept: &BTreeSet<usize>,
    needed: &Range<usize>,
    tops: &BTreeMap<usize, (Pixels, Pixels)>,
    translation: Point<ScaledPixels>,
    scale_factor: f32,
) -> bool {
    const EPSILON: f32 = 0.01;
    let half_way = |value: f32| ((value - value.floor()) - 0.5).abs() < EPSILON;
    rows.range(needed.clone())
        .filter(|(row, _)| kept.contains(row))
        .all(|(row, held)| {
            let Some((top, height)) = tops.get(row) else {
                return false;
            };
            let top = top.0 * scale_factor;
            let bottom = top + height.0 * scale_factor;
            let moved = held.slot.origin.y.0 + translation.y.0;
            (moved - top).abs() < EPSILON && !half_way(top) && !half_way(bottom)
        })
}

/// The rows of `tops` (each row's top and height) that lie across `bounds`,
/// the list's: those it shows.
fn shown_rows(tops: &BTreeMap<usize, (Pixels, Pixels)>, bounds: Bounds<Pixels>) -> Range<usize> {
    let shown = |(row, (top, height)): (&usize, &(Pixels, Pixels))| {
        (*top < bounds.bottom() && *top + *height > bounds.top()).then_some(*row)
    };
    match (
        tops.iter().find_map(shown),
        tops.iter().rev().find_map(shown),
    ) {
        (Some(first), Some(last)) => first..last + 1,
        _ => 0..0,
    }
}

/// Notes which rows the `list` of `state`, laid out at `bounds`, showed on
/// a frame that kept them off its layer, if it has one: as far down from
/// its first row shown as its bounds reach.
fn note_shown_without_layer(
    window: &mut Window,
    state: &crate::StateInner,
    bounds: Bounds<Pixels>,
) {
    if !COMPILED || window.fast_layers.layers.is_empty() {
        return;
    }
    let id = list_id(window, &state.version);
    let frame = window.fast_layers.frame;
    let Some(layer) = window.fast_layers.layers.get_mut(&id) else {
        return;
    };
    let top = state.logical_scroll_top();
    let mut cursor = state.items.cursor::<crate::Count>(());
    cursor.seek(&crate::Count(top.item_ix), sum_tree::Bias::Right);
    let mut height = -top.offset_in_item;
    let mut end = top.item_ix;
    while let Some(item) = cursor.item()
        && height < bounds.size.height
    {
        height += item.size().map_or(bounds.size.height, |size| size.height);
        end += 1;
        cursor.next();
    }
    layer.rows.visible = Some((frame, top.item_ix..end));
}

/// Starts painting the rows of the `list` of `state`.
pub(crate) fn begin_paint_list(window: &mut Window, cx: &mut App, state: &crate::ListState) {
    if !LIST_LAYERS {
        return;
    }
    if !COMPILED || window.fast_layers.layers.is_empty() {
        return;
    }
    let version = state.0.borrow().version.clone();
    let id = list_id(window, &version);
    begin_paint_rows(window, cx, Some(&id));
}

/// Ends painting the rows of the `list` of `state`: the rows rendered for
/// its layer alone are painted, and the layer is composited.
pub(crate) fn end_paint_list(window: &mut Window, cx: &mut App, state: &crate::ListState) {
    if !LIST_LAYERS {
        return;
    }
    if !COMPILED || window.fast_layers.layers.is_empty() {
        return;
    }
    let version = state.0.borrow().version.clone();
    let id = list_id(window, &version);
    let Some(frame) = frame_mut(window, &id) else {
        return;
    };
    let extra = mem::take(&mut frame.extra);
    for (row, mut element) in extra {
        paint_row(window, cx, Some(row), |window, cx| {
            element.paint(window, cx)
        });
    }
    end_paint_rows(window, cx, Some(&id));
}

/// Starts painting the rows of the list `id` as its prepaint decided, and
/// carries the paint records of the rows its layer keeps.
pub(crate) fn begin_paint_rows(window: &mut Window, cx: &mut App, id: Option<&GlobalElementId>) {
    if !LIST_LAYERS {
        return;
    }
    let Some(id) = id else {
        return;
    };
    if window.fast_layers.layers.is_empty() {
        return;
    }
    let Some(frame) = frame_mut(window, id) else {
        return;
    };
    if frame.paint.is_some() {
        return;
    }
    let region = rows_region(frame);
    let has_rows = !frame.slots.is_empty();
    let background = if has_rows {
        paint::bake_background(window)
    } else {
        None
    };
    let mut state = PaintState {
        background,
        swapped: background.is_some(),
        scene: Scene::default(),
        records_start: window.paint_index(),
        recording: None,
        current: None,
        spans: Vec::new(),
    };
    if state.swapped {
        window
            .content_mask_stack
            .push(ContentMask { bounds: region });
        mem::swap(&mut window.next_frame.scene, &mut state.scene);
        state.recording = Some(cx.begin_recording_dependencies());
    }
    let frame = frame_mut(window, id).unwrap();
    let marker = marker(id, frame);
    frame.paint = Some(state);
    window.fast_layers.painting = Some(marker);
    carry_paint_rows(window, id);
    check_hovers(window, id);
}

/// Asks for another frame if a row the layer of the list `id` keeps this
/// frame was painted by a hover that the frame's hit test, made after its
/// prepaint, finds changed: its hover was foretold from where the rows move
/// (see [`stale_rows`]), and something outside the list moved too. The row
/// is rendered again on the next frame, as a retained view whose hover
/// changes the same way is.
fn check_hovers(window: &mut Window, id: &GlobalElementId) {
    let Some(layer) = window.fast_layers.layers.get(id) else {
        return;
    };
    let Some(frame) = layer.rows.frame.as_ref() else {
        return;
    };
    // A row the list does not show can show a stale hover: it is checked
    // again before it shows.
    let rows = &layer.rows.rows;
    let changed = frame
        .carried
        .iter()
        .filter(|ix| frame.visible.contains(ix) && !frame.leaving.contains(ix))
        .any(|ix| {
            rows.get(ix)
                .is_some_and(|row| !window.hovers_unchanged(&row.hovers))
        });
    if changed {
        window.request_animation_frame();
    }
}

/// Paints a row of a list with `f`: into the list's layer if its prepaint
/// rendered the row for it, not at all if the layer keeps the row, into the
/// frame otherwise. `ix` is the row, or, for a uniform list, the next row it
/// rendered.
pub(crate) fn paint_row(
    window: &mut Window,
    cx: &mut App,
    ix: Option<usize>,
    f: impl FnOnce(&mut Window, &mut App),
) {
    if !LIST_LAYERS {
        return f(window, cx);
    }
    let Some(id) = window.fast_layers.painting.as_ref().map(|p| p.id.clone()) else {
        return f(window, cx);
    };
    let Some(layer) = window.fast_layers.layers.get_mut(&id) else {
        return f(window, cx);
    };
    let held = &layer.rows.rows;
    let Some(frame) = layer.rows.frame.as_mut() else {
        return f(window, cx);
    };
    let Some(paint) = frame.paint.as_ref() else {
        return f(window, cx);
    };
    if paint.current.is_some() {
        // A row of a list nested in a row being painted.
        return f(window, cx);
    }
    let swapped = paint.swapped;
    let row = match ix {
        Some(row) => row,
        None => {
            let Some(row) = frame.order.get(frame.next).copied() else {
                return f(window, cx);
            };
            frame.next += 1;
            row
        }
    };
    if !frame.slots.contains_key(&row) {
        if frame.mode == Mode::Extend && held.contains_key(&row) {
            // The layer keeps the row as it is.
            return;
        }
        if !swapped {
            return f(window, cx);
        }
        // Into the frame, around the layer's scene and painted region.
        let region = window.content_mask_stack.pop();
        swap_scenes(window, &id);
        f(window, cx);
        swap_scenes(window, &id);
        window.content_mask_stack.extend(region);
        return;
    }
    if !swapped {
        return f(window, cx);
    }
    let start = window.next_frame.scene.paint_operations.len();
    window.take_hover_reads();
    let hovers_start = window.retained_state.hover_dependencies.len();
    let paint_start = window.paint_index();
    set_current_row(window, &id, Some(row));
    {
        f(window, cx);
    }
    set_current_row(window, &id, None);
    let paint_end = window.paint_index();
    let end = window.next_frame.scene.paint_operations.len();
    window.take_hover_reads();
    let hovers = window.retained_state.hover_dependencies[hovers_start..].to_vec();
    if let Some(paint) = frame_mut(window, &id).and_then(|frame| frame.paint.as_mut()) {
        paint.spans.push(RowPaint {
            row,
            operations: start..end,
            paint: paint_start..paint_end,
            hovers,
        });
    }
}

fn swap_scenes(window: &mut Window, id: &GlobalElementId) {
    let Some(layer) = window.fast_layers.layers.get_mut(id) else {
        return;
    };
    if let Some(paint) = layer
        .rows
        .frame
        .as_mut()
        .and_then(|frame| frame.paint.as_mut())
    {
        mem::swap(&mut window.next_frame.scene, &mut paint.scene);
    }
}

fn set_current_row(window: &mut Window, id: &GlobalElementId, row: Option<usize>) {
    if let Some(paint) = frame_mut(window, id).and_then(|frame| frame.paint.as_mut()) {
        paint.current = row;
    }
}

/// Ends painting the rows of the list `id`: the rows painted into its layer
/// are recorded, those it drops forgotten, and the layer is composited.
pub(crate) fn end_paint_rows(window: &mut Window, cx: &mut App, id: Option<&GlobalElementId>) {
    if !LIST_LAYERS {
        return;
    }
    let Some(id) = id else {
        return;
    };
    if window.fast_layers.layers.is_empty() {
        return;
    }
    let Some(layer) = window.fast_layers.layers.get_mut(id) else {
        return;
    };
    let Some(mut frame) = layer.rows.frame.take() else {
        return;
    };
    let Some(mut paint) = frame.paint.take() else {
        return;
    };
    window.fast_layers.painting = None;
    let records = paint.records_start.clone()..window.paint_index();
    if frame.slots.is_empty() {
        match frame.mode {
            Mode::Extend => {
                let layer = window.fast_layers.layers.get_mut(id).unwrap();
                if layer.rows.rows.len() == frame.carried.len() {
                    // Nothing new: the layer's content stands.
                    count_extended_frame(0);
                    finish_records(window, id, &frame, records);
                    paint::composite_at(window, id, frame.translation);
                    return;
                }
                // Rows are dropped: the content changes.
                paint.background = paint::bake_background(window);
            }
            // No row to paint: the layer holds nothing.
            Mode::Repaint => {
                if let Some(layer) = window.fast_layers.layers.get_mut(id) {
                    layer.record = None;
                }
                clear_rows(window, id, &frame);
                return;
            }
        }
    }
    let Some(background) = paint.background else {
        // The rows were painted into the frame: so is what the layer held.
        let layer = window.fast_layers.layers.get_mut(id).unwrap();
        if let Some(record) = layer.record.take()
            && frame.mode == Mode::Extend
        {
            let carried: BTreeSet<usize> = frame.carried.iter().copied().collect();
            let kept: Vec<Rc<Scene>> = layer
                .rows
                .rows
                .iter()
                .filter(|(ix, _)| carried.contains(ix))
                .map(|(_, row)| row.part.scene.clone())
                .collect();
            drop(record);
            for scene in kept {
                paint::draw_into_frame(window, &scene.paint_operations, frame.translation);
            }
        }
        clear_rows(window, id, &frame);
        policy::defer_unbaked(window, id);
        return;
    };

    let paint_dependencies = paint
        .recording
        .take()
        .map(|recording| without_owner(window, cx.finish_recording_dependencies(recording).all))
        .unwrap_or_default();
    if paint.swapped {
        mem::swap(&mut window.next_frame.scene, &mut paint.scene);
        window.content_mask_stack.pop();
    }
    let rendered_rows = paint.spans.len();
    let rendered_operations = paint.scene.paint_operations.len();
    let painted = paint.scene;

    let scale_factor = window.scale_factor();
    let translation = frame.translation;
    let to_content = point(
        ScaledPixels(-translation.x.0),
        ScaledPixels(-translation.y.0),
    );
    let views = invalidate::content_views(window, &frame.prepaint_range);
    let viewport = window.snapped_content_mask().bounds;
    let mut row_prepaints = mem::take(&mut frame.row_prepaints);

    let layer = window.fast_layers.layers.get_mut(id).unwrap();
    let rows = &mut layer.rows;
    let for_hover = paint
        .spans
        .iter()
        .filter(|span| frame.stale.contains(&span.row))
        .count();
    match frame.mode {
        Mode::Repaint => rows.clear(),
        Mode::Extend => {
            rows.added_since_repaint += paint
                .spans
                .iter()
                .filter(|span| !rows.rows.contains_key(&span.row))
                .count();
            let carried: BTreeSet<usize> = frame.carried.iter().copied().collect();
            rows.rows.retain(|row, _| carried.contains(row));
            count_extended_frame(for_hover);
        }
    }
    let mut operations = painted.paint_operations;
    for span in paint.spans {
        let Some(slot) = frame.slots.get(&span.row) else {
            continue;
        };
        let slot = slot.scale(scale_factor);
        let slot = Bounds {
            origin: slot.origin + to_content,
            size: slot.size,
        };
        // Each row's operations are taken, in content space, once.
        let mut row_operations: Vec<PaintOperation> = operations[span.operations]
            .iter_mut()
            .map(|operation| mem::replace(operation, PaintOperation::EndLayer))
            .collect();
        for operation in &mut row_operations {
            match operation {
                PaintOperation::Primitive(primitive) => move_primitive(primitive, to_content),
                PaintOperation::StartLayer(bounds) => bounds.origin = bounds.origin + to_content,
                PaintOperation::EndLayer => {}
            }
        }
        let (tile_hashes, reach) = part_tile_hashes(&row_operations, paint::TILE_SIZE);
        let has_paths = row_operations
            .iter()
            .any(|operation| matches!(operation, PaintOperation::Primitive(Primitive::Path(_))));
        let mut scene = Scene::default();
        scene.paint_operations = row_operations;
        let (prepaint, hitboxes, layout_keys) =
            match row_prepaints.iter_mut().rev().find(|p| p.row == span.row) {
                Some(prepainted) => {
                    let range = &prepainted.range;
                    let inserted = &window.next_frame.hitboxes
                        [range.start.hitboxes_index..range.end.hitboxes_index];
                    let mut hitboxes = inserted.to_vec();
                    if prepainted.masks.len() == hitboxes.len() {
                        for (hitbox, mask) in hitboxes.iter_mut().zip(&prepainted.masks) {
                            hitbox.content_mask = *mask;
                        }
                    } else {
                        debug_assert!(false, "a hitbox inserted by a row went unnoted");
                    }
                    (
                        range.clone(),
                        hitboxes,
                        mem::take(&mut prepainted.layout_keys),
                    )
                }
                None => {
                    debug_assert!(
                        false,
                        "a row painted into a layer was not prepainted into it"
                    );
                    let end = frame.prepaint_range.end.clone();
                    (end.clone()..end, Vec::new(), Vec::new())
                }
            };
        let has_states = prepaint.start.accessed_element_states_index
            != prepaint.end.accessed_element_states_index
            || span.paint.start.accessed_element_states_index
                != span.paint.end.accessed_element_states_index;
        rows.rows.insert(
            span.row,
            Row {
                slot,
                part: LayerPart {
                    bounds: Some(reach.unwrap_or_default()),
                    scene: Rc::new(scene),
                },
                tile_hashes,
                has_paths,
                translation,
                hitboxes,
                hovers: span.hovers,
                has_states,
                layout_keys,
                prepaint,
                paint: span.paint,
                dropped: false,
            },
        );
    }
    rows.list = true;
    let visible_operations: usize = rows
        .rows
        .range(frame.visible.clone())
        .map(|(_, row)| row.part.scene.paint_operations.len())
        .sum();
    let work = (rendered_rows as f32 / frame.visible.len().max(1) as f32)
        .max(rendered_operations as f32 / visible_operations.max(1) as f32);

    // The content: the rows in order.
    let content = LayerContent::from_parts(rows.rows.values().map(|row| row.part.clone()));
    let mut region = Bounds {
        origin: viewport.origin + to_content,
        size: viewport.size,
    };
    for row in rows.rows.values() {
        region = region.union(&row.slot);
    }
    let hashes = combine_tile_hashes(
        rows.rows.values().map(|row| row.tile_hashes.as_slice()),
        paint::TILE_SIZE,
        region,
    );
    let has_paths = rows.rows.values().any(|row| row.has_paths);

    let old = layer.record.take();
    let generation = layer.next_generation();
    let dirty = match &old {
        Some(old) if old.background == background => dirty_tiles(&old.tile_hashes, &hashes),
        _ => paint::all_tiles(&hashes),
    };
    let dependencies = match (&old, frame.mode) {
        (Some(old), Mode::Extend) => old
            .dependencies
            .union(&frame.dependencies)
            .union(&paint_dependencies),
        _ => frame.dependencies.union(&paint_dependencies),
    };
    let rows = &layer.rows;
    let painted_region = rows.rows.values().fold(frame.viewport, |region, row| {
        let slot = Bounds {
            origin: row.slot.origin - to_content,
            size: row.slot.size,
        };
        region.union(&Bounds {
            origin: point(
                px(slot.origin.x.0 / scale_factor),
                px(slot.origin.y.0 / scale_factor),
            ),
            size: crate::size(
                px(slot.size.width.0 / scale_factor),
                px(slot.size.height.0 / scale_factor),
            ),
        })
    });
    let dirtied = dirty.len();
    layer.record = Some(LayerRecord {
        content,
        generation,
        painted_region,
        viewport: frame.viewport,
        scroll_offset: frame.scroll_offset,
        translation,
        prepaint_range: frame.prepaint_range.clone(),
        paint_range: records.clone(),
        tile_hashes: hashes,
        dirty_tiles: dirty,
        background,
        hovers: Rc::from([]),
        dependencies,
        views,
        has_paths,
        paths: Rc::from([]),
        view_layouts: Rc::default(),
    });
    finish_records(window, id, &frame, records);
    if frame.mode == Mode::Repaint && !has_paths {
        window
            .layout_engine
            .as_mut()
            .unwrap()
            .retention
            .stats
            .layer_frames_repainted += 1;
    }
    policy::note_work(window, id, work);
    paint::insert_layer(window, id, translation, dirtied);
}

/// Notes, for the layer of the list `id`, where the records of its rows lie
/// in the frame being drawn, whose `frame` drew them, and how far the
/// positions they hold lag behind.
fn finish_records(
    window: &mut Window,
    id: &GlobalElementId,
    frame: &RowsFrame,
    records: Range<PaintIndex>,
) {
    let frame_number = window.fast_layers.frame;
    let scale_factor = window.scale_factor();
    let Some(layer) = window.fast_layers.layers.get_mut(id) else {
        return;
    };
    let translation = frame.translation;
    if let Some(record) = layer.record.as_mut() {
        record.prepaint_range = frame.prepaint_range.clone();
        record.paint_range = records;
    }
    let stale = layer
        .rows
        .rows
        .values()
        .find(|row| row.translation != translation)
        .map_or(Point::default(), |row| row.delta(translation, scale_factor));
    let input = &mut layer.input;
    input.ranges_frame = Some(frame_number);
    input.viewport = frame.viewport;
    input.stale = stale;
    let rows = &mut layer.rows;
    rows.last_translation = Some(translation);
    rows.visible = Some((frame_number, frame.visible.clone()));
    for ix in &frame.leaving {
        if let Some(row) = rows.rows.get_mut(ix) {
            row.dropped = true;
        }
    }
}

/// Forgets the rows of the layer of the list `id`, whose content is gone,
/// after `frame` showed them without the layer.
fn clear_rows(window: &mut Window, id: &GlobalElementId, frame: &RowsFrame) {
    let frame_number = window.fast_layers.frame;
    if let Some(layer) = window.fast_layers.layers.get_mut(id) {
        layer.rows.clear();
        layer.rows.visible = Some((frame_number, frame.visible.clone()));
    }
}