frus-shell 0.4.0

frus — the platform layer: window + event loop (Milestone 0)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
//! The generic driver: implements [`winit::application::ApplicationHandler`] for
//! any [`Application`].
//!
//! The framework owns the window, the renderer, the [`Runtime`] — the retained
//! interaction state: hover, focus, scroll, editing, animations — input routing by
//! hit test, dragging (scrollbars, selection, handles, the back gesture) and the
//! animation clock. The application supplies only `update`, `view` and friends.

use std::collections::HashMap;
use std::sync::Arc;

use web_time::Instant;

use frus_gpu::Renderer;
use frus_widgets::{
    build_deferred, build_ui, collect_ids, find_by_key, find_path, find_widget, focus_changes,
    nearest_reorder_slot, reflow_reorder_cards, reflow_reorder_columns, reorder_drop_after,
    reorder_siblings, reorderable_owners, subtree_ids, Accessibility, Brightness, Color,
    Cursor as UiCursor, Edit, EditKind, EditSnapshot, FocusDirection, Insets, Key, KeyResponse,
    KeyStroke, MediaQuery, Point, Primitive, Rect, RegionPoint, RegionSelection, ReorderAxis,
    Runtime, Scene, ScrollTo, Scrollable, SheetTo, ShortcutKey, Size, TextStop, Theme, ToolbarMark,
    Ui, VelocityEstimate, VelocityTracker, Widget, WidgetId, WindowInsets,
};
use winit::application::ApplicationHandler;
use winit::event::{
    ElementState, MouseButton, MouseScrollDelta, StartCause, TouchPhase, WindowEvent,
};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy};
use winit::keyboard::{Key as WinitKey, KeyCode, NamedKey, PhysicalKey};
use winit::window::{CursorIcon, Window, WindowId};

use crate::application::{Application, Lifecycle};

/// Everything the platform reports about its user, in one walk.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct PlatformSettings {
    /// The system's *Font size* slider. `1.0` is normal; Android's own slider reaches
    /// 1.3, and the accessibility sizes go further.
    pub text_scaler: f32,
    /// Whether the system is currently showing a dark interface.
    pub brightness: Brightness,
    /// The accessibility settings, as far as they could be read.
    pub accessibility: Accessibility,
    /// **The reader's preferred languages**, best first, as the platform reports them.
    ///
    /// Empty where the platform said nothing — which is a real answer and not a failure:
    /// the resolution treats it as *no preference* and hands back the application's own
    /// first choice, exactly as the reference does (`app.dart:153`).
    pub locales: Vec<frus_widgets::Locale>,
}

impl Default for PlatformSettings {
    /// What a platform that reports nothing looks like: a user who has changed nothing.
    fn default() -> Self {
        Self {
            text_scaler: 1.0,
            brightness: Brightness::Light,
            accessibility: Accessibility::NONE,
            locales: Vec::new(),
        }
    }
}
use crate::gesture::{PointerEvent, PointerKind, PressRecognizer};

/// What a key asks of the clipboard.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ClipCommand {
    Copy,
    Cut,
    Paste,
}

/// The clipboard command a key press means, if any: Ctrl+C/X/V, and the Copy, Cut and
/// Paste keys a keyboard may have for them (milestone 509).
///
/// Both halves of the key are asked. A desktop keyboard's Copy key arrives as a named
/// logical key; Android's arrives by **physical code only** — winit gives it no logical
/// key at all — so a check of the logical key alone would ignore it on the one platform
/// that has it as a keycode of its own.
fn clipboard_command(logical: &WinitKey, physical: PhysicalKey, ctrl: bool) -> Option<ClipCommand> {
    match logical {
        WinitKey::Named(NamedKey::Copy) => return Some(ClipCommand::Copy),
        WinitKey::Named(NamedKey::Cut) => return Some(ClipCommand::Cut),
        WinitKey::Named(NamedKey::Paste) => return Some(ClipCommand::Paste),
        WinitKey::Character(c) if ctrl => {
            if c.eq_ignore_ascii_case("c") {
                return Some(ClipCommand::Copy);
            }
            if c.eq_ignore_ascii_case("x") {
                return Some(ClipCommand::Cut);
            }
            if c.eq_ignore_ascii_case("v") {
                return Some(ClipCommand::Paste);
            }
        }
        _ => {}
    }
    match physical {
        PhysicalKey::Code(KeyCode::Copy) => Some(ClipCommand::Copy),
        PhysicalKey::Code(KeyCode::Cut) => Some(ClipCommand::Cut),
        PhysicalKey::Code(KeyCode::Paste) => Some(ClipCommand::Paste),
        _ => None,
    }
}

/// Whether a key press asks for the **selection bar**: the context-menu key, which a
/// keyboard may have between Alt Gr and Ctrl, or Shift+F10, which every desktop toolkit reads
/// the same way (milestone 568). What lets someone with no pointer — and so no hold or
/// right-click — open it.
fn opens_selection_bar(logical: &WinitKey, shift: bool) -> bool {
    match logical {
        WinitKey::Named(NamedKey::ContextMenu) => true,
        WinitKey::Named(NamedKey::F10) => shift,
        _ => false,
    }
}

/// Whether `widget` takes typing, and so wants the software keyboard while it has focus.
///
/// Asked of the widget (milestone 510). It used to be asked of a **caret hit test** at
/// the corner of a field one pixel wide, and a field with a clickable suffix — the ×
/// a field shows once it holds text — answered that no caret goes there, since that
/// pixel is its clear button. So the first letter typed into such a field closed the
/// keyboard and ended its composition, and the keyboard's next update was written
/// beside the first: `F`, then `FFr`.
///
/// A field that can only be **read** — a read-only one, a selectable paragraph — is a text field
/// with a caret and a selection and no use for a keyboard, which would slide up over the very
/// words its reader has come to select.
#[cfg(any(android, test))]
fn wants_keyboard<M>(widget: &dyn Widget<M>) -> bool {
    is_text_field(widget) && widget.focusable() && widget.takes_typing()
}

/// Whether `widget` is a **text field**: what takes the left and right arrows for its caret
/// instead of leaving them to focus navigation.
///
/// Asked of the widget, and not of a caret hit test at the corner of a field one pixel wide —
/// which is how this was decided until milestone 570. A field that holds text shows a clear
/// button, and the button covers that pixel, so the probe answered "no caret goes here" and the
/// **left and right arrows moved the focus to the next control** instead of the caret: in any
/// field with something in it, on every platform, and never in an empty one. It is the same
/// trap milestone 510 had already got the keyboard out of, in the one place it was not looked for.
fn is_text_field<M>(widget: &dyn Widget<M>) -> bool {
    widget.text_value().is_some()
}

/// How far apart two presses may be and still be a double click on words in a selection area, in
/// logical pixels.
const REGION_DOUBLE_CLICK_SLOP: f32 = 8.0;

/// How long a first tap waits for a second one to make a double tap: the reference's
/// `kDoubleTapTimeout`.
const DOUBLE_TAP_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(300);

/// How far apart two taps may be and still be a double tap, in logical pixels: the reference's
/// `kDoubleTapSlop`.
const DOUBLE_TAP_SLOP: f32 = 100.0;

/// The fastest a drag's end velocity is reported, in logical pixels per second: the
/// reference's `kMaxFlingVelocity`.
const MAX_PAN_VELOCITY: f32 = 8000.0;

/// A first tap on something that also takes a double tap, waiting to see whether a second
/// one follows (milestone 581).
struct PendingTap<M> {
    /// What was tapped.
    id: WidgetId,
    /// When it was tapped.
    at: Instant,
    /// Where it was tapped.
    position: Point,
    /// The tap's own message, sent if no second tap comes in time.
    single: Option<M>,
}

/// Whether a field's **Select all**, pressed on its bar, puts the bar away: on macOS, Linux
/// and Windows it does, its work done; on Android, iOS and Fuchsia the bar stays, offering
/// what can be done with everything selected (`editable_text.dart:2914`, milestone 625).
///
/// The **system's** platform decides, not the theme's, as in the reference: it is how the
/// system's own menus behave, not how the application looks.
fn select_all_hides_bar(platform: frus_widgets::TargetPlatform) -> bool {
    platform.is_desktop()
}

/// The clipboard: `arboard` on the desktop platforms, the platform's own on Android
/// (`ClipboardManager`, through the bundled dex — milestone 509, #22), the browser's
/// asynchronous Clipboard API on the Web (milestone 526, #17), and a no-op on iOS
/// (`arboard` does not compile there and is not a dependency).
/// The stub is gated on what is *not* implemented rather than on a list of the other
/// platforms: that is what makes adding a target never leave this type undefined.
/// One uniform API, so the driver's body stays free of `cfg`.
///
/// **A paste is asked for, and answered.** The Web's read is a promise — it may prompt
/// the reader, be refused, or take its time — and the other platforms' reads are
/// immediate. So `Clipboard::paste` names the field that asked and either answers at
/// once or answers later through `Clipboard::take_answered`, which the driver drains
/// every frame; both answers land through the same rule, `Pasted::lands`. Nothing on a
/// synchronous platform pretends to wait, and no widget knows which kind it is on: the
/// shell, not the field, holds the clipboard.
mod clip {
    use frus_widgets::WidgetId;

    /// What the clipboard answered to a paste: its text, and the field that asked.
    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct Pasted {
        pub into: WidgetId,
        pub text: String,
    }

    impl Pasted {
        /// Whether this paste goes into its field: only while that field still has the
        /// focus — on the Web the answer comes back after the key press, and the reader
        /// may have moved on to another field, or to none — and only when there is text.
        /// An empty clipboard is nothing to paste, not an instruction to delete the
        /// selection; the browser answers a clipboard holding no text with `""`.
        pub fn lands(&self, focused: Option<WidgetId>) -> bool {
            focused == Some(self.into) && !self.text.is_empty()
        }
    }

    /// The platforms whose read is immediate answer a paste on the spot.
    #[cfg(not(web))]
    impl Clipboard {
        pub fn paste(
            &mut self,
            into: WidgetId,
            _wake: Option<&std::sync::Arc<winit::window::Window>>,
        ) -> Option<Pasted> {
            self.get_text().map(|text| Pasted { into, text })
        }
        pub fn take_answered(&mut self) -> Option<Pasted> {
            None
        }
    }

    #[cfg(desktop)]
    pub enum Clipboard {
        /// The system's, through `arboard`.
        System(Option<arboard::Clipboard>),
        /// One of its own, in memory: what a shell with no window holds (the test
        /// driver's). The system's is shared by everything on the machine and, on macOS,
        /// is not to be touched from several threads at once — and tests run on several.
        /// Only there, so a build without it has no variant nothing makes.
        #[cfg(any(test, feature = "testing"))]
        Memory(Option<String>),
    }

    #[cfg(desktop)]
    impl Clipboard {
        pub fn new() -> Self {
            Self::System(arboard::Clipboard::new().ok())
        }
        /// Only a shell with no window — the test driver — holds one.
        #[cfg(any(test, feature = "testing"))]
        pub fn in_memory() -> Self {
            Self::Memory(None)
        }
        pub fn get_text(&mut self) -> Option<String> {
            match self {
                Self::System(system) => system.as_mut().and_then(|c| c.get_text().ok()),
                #[cfg(any(test, feature = "testing"))]
                Self::Memory(text) => text.clone(),
            }
        }
        pub fn has_text(&mut self) -> bool {
            self.get_text().is_some_and(|text| !text.is_empty())
        }
        pub fn set_text(&mut self, text: String) {
            match self {
                Self::System(system) => {
                    if let Some(c) = system.as_mut() {
                        let _ = c.set_text(text);
                    }
                }
                #[cfg(any(test, feature = "testing"))]
                Self::Memory(held) => *held = Some(text),
            }
        }
    }

    /// Elsewhere a shell with no window keeps the platform's clipboard: no test runs there.
    #[cfg(all(not(desktop), any(test, feature = "testing")))]
    impl Clipboard {
        pub fn in_memory() -> Self {
            Self::new()
        }
    }

    #[cfg(android)]
    pub struct Clipboard;

    #[cfg(android)]
    impl Clipboard {
        pub fn new() -> Self {
            Self
        }
        pub fn get_text(&mut self) -> Option<String> {
            crate::android_clipboard::get_text()
        }
        pub fn has_text(&mut self) -> bool {
            self.get_text().is_some_and(|text| !text.is_empty())
        }
        pub fn set_text(&mut self, text: String) {
            crate::android_clipboard::set_text(&text);
        }
    }

    /// The pastes a clipboard has answered later and the driver has not taken yet, in the
    /// order the answers came — which need not be the order they were asked in.
    ///
    /// Held by the Web's clipboard; kept out of its `cfg` so that it is tested natively.
    #[cfg(any(web, test))]
    #[derive(Default)]
    pub struct Answers(std::rc::Rc<std::cell::RefCell<std::collections::VecDeque<Pasted>>>);

    #[cfg(any(web, test))]
    impl Answers {
        /// What answers a paste into `into` once the text is there: it queues the paste,
        /// then calls `wake`, so that a frame comes to take it.
        pub fn answer_for(
            &self,
            into: WidgetId,
            wake: impl FnOnce() + 'static,
        ) -> impl FnOnce(String) + 'static {
            let queue = std::rc::Rc::clone(&self.0);
            move |text| {
                queue.borrow_mut().push_back(Pasted { into, text });
                wake();
            }
        }

        /// The oldest answer not taken yet.
        pub fn take(&self) -> Option<Pasted> {
            self.0.borrow_mut().pop_front()
        }
    }

    /// The Web: a read is started by the key press and answered by the browser later,
    /// into a queue the driver drains; the window is asked for a frame so that it does.
    #[cfg(web)]
    pub struct Clipboard {
        answered: Answers,
    }

    #[cfg(web)]
    impl Clipboard {
        pub fn new() -> Self {
            Self {
                answered: Answers::default(),
            }
        }
        pub fn set_text(&mut self, text: String) {
            crate::web_clipboard::set_text(&text);
        }
        /// The browser's clipboard cannot be read without asking, and asking is a promise
        /// that may prompt the reader: so a bar opening cannot know, and offers Paste.
        pub fn has_text(&mut self) -> bool {
            true
        }
        pub fn paste(
            &mut self,
            into: WidgetId,
            wake: Option<&std::sync::Arc<winit::window::Window>>,
        ) -> Option<Pasted> {
            let wake = wake.cloned();
            crate::web_clipboard::get_text(self.answered.answer_for(into, move || {
                if let Some(window) = wake {
                    window.request_redraw();
                }
            }));
            None
        }
        pub fn take_answered(&mut self) -> Option<Pasted> {
            self.answered.take()
        }
    }

    #[cfg(not(any(desktop, android, web)))]
    pub struct Clipboard;

    #[cfg(not(any(desktop, android, web)))]
    impl Clipboard {
        pub fn new() -> Self {
            Self
        }
        pub fn get_text(&mut self) -> Option<String> {
            None
        }
        pub fn has_text(&mut self) -> bool {
            false
        }
        pub fn set_text(&mut self, _text: String) {}
    }
}

/// Browser timers, for the Web: the counterpart of the native subscriptions'
/// `recv_timeout` thread. A **retained** `setInterval`, whose **drop** calls
/// `clearInterval` and releases the closure. That is how an `every` subscription
/// ticks on the Web, where there is no background thread.
#[cfg(web)]
mod web_timer {
    use wasm_bindgen::prelude::Closure;
    use wasm_bindgen::JsCast;

    /// An active `setInterval`: as long as this handle lives the callback is called
    /// back every `ms`; dropping it cancels that.
    pub(crate) struct Interval {
        id: i32,
        // The JS closure must live as long as the interval does.
        _closure: Closure<dyn FnMut()>,
    }

    impl Interval {
        /// Schedules `f` every `ms` milliseconds, 1 ms at the least. `None` when there
        /// is no window, that is, in a DOM-less context.
        pub(crate) fn new(ms: i32, f: impl FnMut() + 'static) -> Option<Self> {
            let window = web_sys::window()?;
            let closure = Closure::wrap(Box::new(f) as Box<dyn FnMut()>);
            let id = window
                .set_interval_with_callback_and_timeout_and_arguments_0(
                    closure.as_ref().unchecked_ref(),
                    ms.max(1),
                )
                .ok()?;
            Some(Self {
                id,
                _closure: closure,
            })
        }
    }

    impl Drop for Interval {
        fn drop(&mut self) {
            if let Some(window) = web_sys::window() {
                window.clear_interval_with_handle(self.id);
            }
        }
    }

    /// Calls `f` once, after `ms` milliseconds — the Web half of
    /// [`Command::after`](crate::Command::after).
    ///
    /// There is no handle to keep, and that is the point. `Closure::once_into_js`
    /// hands ownership of the closure to the JS side, which frees it after the call.
    /// A `Closure` we owned instead would have to be either leaked — one leak per
    /// timer — or dropped here, which would free the callback out from under a
    /// `setTimeout` that has not fired yet.
    pub(crate) fn after(ms: i32, f: impl FnOnce() + 'static) {
        let Some(window) = web_sys::window() else {
            return;
        };
        let callback = wasm_bindgen::closure::Closure::once_into_js(f);
        let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(
            callback.unchecked_ref(),
            ms.max(0),
        );
    }
}

/// An active subscription's cancellation handle: **dropping** it stops the
/// subscription.
/// - Native: the executor task's handle — dropping it cancels the task.
/// - Web: a retained `setInterval` (`None` when installing it failed).
#[cfg(not(web))]
type SubHandle = async_executor::Task<()>;
#[cfg(web)]
type SubHandle = Option<web_timer::Interval>;

/// Scroll speed, in pixels per wheel notch.
const SCROLL_SPEED: f32 = 40.0;

/// The distance a **finger** must travel before the framework is confident the
/// gesture is a drag rather than a tap, in logical px.
///
/// 18 px is large for a screen measurement, and deliberately so: a thumb covers a
/// wide contact patch and rolls as it presses, so a smaller threshold turns taps
/// near the edge of a button into aborted drags. It is the value the mature
/// toolkits settled on after starting at 8 and hearing that targets were too hard
/// to hit.
const TOUCH_SLOP: f32 = 18.0;

/// The same threshold for a **precise** pointer — a mouse or a trackpad. It knows
/// exactly where it is, so almost any movement is intentional.
const PRECISE_SLOP: f32 = 1.0;

/// The velocity a release should be flung with, per axis — zero on an axis the
/// gesture did not really travel along.
///
/// Speed alone is not a fling. A finger that twitches fast over three pixels
/// produces a large velocity and no intent; requiring the gesture to have
/// **covered ground** as well is what separates the two, and the distance that says
/// "this was a drag" is the same `slop` that started it.
///
/// The gate is per axis because a scroll is two independent axes: a swipe running
/// down the screen must not fling sideways on the little horizontal wobble a thumb
/// always adds.
fn fling_velocity(estimate: VelocityEstimate, slop: f32) -> (f32, f32) {
    let gate = |velocity: f32, travelled: f32| {
        if travelled.abs() > slop {
            velocity
        } else {
            0.0
        }
    };
    (
        gate(estimate.velocity.x, estimate.offset.0),
        gate(estimate.velocity.y, estimate.offset.1),
    )
}

/// The elastic overshoot allowed past the scroll bounds, in px — the rubber band.
const SCROLL_OVER: f32 = 48.0;

/// The minimum velocity, in px/s, on releasing a pan that starts a fling.
const PAN_FLING_MIN: f32 = 80.0;

/// The width, in physical px, of the edge zone that arms the back gesture.
const BACK_EDGE: f32 = 24.0;

/// The **drag-and-drop** (reorder) preview — paint geometry only. The shadow's
/// *colour* comes from the theme (`theme.scheme.shadow`, as `Button` does); only the
/// geometry lives here, as named constants rather than magic numbers scattered about.
mod drag_preview {
    /// The vertical offset of the ghost's drop shadow, in px.
    pub const SHADOW_OFFSET_Y: f32 = 4.0;
    /// The blur of the ghost's drop shadow, in px.
    pub const SHADOW_BLUR: f32 = 12.0;
    /// The opacity of the ghost's shadow.
    pub const SHADOW_ALPHA: f32 = 0.28;
    /// The opacity of the ghost's `primary` border.
    pub const BORDER_ALPHA: f32 = 0.9;
    /// The thickness of the ghost's `primary` border, in px.
    pub const BORDER_WIDTH: f32 = 1.5;
    /// A slight vertical lift of the ghost during a **horizontal** drag, for columns.
    pub const LIFT_Y: f32 = -2.0;
    /// The thickness of the **insertion line** in the vertical preview, in px.
    pub const INSERT_THICKNESS: f32 = 3.0;
}

/// Whether a frame builds the view again rather than repainting the tree it already has:
/// when something asked for it (`dirty`), while the application's own animations are
/// moving **and in the frame they stop in**, or for a reason of the frame's own
/// (`otherwise`: no tree yet, a switcher in flight).
///
/// The frame they stop in, because the tick that ends a transition has changed the state
/// — a push's page left behind is gone — and reports nothing moving. Without it the tree
/// hit-tested from then on is the transition's last, the page left behind still in it
/// under the finger (milestone 531).
fn frame_needs_build(dirty: bool, animating: bool, was_animating: bool, otherwise: bool) -> bool {
    dirty || animating || was_animating || otherwise
}

/// What a press is still a candidate for once it has chosen its drag: the long press a
/// widget under the finger asks for, and the item it would lift on a hold.
///
/// A long press only while the press was not captured by a drag — a scrollbar, a handle,
/// a selection; a touch scroll that has not moved yet stays a candidate. An item that
/// lifts on a hold is a candidate under a scroll too: the scroll keeps the gesture for
/// now, and the deadline decides, since a finger that stays put was never scrolling.
fn hold_candidates<Msg: Clone>(
    drag: Option<&Drag>,
    ui: Option<&frus_widgets::Ui<Msg>>,
    tree: Option<&dyn frus_widgets::Widget<Msg>>,
    at: Point,
) -> (Option<Msg>, Option<frus_widgets::DragSource>) {
    // A back gesture owns its pointer from the press that starts it, as the reference's
    // pop gesture does: nothing on either page takes a finger that is taking a page away
    // (milestone 531). The page below is not even in the frame yet when the press lands —
    // what is under the finger is whatever the frame on screen holds.
    if matches!(drag, Some(Drag::Back { .. })) {
        return (None, None);
    }
    let Some(ui) = ui else {
        return (None, None);
    };
    // A drag that has not moved yet may still be a hold: a scroll's, or a detector's that
    // also takes a long press (milestone 582, seen on the phone).
    let free = matches!(
        drag,
        None | Some(Drag::Scroll { moved: false, .. }) | Some(Drag::Gesture { moved: false, .. })
    );
    let long_press = if free { ui.long_press_at(at) } else { None };
    let lift = ui.drag_source_at(at).filter(|source| {
        tree.and_then(|tree| find_widget(tree, source.id))
            .is_some_and(|widget| widget.drag_needs_long_press())
    });
    (long_press, lift)
}

/// The drag a press is left with when its hold's deadline fires, from the drag it had
/// and what the press found to lift.
///
/// A pending touch scroll no longer has any reason to exist — unless the hold was the
/// lift of an item or of a row, in which case the scroll hands the gesture over and what
/// was held is already up: `moved` is true because the hold *was* the threshold, and
/// asking for a movement as well would mean a row that was held and then carried
/// straight out of the list never engaged at all.
fn drag_after_hold(
    drag: Option<Drag>,
    lift: Option<frus_widgets::DragSource>,
    reorder: Option<(WidgetId, usize, Point)>,
    cursor: Point,
) -> Option<Drag> {
    // Never a back gesture's: the hold was not what that finger was doing, and taking the
    // drag from it would leave the application's gesture open with nothing to end it.
    if let Some(Drag::Back { start_x }) = drag {
        return Some(Drag::Back { start_x });
    }
    if let Some(source) = lift {
        Some(Drag::Item {
            source,
            start: cursor,
            moved: true,
            over: None,
        })
    } else if let Some((id, from, start)) = reorder {
        Some(Drag::Reorder {
            id,
            from,
            start,
            moved: true,
            carried: None,
        })
    } else {
        None
    }
}

/// A drag currently under way with the mouse.
enum Drag {
    /// A scrollbar's thumb.
    Scrollbar {
        id: WidgetId,
        vertical: bool,
        grab: f32,
        track_start: f32,
        track_len: f32,
        thumb_len: f32,
        max: f32,
        /// Whether this axis numbers its offsets from the far end, in which case the
        /// thumb's position along the track reads backwards.
        reverse: bool,
    },
    /// A selection dragged out over the texts of a
    /// [`SelectionArea`](frus_widgets::SelectionArea): it may leave the text it began in, and
    /// never leaves the area.
    RegionSelect { area: WidgetId },
    /// A handle of a selection area's touch selection, held (milestone 577): it carries its
    /// end of the selection to the text under the finger, the other end staying put. `grab` is
    /// the offset from the finger to the text position the handle stands for.
    RegionHandle {
        area: WidgetId,
        handle: crate::selection::Handle,
        grab: Point,
    },
    /// A text selection inside a field, with its bounds, for placement.
    TextSelect {
        id: WidgetId,
        rect: frus_widgets::Rect,
    },
    /// A **selection handle**, held (milestone 511). `grab` is the offset from the finger
    /// to the text position the handle stands for, so the selection follows the handle
    /// rather than jumping to the fingertip the moment it moves.
    SelectionHandle {
        id: WidgetId,
        rect: frus_widgets::Rect,
        handle: crate::selection::Handle,
        grab: Point,
    },
    /// A draggable widget — a slider or a handle — dragged along its horizontal axis.
    /// `last_x` is the pointer's last abscissa, so the **delta** can be delivered to
    /// the handles that accumulate, such as a column resize.
    Widget {
        id: WidgetId,
        rect: frus_widgets::Rect,
        last_x: f32,
        /// Where the press landed, and the widget's track as it stood then: a slide that
        /// moves the value from where it was measures from both (milestone 650).
        press_x: f32,
        track: frus_widgets::DragTrack,
        /// Whether the press started anything: a slider that only takes a slide on its
        /// thumb, pressed elsewhere, takes none of the gesture.
        active: bool,
        /// On a track with two thumbs, the one the press took — `None` until a press on
        /// both has moved far enough to say which (milestone 651).
        thumb: Option<usize>,
    },
    /// Reordering a **column**: a header is grabbed (`id`, column `from`) and dropped
    /// onto another. `moved` tells a drag from a plain tap — which stays a sort —
    /// by the `TOUCH_SLOP` threshold measured from `start`.
    Reorder {
        id: WidgetId,
        from: usize,
        start: Point,
        moved: bool,
        /// What is carried and where: the row the grab moves and its box, taken from the
        /// frame the first time the drag is carried and moved with the content since, as a
        /// lifted item's box is. The frame knows a reorderable's box only while it shows, and
        /// only as much of it as shows — and carrying a row to an edge is exactly what
        /// scrolls it out of sight (milestone 527, seen on a phone).
        carried: Option<(WidgetId, Rect)>,
    },
    /// Panning an interactive viewport (`InteractiveViewer`): the pointer pushes the
    /// content. `last` is the previous position, for the delta; `moved` tells a real
    /// pan from a plain tap, by the `TOUCH_SLOP` threshold, so a click on a child can
    /// still get through. `viewport` bounds the pan to the frame. The release
    /// velocity comes from the shell's gesture tracker.
    Pan {
        id: WidgetId,
        last: Point,
        moved: bool,
        viewport: frus_widgets::Rect,
    },
    /// Scrolling a scrollable area with a finger. `moved` tells a real scroll from a
    /// plain tap, movement staying under the `TOUCH_SLOP` threshold.
    Scroll {
        id: WidgetId,
        last: Point,
        moved: bool,
        /// The speed inherited from a fling this press interrupted, per axis, in
        /// px/s — added to the release velocity so repeated swipes build momentum
        /// where the platform does that. Zero when the content was already still.
        carried: (f32, f32),
        /// A dismissible item under the finger, still in the running. Both gestures
        /// start the same way, so neither is chosen at the press: the first movement
        /// past the threshold decides by **direction**, and the loser never sees the
        /// gesture. Cleared once the scroll has won.
        dismiss: Option<frus_widgets::Dismissable>,
        /// A detector that takes a drag under the finger, still in the running, with the way
        /// it drags (milestone 582). Decided at the threshold like `dismiss`: by direction.
        pan: Option<(WidgetId, frus_widgets::PanAxis)>,
        /// The axis this gesture was **claimed by**, decided once at the threshold and
        /// held for the rest of the drag: `true` for vertical.
        ///
        /// A page that scrolls down must not drift sideways at the same time, and a
        /// finger never travels in a straight line. The reference settles this in its
        /// gesture arena — a vertical and a horizontal recogniser compete, the first
        /// past its own slop wins, the loser is out of the gesture entirely — and this
        /// is the same rule for an area that can go both ways. `None` until the
        /// threshold is crossed.
        axis: Option<bool>,
    },
    /// A drag on a [`GestureDetector`](frus_widgets::GestureDetector) (milestone 582). `start`
    /// is where the pointer went down, `last` where it was at the last update; `moved` tells a
    /// drag from a tap, by the slop, and the start is only reported once it is a drag.
    Gesture {
        id: WidgetId,
        axis: frus_widgets::PanAxis,
        start: Point,
        last: Point,
        moved: bool,
    },
    /// Swiping a [`frus_widgets::Dismissible`] item aside. `last` is the previous
    /// position, for the delta; the item is already past the threshold by the time this
    /// exists, since it is only ever reached by winning the direction test.
    Dismiss {
        item: frus_widgets::Dismissable,
        last: Point,
        /// `false` until the finger has passed the threshold — a press that never
        /// travels is still a tap on the row.
        moved: bool,
    },
    /// Carrying a [`frus_widgets::Draggable`] towards a [`frus_widgets::DragTarget`].
    /// `over` is the target the pointer is on now, when it would accept the payload —
    /// kept here so that entering and leaving one costs a comparison rather than a
    /// second hit test.
    Item {
        source: frus_widgets::DragSource,
        start: Point,
        /// `false` until the finger has passed the threshold: a press that never
        /// travels is a plain click on whatever is inside.
        moved: bool,
        over: Option<WidgetId>,
    },
    /// A [`frus_widgets::DraggableScrollableSheet`] moved by its panel, where nothing
    /// under the finger scrolls — its grabber, its header, a list too short to move
    /// (milestone 515). `available` is the height its shares are shares of, taken at
    /// the press: the panel may shrink to nothing under the finger, and still come back.
    Sheet {
        id: WidgetId,
        last: Point,
        /// `false` until the finger has passed the threshold: a press that never
        /// travels is a tap on whatever is in the sheet.
        moved: bool,
        available: f32,
    },
    /// The "back" gesture: the framework measures the finger's progress and velocity
    /// and passes them to the application, which decides on the navigation.
    Back { start_x: f32 },
}

/// The driver: an `event → frame` loop around an [`Application`].
/// Turns an application's `view` into a tree that is **ready to be read**.
///
/// The one way this shell builds a tree, and it exists because there were two. A
/// `ThemeBuilder` — and everything built on one, an `AppBar` included — has no children
/// until [`build_deferred`] has been over it, so every traversal of a tree that has not
/// been prepared finds nothing inside such a subtree and says nothing about it.
///
/// Both of the shell's build sites read the tree **before** the layout pass would have
/// prepared it: the frame's own path calls `collect_ids` on it for the mount and leave
/// bookkeeping, and the burst path hands it straight to `find_widget`. Neither of those is
/// a mistake to be spotted at a call site; they are why this is one function.
///
/// The surface must already be described — the reader's font setting reaches anything a
/// deferred subtree measures, and a build outside a surface measures at scale 1 while the
/// frame lays it out at whatever the reader asked for (milestone 408).
/// **The ambient answers an application gives**, read afresh every frame.
///
/// Both of these are settings rather than facts: a settings screen may turn scrollbars on
/// or change the reader's language while the application is running, and neither should
/// wait for a restart. Reading them once at start-up is the bug this shape avoids.
///
/// It is one function so that a test can drive it. The frame loop needs a window and an
/// event-loop proxy, so nothing in this repo can call the loop — which is exactly how a
/// setting that never reached production got shipped once already (milestone 408).
fn install_ambient<A: Application>(app: &A, preferred: &[frus_widgets::Locale]) {
    // **How the scrollables behave** (milestone 616): the application's behaviour, at the
    // root of the tree, under every `ScrollConfiguration` the view installs.
    frus_widgets::ScrollConfiguration::set_root(app.scroll_behavior());
    // **Which language the interface is in**, resolved from what the platform reports
    // against what the application has. Installed before the table, because an
    // application choosing its table by language reads it from here.
    frus_widgets::locale::install(app.resolved_locale(preferred));
    if let Some(table) = app.localizations() {
        frus_widgets::localizations::install(table);
    }
}

fn build_view<A: Application>(
    app: &A,
    theme: &Theme,
    runtime: &frus_widgets::Runtime,
) -> Box<dyn Widget<A::Message>> {
    debug_assert!(
        frus_widgets::MediaQuery::of().is_described(),
        "a view is being built with no surface described: install one first — milestone 416"
    );
    // Every state a component keeps is marked as reached while the tree is built, and
    // what a build did not reach is let go when the frame that laid it out is done.
    runtime.states.begin_build();
    let tree = app.view(theme);
    build_deferred(tree.as_ref(), theme, runtime);
    tree
}

/// Where the messages an effect produces on another thread are sent: the event loop's proxy,
/// or nowhere for a driver no event loop runs.
struct Mailbox<M: 'static>(Option<EventLoopProxy<M>>);

impl<M: 'static> Clone for Mailbox<M> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<M: 'static> Mailbox<M> {
    /// Sends `message` to the loop. An error when the loop has closed, or when there is
    /// none — either way nobody is left to tell.
    fn send_event(&self, message: M) -> Result<(), ()> {
        match &self.0 {
            Some(proxy) => proxy.send_event(message).map_err(|_| ()),
            None => Err(()),
        }
    }
}

/// The event handler that drives an [`Application`]: it owns the window, the renderer, the
/// last interface built and the runtime, and turns each event of the loop into messages,
/// frames and effects. [`run`](crate::run) and the other entry points build one; it is
/// exported for a platform layer that supplies its own loop, not for an application to
/// construct.
pub struct App<A: Application> {
    /// The application being driven: its state and logic.
    app: A,
    /// The channel that feeds back the messages effects produce, from their threads.
    proxy: Mailbox<A::Message>,
    window: Option<Arc<Window>>,
    renderer: Option<Renderer>,
    /// The renderer's GPU device was lost: a new renderer is made at the next frame's start
    /// (milestone 686).
    renderer_lost: bool,
    /// A renderer being initialised **asynchronously**, on the Web only: filled in by
    /// the `spawn_local` future and picked up on the first frame, the Web being unable
    /// to block on GPU init.
    #[cfg(web)]
    pending_renderer: std::rc::Rc<std::cell::RefCell<Option<Renderer>>>,
    /// What this side knows of the browser's history — see [`crate::history`].
    #[cfg(web)]
    history: crate::history::History,
    /// How the application's location is written in the address bar, and the document's base
    /// path, which the `Path` way of writing needs. Read once, at launch.
    #[cfg(web)]
    address: (crate::LocationStrategy, String),
    /// The window's accessibility bridge (AccessKit) — desktop only.
    #[cfg(desktop)]
    a11y: Option<crate::a11y::A11y>,
    /// The window's accessibility bridge, projected into the canvas's DOM — web only.
    #[cfg(web)]
    a11y: Option<crate::a11y_web::A11y>,
    /// The last interface built, used for hit testing, focus and scrolling.
    ui: Option<Ui<A::Message>>,
    /// The last widget tree built, used for keyboard and editing routing.
    tree: Option<Box<dyn Widget<A::Message>>>,
    /// The pointer's last known position, in **logical** pixels.
    cursor: Point,
    /// Where the pointer that **hovers** is: a mouse once it has moved, a finger only
    /// while it touches. Kept as a place and asked of each frame — see [`crate::hover`].
    hover: crate::hover::Hover,
    /// The screen's DPI scale factor (physical = logical × scale × density).
    scale: f32,
    /// The last **logical** size handed to the app, to detect breakpoints.
    last_size: Option<(f32, f32)>,
    /// State retained between frames: hover and focus, scroll, caret and selection.
    runtime: Runtime,
    /// **The theme on display and the fade toward the one now asked for** — the
    /// framework's, not the application's, since milestone 452. It resolves the
    /// application's themes against the platform's brightness and the reader's contrast
    /// setting once a frame, and crosses between two of them over time.
    themes: crate::theming::ThemeFade,
    /// Live-reload watching (development, `FRUS_WATCH=1`): relaunch on recompilation.
    reload: Option<crate::reload::ReloadWatcher>,
    /// The channel `frus run` listens on, when it started this application — see [`crate::dev`].
    #[cfg(any(desktop, android))]
    dev: Option<crate::dev::DevChannel>,
    /// Overflowing boxes already named on the console, so that a layout that does not
    /// fit is reported once and not sixty times a second.
    reported_overflows: std::cell::RefCell<std::collections::HashSet<u64>>,
    /// Is the runtime inspector on? Toggled by F12, in debug builds only.
    inspector: bool,
    /// A tree dump to print on the next inspected frame.
    inspector_dump: bool,
    /// What the keys of `frus run` turned on or asked for (milestone 668); see
    /// [`App::take_dev_commands`].
    debug: DebugAsks,
    /// The current keyboard modifiers.
    shift: bool,
    ctrl: bool,
    alt: bool,
    meta: bool,
    /// The remembered "goal" visual column for Up/Down/PgUp/PgDn: crossing shorter
    /// lines keeps the original column, the way an editor does. Cleared as soon as any
    /// other caret movement happens.
    goal_x: Option<f32>,
    /// Clipboard access: `arboard` on the desktop, the platform's on Android, the
    /// browser's on the web, nothing yet on iOS.
    clipboard: clip::Clipboard,
    /// Has the startup effect (`init`) already run? This keeps it from being replayed
    /// when the surface is recreated, as it is when Android returns from background.
    started: bool,
    /// The last frame's instant, for the animations' dt.
    last_frame: Option<Instant>,
    /// The **build** phase is dirty: the app's state, or the size, changed and the
    /// `view` must be rebuilt. The view is a pure function of `(state, theme, size)` —
    /// never of hover, scroll or focus, which live in the `Runtime` — so a frame that
    /// only animates an interaction merely **repaints** the retained tree (§1: "a hover
    /// touches paint and nothing else").
    build_dirty: bool,
    /// Whether the application's own animations were moving at the last frame. The frame
    /// they stop in is built once more: the tick that ends a transition has changed the
    /// state — the page it left is gone — and says it is no longer moving, so without it
    /// the tree hit-tested from then on is the transition's last (milestone 531).
    app_was_animating: bool,
    /// The mouse drag under way.
    drag: Option<Drag>,
    /// Was the pointer that started the drag under way a finger? A mouse is
    /// precise and needs almost no slop; a finger needs a lot.
    pointer_touch: bool,
    /// The pointer history of the drag under way, and the instant it began.
    ///
    /// One tracker for all of them: at most one drag is active at a time, and every
    /// kind of drag asks the same question on release — how fast was the finger
    /// going. Keeping it here rather than in each [`Drag`] variant means the
    /// gesture's clock and its history start together, in one place.
    gesture_velocity: VelocityTracker,
    /// The test driver's clock for the velocity tracker, when there is one: seconds of
    /// frames run, and when the gesture under way began on it. `None` in an application,
    /// which stamps samples with the wall clock. A driver's events are microseconds apart on
    /// the wall, and irregularly so on a loaded machine: a fling read from them came out at
    /// any speed, in either direction, and a test that let go of a scroll saw it thrown back
    /// to the top (milestone 584, seen in CI).
    gesture_clock: Option<(f32, f32)>,
    gesture_start: Instant,
    /// The pointer's **smoothed** abscissa during a reorder: it springs toward the
    /// real position, giving the columns' sliding a gentle inertia — the background
    /// catches up with the ghost, which sticks to the pointer.
    reorder_x: f32,
    /// The **smoothed** ordinate of the **insertion line** during a **vertical**
    /// reorder, that is, Kanban cards: it springs toward the **chosen** slot edge, the
    /// hovered half, so that the line and the gap *slide* between cards instead of
    /// jumping — the vertical counterpart of the horizontal `reorder_x` spring.
    reorder_y: f32,
    /// The last **announcement** pushed to the accessibility bridge's live region, for
    /// the screen reader. It persists as is: it is re-spoken only on a change, so the
    /// same text carried over every frame does not repeat. Desktop and web.
    #[cfg(any(desktop, web))]
    announce: String,
    /// The tap-or-long-press recogniser (gesture tier 1).
    press: PressRecognizer,
    /// The pressed target's long-press message, captured on the press.
    long_press_msg: Option<A::Message>,
    /// A **text field** pressed with a finger: a hold there selects the word under it
    /// (milestone 511), where on anything else it is the widget's long press.
    pending_word: Option<WidgetId>,
    /// A finger came down on words in a selection area: a hold there selects the word under it
    /// and opens the bar (milestone 576).
    pending_region_hold: bool,
    /// The focused field's caret blink (milestone 513).
    caret: crate::caret::CaretBlink,
    /// The form last shown to the platform's autofill service, as it was shown
    /// (milestone 512) — what a returned value is routed against, and what a value the
    /// service has not heard is told apart from.
    #[cfg(android)]
    autofill_reported: Vec<crate::autofill::AutofillField>,
    /// The field of that form the service was told has focus.
    #[cfg(android)]
    autofill_focus: Option<WidgetId>,
    /// The [`frus_widgets::AutofillGroup`] that form is, while it is on screen.
    #[cfg(android)]
    autofill_group: Option<WidgetId>,
    /// When the last **recorded** edit happened, for the pause that breaks a run of
    /// typing into two steps of undo. One field and not one per text field, because only
    /// the focused one is being typed into, and leaving a field ends its run anyway.
    last_edit_at: Option<Instant>,
    /// A [`frus_widgets::Draggable`] that asked to be lifted by a **hold**, waiting
    /// for the long-press deadline. Inside a scrollable this is the only way up: the
    /// plain drag belongs to the scroll, and a hold is the one signal it cannot claim.
    pending_lift: Option<frus_widgets::DragSource>,
    /// A **reorderable row** that asked to be lifted by a hold, waiting for the same
    /// deadline: `(the row, its index, where the finger landed)`.
    ///
    /// Its own field rather than a second use of `pending_lift`, because what the two
    /// become at the deadline is different — one carries a payload to a drop target, the
    /// other carries itself to a slot — but the reason they wait is the same, and it is
    /// the reason a list can still be scrolled.
    pending_reorder: Option<(WidgetId, usize, Point)>,
    /// The last click's instant, for double-click detection.
    last_click_time: Option<Instant>,
    /// When and where the last press began a selection in a selection area: a second one soon
    /// after and close by is a double click.
    last_region_click: Option<(Instant, Point)>,
    /// A first tap waiting to see whether it is half of a double tap (milestone 581).
    pending_tap: Option<PendingTap<A::Message>>,
    /// How many values the work components started had brought when this shell last looked
    /// (milestone 585).
    task_arrivals: u64,
    /// The regions the pointer is in, the innermost first, each with its box when it was
    /// last seen (milestone 583).
    entered: Vec<(WidgetId, Rect)>,
    /// Whether a button or a finger is down: a region hears moves only without one.
    pointer_held: bool,
    /// The widgets hearing the pointer's raw events that it went down in, each with its box
    /// then: they hear it until it lifts, wherever it goes (milestone 586).
    captured: Vec<(WidgetId, Rect)>,
    /// A counter for the keys of leaving events, which fade out.
    leaving_counter: u64,
    /// The running subscriptions: id → cancellation handle, dropping which stops it.
    running_subs: HashMap<u64, SubHandle>,
    /// Pending focus requests — the keys `Command::focus` produced — resolved against
    /// the **freshly built** tree on the next frame.
    pending_focus: Vec<u64>,
    /// Pending **scroll** requests — the `(key, ScrollTo)` pairs `Command::scroll`
    /// produced — resolved against the frame that follows, and dropped whether or not
    /// the key named anything (see `Command::scroll`).
    pending_scroll: Vec<(u64, ScrollTo)>,
    /// The requests of the frame in progress that the **previous** frame's registry
    /// could not place — a region that has only just appeared. Tried once more against
    /// the registry this frame builds, and then gone: a request gets one frame.
    retry_scroll: Vec<(u64, ScrollTo)>,
    /// Pending **sheet** requests — the `(key, SheetTo)` pairs `Command::sheet` produced —
    /// on the terms of the scroll requests above.
    pending_sheet: Vec<(u64, SheetTo)>,
    /// The sheet requests of the frame in progress that the previous frame's sheets did
    /// not name: tried once more against this frame's.
    retry_sheet: Vec<(u64, SheetTo)>,
    /// The **focus history** of triggers, for returning focus when an overlay closes:
    /// on every focus change the old one, if still present, is pushed; when focus
    /// **vanishes** because a menu or modal closed, we go back to the most recent
    /// entry that is still present.
    focus_history: Vec<WidgetId>,
    /// The previous frame's focus, to detect the transitions worth pushing.
    prev_focus: Option<WidgetId>,
    /// The focus the widgets were last told about (milestone 660); see
    /// `report_focus`.
    focus_reported: Option<WidgetId>,
    /// The widgets that took the focus on appearing, as of the last frame: one that is new
    /// this frame takes it (milestone 605).
    autofocused: std::collections::HashSet<WidgetId>,
    /// How smooth the frames are, when asked (milestone 609).
    frame_stats: crate::frame_stats::FrameStats,
    /// What the frame being drawn has cost so far, while frames are measured.
    frame_costs: crate::frame_stats::FrameCosts,
    /// The window is occluded, so rendering is suspended.
    occluded: bool,
    /// Cumulative elapsed time, in seconds, for the continuous animations.
    elapsed: f32,
    /// The last window insets handed to the app — padding plus keyboard — in logical px.
    last_insets: WindowInsets,
    /// Whether the window's title bar line is shared with the content, and what the content
    /// is told about it (milestone 640).
    #[cfg_attr(not(windows), allow(dead_code))]
    title_bar_on: bool,
    title_bar: Option<frus_widgets::TitleBar>,
    /// The application's icon, kept for the life of the program, to paint on the line.
    #[cfg_attr(not(windows), allow(dead_code))]
    window_icon: Option<&'static [u8]>,
    /// The soft keyboard has just grown, so the focused widget is brought back into view
    /// once the frame that lays out the shortened window is built: the keyboard covers
    /// the bottom of the screen, and a field under it is a field the reader cannot see
    /// while typing in it.
    reveal_after_keyboard: bool,
    /// What the **platform** last said about the person using it: the font-size slider,
    /// the night setting, the accessibility switches.
    ///
    /// Cached rather than read per frame, because reading it is a walk across the JNI
    /// boundary and the answer changes about once a year. It is refreshed when the
    /// surface appears — which on Android is also when it *reappears*, the activity being
    /// recreated on a font-scale or night change since no `configChanges` is declared —
    /// and on a theme change where the platform sends one.
    platform: PlatformSettings,
    /// The **keyboard-free** inset baseline, along with the physical size it was
    /// taken at — a rotation resets it: whatever bottom inset exceeds it is credited
    /// to the software keyboard.
    inset_baseline: Option<(Insets, (u32, u32))>,
    /// The Android activity's handle, used to query the insets, the keyboard and so on.
    /// The current **lifecycle** state, so the app is notified only on real
    /// **transitions**.
    lifecycle: Lifecycle,
    #[cfg(android)]
    android_app: Option<winit::platform::android::activity::AndroidApp>,
    /// Is the software keyboard being asked for? It follows the text fields' focus.
    #[cfg(android)]
    soft_input_shown: bool,
    /// The system bars as the platform was last told them, so that it is told only of a
    /// change (#46).
    #[cfg(android)]
    system_bars: Option<frus_widgets::SystemBars>,
}

impl<A: Application> App<A> {
    /// Creates the driver around an application and its message channel.
    pub fn new(app: A, proxy: EventLoopProxy<A::Message>) -> Self {
        Self::with_mailbox(app, Mailbox(Some(proxy)))
    }

    /// A driver with no event loop behind it, for a test that feeds it input and frames
    /// by hand: whatever an effect sends back goes nowhere. An event loop cannot be built
    /// on a machine with no display, which is where the continuous integration runs.
    #[cfg(any(test, feature = "testing"))]
    fn detached(app: A) -> Self {
        let mut shell = Self::with_mailbox(app, Mailbox(None));
        // A shell with no window is a test's: it keeps a clipboard of its own rather than
        // the machine's, which tests running side by side would share — and which macOS
        // does not let several threads touch at once (a test run aborted on it).
        shell.clipboard = clip::Clipboard::in_memory();
        shell
    }

    fn with_mailbox(app: A, proxy: Mailbox<A::Message>) -> Self {
        // The widget layer knows how to *want* an image over the network and has no way
        // to get one: no runtime, no socket, and no dependency on this crate, since the
        // dependency runs the other way. So the shell says how, on the way up, and the
        // widget layer only asks. Same shape as the image decoder a step earlier.
        #[cfg(feature = "net")]
        frus_widgets::set_image_fetcher(fetch_image_bytes);
        // And how to run the work a component starts (milestone 585): this shell's executor
        // natively, the browser on the Web.
        #[cfg(not(web))]
        frus_widgets::set_task_spawner(|task| crate::runtime::spawn(task).detach());
        #[cfg(web)]
        frus_widgets::set_task_spawner(wasm_bindgen_futures::spawn_local);
        Self {
            app,
            proxy,
            window: None,
            renderer: None,
            renderer_lost: false,
            #[cfg(web)]
            pending_renderer: std::rc::Rc::new(std::cell::RefCell::new(None)),
            #[cfg(web)]
            history: crate::history::History::new(),
            #[cfg(web)]
            address: (crate::LocationStrategy::Hash, "/".to_string()),
            #[cfg(desktop)]
            a11y: None,
            #[cfg(web)]
            a11y: None,
            ui: None,
            tree: None,
            cursor: Point::new(0.0, 0.0),
            hover: crate::hover::Hover::default(),
            scale: 1.0,
            last_size: None,
            runtime: Runtime::default(),
            themes: crate::theming::ThemeFade::default(),
            reload: crate::reload::ReloadWatcher::new(),
            #[cfg(any(desktop, android))]
            dev: None,
            reported_overflows: std::cell::RefCell::new(std::collections::HashSet::new()),
            inspector: false,
            inspector_dump: false,
            debug: DebugAsks::default(),
            shift: false,
            ctrl: false,
            alt: false,
            meta: false,
            goal_x: None,
            clipboard: clip::Clipboard::new(),
            started: false,
            last_frame: None,
            build_dirty: true,
            app_was_animating: false,
            drag: None,
            pointer_touch: false,
            gesture_velocity: VelocityTracker::default(),
            gesture_clock: None,
            gesture_start: Instant::now(),
            reorder_x: 0.0,
            reorder_y: 0.0,
            #[cfg(any(desktop, web))]
            announce: String::new(),
            press: PressRecognizer::new(),
            long_press_msg: None,
            pending_word: None,
            pending_region_hold: false,
            caret: crate::caret::CaretBlink::new(),
            #[cfg(android)]
            autofill_reported: Vec::new(),
            #[cfg(android)]
            autofill_focus: None,
            #[cfg(android)]
            autofill_group: None,
            last_edit_at: None,
            pending_lift: None,
            pending_reorder: None,
            last_click_time: None,
            last_region_click: None,
            pending_tap: None,
            task_arrivals: 0,
            entered: Vec::new(),
            pointer_held: false,
            captured: Vec::new(),
            leaving_counter: 0,
            running_subs: HashMap::new(),
            pending_focus: Vec::new(),
            pending_scroll: Vec::new(),
            retry_scroll: Vec::new(),
            pending_sheet: Vec::new(),
            retry_sheet: Vec::new(),
            focus_history: Vec::new(),
            prev_focus: None,
            focus_reported: None,
            autofocused: std::collections::HashSet::new(),
            frame_stats: crate::frame_stats::FrameStats::new(),
            frame_costs: crate::frame_stats::FrameCosts::default(),
            occluded: false,
            elapsed: 0.0,
            last_insets: WindowInsets::ZERO,
            title_bar_on: false,
            title_bar: None,
            window_icon: None,
            reveal_after_keyboard: false,
            platform: PlatformSettings::default(),
            inset_baseline: None,
            // The app starts out detached; `resumed` will move it to `Resumed`.
            lifecycle: Lifecycle::Detached,
            #[cfg(android)]
            android_app: None,
            #[cfg(android)]
            soft_input_shown: false,
            #[cfg(android)]
            system_bars: None,
        }
    }

    /// What an assistive technology's click on widget `id` does: what a pointer click on it
    /// would — its message, or, for a built-in button of the selection bar that carries none,
    /// its editing action (milestone 568), on the field the bar is open on.
    #[cfg(any(desktop, web))]
    fn activate_for_assistive_tech(&mut self, id: WidgetId) {
        if let Some(action) = self.ui.as_ref().and_then(|ui| ui.edit_action_for(id)) {
            self.perform_edit_action(action);
            return;
        }
        if let Some(msg) = self.ui.as_ref().and_then(|ui| ui.msg_for(id)) {
            // An item of the application's own on the bar closes it, as a press does.
            if self.ui.as_ref().is_some_and(|ui| ui.hit_is_on_toolbar(id)) {
                self.runtime.selection_handles = None;
                self.hide_selection_toolbar();
            }
            self.dispatch(msg);
            self.request_redraw();
        }
    }

    /// Replays the actions an assistive technology asked for: an AT click activates
    /// the widget, exactly as a pointer click would, and an AT focus focuses it.
    #[cfg(desktop)]
    fn drain_a11y_actions(&mut self) {
        use crate::a11y::A11yAction;
        let actions = match self.a11y.as_ref() {
            Some(a11y) => a11y.take_actions(),
            None => return,
        };
        for action in actions {
            match action {
                A11yAction::Click(id) => self.activate_for_assistive_tech(id),
                A11yAction::Focus(id) => {
                    // A button of the selection bar takes no focus: the bar acts on the
                    // field, and a focus that left it would end the very selection the bar
                    // is open on before the click that follows the focus got to use it.
                    if self.ui.as_ref().is_some_and(|ui| ui.hit_is_on_toolbar(id)) {
                        continue;
                    }
                    self.runtime.input.focused = Some(id);
                    self.runtime.focus_visible = true;
                    self.request_redraw();
                }
            }
        }
    }

    /// The web's counterpart to `drain_a11y_actions` above — same replay, the DOM
    /// bridge's own action type (#18).
    #[cfg(web)]
    fn drain_a11y_actions(&mut self) {
        use crate::a11y_web::A11yAction;
        let actions = match self.a11y.as_ref() {
            Some(a11y) => a11y.take_actions(),
            None => return,
        };
        for action in actions {
            match action {
                A11yAction::Click(id) => self.activate_for_assistive_tech(id),
                A11yAction::Focus(id) => {
                    // A button of the selection bar takes no focus: the bar acts on the
                    // field, and a focus that left it would end the very selection the bar
                    // is open on before the click that follows the focus got to use it.
                    if self.ui.as_ref().is_some_and(|ui| ui.hit_is_on_toolbar(id)) {
                        continue;
                    }
                    self.runtime.input.focused = Some(id);
                    self.runtime.focus_visible = true;
                    self.request_redraw();
                }
            }
        }
    }

    /// Keeps the **system bars** in step with the frame (#46): their colour and their icons,
    /// from the regions under them and then the theme. The platform is told only when the
    /// answer changes, telling it being a crossing to the Java UI thread — and a request
    /// that did not arrive is asked again next frame rather than remembered as made.
    ///
    /// The two points are the first row of content under the status bar and the last one
    /// above the navigation bar: this window is not drawn behind the bars, so what a bar
    /// stands against is what lies at the edge of the content next to it.
    fn sync_system_bars(&mut self, theme: &Theme) {
        #[cfg(android)]
        {
            let Some(ui) = self.ui.as_ref() else {
                return;
            };
            let Some(window) = self.window.as_ref() else {
                return;
            };
            let scale = self.total_scale();
            let size = window.inner_size();
            let (width, height) = (size.width as f32 / scale, size.height as f32 / scale);
            let edges = self.last_insets.padding;
            let bars = ui
                .system_ui_style(
                    frus_widgets::Point::new(width / 2.0, edges.top + 0.5),
                    frus_widgets::Point::new(width / 2.0, height - edges.bottom - 0.5),
                )
                .resolve(theme);
            if self.system_bars != Some(bars) && crate::android_system_bars::apply(bars) {
                self.system_bars = Some(bars);
            }
        }
        #[cfg(not(android))]
        let _ = theme;
    }

    /// Keeps the **software keyboard** in step with focus: asked for when focus is in
    /// a text field (`wants_keyboard`), closed otherwise. Called at the end of a
    /// frame, since any focus change already triggers a redraw.
    fn sync_soft_input(&mut self) {
        #[cfg(android)]
        {
            let editing = self
                .runtime
                .input
                .focused
                .and_then(|id| {
                    self.tree
                        .as_ref()
                        .and_then(|tree| find_widget(tree.as_ref(), id))
                })
                .is_some_and(wants_keyboard);
            if editing != self.soft_input_shown {
                self.soft_input_shown = editing;
                self.end_composition();
                if crate::android_ime::installed() {
                    // The InputConnection bridge: the Java view captures the IME.
                    if editing {
                        if let Some(id) = self.runtime.input.focused {
                            self.push_ime_context(id);
                        }
                        crate::android_ime::start_input(self.focused_ime());
                    } else {
                        crate::android_ime::clear_editor_state();
                        crate::android_ime::stop_input();
                    }
                } else if let Some(app) = &self.android_app {
                    // The TYPE_NULL fallback: a plain open, Latin keys only.
                    if editing {
                        app.show_soft_input(true);
                    } else {
                        app.hide_soft_input(false);
                    }
                }
            }
        }
    }

    /// What keyboard the **focused field** asks for.
    ///
    /// Found the same way the caret is — the focused id, resolved against the last
    /// tree built — so the two answers cannot disagree about which field is being
    /// typed into. A focus that resolves to nothing falls back to ordinary text, which
    /// is what every field got before this was asked at all.
    #[cfg(android)]
    fn focused_ime(&self) -> frus_widgets::Ime {
        self.runtime
            .input
            .focused
            .and_then(|id| {
                self.tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), id))
            })
            .map(|widget| widget.ime())
            .unwrap_or_default()
    }

    /// Notifies the app of a lifecycle **change**; never the same state twice in a row.
    fn set_lifecycle(&mut self, state: Lifecycle) {
        if self.lifecycle != state {
            self.lifecycle = state;
            self.app.on_lifecycle(state);
        }
    }

    /// **Explicitly** asks for the software keyboard again, for the focused field —
    /// called when the user **taps in a text field**, even one already focused. This is
    /// indispensable because the keyboard may have been closed by the **system back
    /// button** without the app being told: `soft_input_shown` then stays `true` and
    /// focus does not change on the next tap, so
    /// [`sync_soft_input`](Self::sync_soft_input)'s diff would see no change and never
    /// reopen the keyboard. Here it is reopened unconditionally — the native behaviour:
    /// tapping in a field shows the keyboard.
    fn request_soft_input(&mut self) {
        #[cfg(android)]
        {
            // Only a field that takes typing: a tap in a paragraph made selectable is a tap
            // in words to select, not in a form.
            let typing = self
                .runtime
                .input
                .focused
                .and_then(|id| {
                    self.tree
                        .as_ref()
                        .and_then(|tree| find_widget(tree.as_ref(), id))
                })
                .is_some_and(wants_keyboard);
            if !typing {
                return;
            }
            self.soft_input_shown = true;
            self.end_composition();
            if crate::android_ime::installed() {
                if let Some(id) = self.runtime.input.focused {
                    self.push_ime_context(id);
                }
                crate::android_ime::start_input(self.focused_ime());
            } else if let Some(app) = &self.android_app {
                app.show_soft_input(true);
            }
        }
    }

    /// Applies the pending IME operations to the focused field (the §6 bridge). The
    /// composition is materialised **in the field**: each update erases the previous
    /// one, the controlled model having no styled composition region yet — see
    /// docs/milestone-81.md.
    #[cfg(android)]
    fn drain_ime(&mut self) {
        use crate::ime::Step;
        let events = crate::android_ime::drain();
        if events.is_empty() {
            return;
        }
        let Some(focused) = self.runtime.input.focused else {
            return;
        };
        for event in events {
            let edit = self
                .runtime
                .edits
                .get(&focused)
                .copied()
                .unwrap_or_default();
            // Planned against the field as it stands before this operation: its text,
            // its caret and the composition it underlines (milestone 510).
            let text = self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), focused))
                .and_then(|widget| widget.text_value().map(str::to_owned))
                .unwrap_or_default();
            for step in crate::ime::plan(&event, &edit, &text) {
                match step {
                    Step::Place { cursor, anchor } => {
                        let edit = self.runtime.edits.entry(focused).or_default();
                        edit.cursor = cursor;
                        edit.anchor = anchor;
                    }
                    Step::Key(key) => self.apply_key(focused, key),
                    Step::Compose(region) => {
                        if let Some(edit) = self.runtime.edits.get_mut(&focused) {
                            edit.composing = region;
                        }
                    }
                    Step::ComposeTo(start) => {
                        if let Some(edit) = self.runtime.edits.get_mut(&focused) {
                            let end = edit.cursor;
                            edit.composing = (end > start).then_some((start, end));
                        }
                    }
                }
            }
        }
        // Refresh the input context, which the IME queries for its suggestions.
        self.push_ime_context(focused);
        self.request_redraw();
    }

    /// Keeps the platform's **autofill service** in step with the form being edited
    /// (milestone 512). When a field that says what it is for takes focus, its form is
    /// shown to the service and the service is told which field it is in; while it stays,
    /// every value the service has not heard is reported, or what it saves is what the
    /// fields held when it first looked; and when the form's group has left the screen
    /// — submitted, or navigated away from — it is committed, which is the moment a
    /// service may offer to save what was typed.
    #[cfg(android)]
    fn sync_autofill(&mut self) {
        use crate::{android_autofill as platform, autofill};
        if !crate::android_ime::installed() {
            return;
        }
        let scale = self.total_scale();
        let (Some(ui), Some(tree)) = (self.ui.as_ref(), self.tree.as_ref()) else {
            return;
        };
        let fields_of = |id: WidgetId| {
            autofill::structure(&ui.form_of(id), scale, |widget| {
                find_widget(tree.as_ref(), widget).map(|w| {
                    (
                        w.autofill_hints(),
                        w.text_value().unwrap_or_default().to_owned(),
                    )
                })
            })
        };
        // The focused field, when it takes part: it says what it is for.
        let focus = self.runtime.input.focused.filter(|&id| {
            find_widget(tree.as_ref(), id).is_some_and(|w| !w.autofill_hints().is_empty())
        });
        if focus != self.autofill_focus {
            if let Some(left) = self.autofill_focus {
                platform::exit(autofill::virtual_id(left));
            }
            if let Some(entered) = focus {
                let group = ui.form_group(entered);
                // A field of the form already shown — the next step of a wizard — keeps
                // the fields shown before it; any other form starts afresh.
                let shown: &[autofill::AutofillField] =
                    if group.is_some() && group == self.autofill_group {
                        &self.autofill_reported
                    } else {
                        &[]
                    };
                let fields = autofill::with_gone(fields_of(entered), shown);
                platform::publish(&fields);
                platform::enter(autofill::virtual_id(entered));
                self.autofill_reported = fields;
                self.autofill_group = group;
            }
            self.autofill_focus = focus;
        } else if let Some(id) = focus {
            let fields = autofill::with_gone(fields_of(id), &self.autofill_reported);
            for (virtual_id, value) in autofill::changed(&self.autofill_reported, &fields) {
                platform::value_changed(virtual_id, &value);
            }
            self.autofill_reported = fields;
        }
        if let Some(group) = self.autofill_group {
            if ui.group_stops(group).is_empty() {
                platform::commit();
                self.autofill_group = None;
                self.autofill_reported.clear();
            }
        }
    }

    /// Puts the values an autofill service chose into their fields (milestone 512), each
    /// through the message typing it would have produced — the path an undo takes, so a
    /// field that refuses typing refuses this too — with the caret after what arrived.
    #[cfg(android)]
    fn drain_autofill(&mut self) {
        let fills = crate::android_autofill::drain();
        if fills.is_empty() {
            return;
        }
        for (widget, value) in crate::autofill::route(&self.autofill_reported, fills) {
            let message = self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), widget))
                .and_then(|w| w.replace_value(value.clone()));
            if let Some(message) = message {
                self.runtime.edits.insert(
                    widget,
                    Edit {
                        cursor: value.chars().count(),
                        anchor: None,
                        composing: None,
                    },
                );
                self.dispatch_edit(message);
            }
        }
        if let Some(id) = self.runtime.input.focused {
            self.push_ime_context(id);
        }
        self.request_redraw();
    }

    /// Publishes field `id`'s editing state to the bridge — text, caret and selection
    /// — the context the IME reads for its suggestions.
    #[cfg(android)]
    fn push_ime_context(&self, id: WidgetId) {
        let value = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.text_value().map(|s| s.to_string()));
        if let Some(text) = value {
            let edit = self.runtime.edits.get(&id).copied().unwrap_or_default();
            crate::android_ime::set_editor_state(&text, edit.cursor, edit.selection_range());
            // And the keyboard is **told**, as an Android editor tells it on every change:
            // a keyboard that predicts keeps its own model of the field, and one never
            // told of a change drifts from it (milestone 510). In UTF-16 units.
            let len = text.chars().count();
            let at = |i: usize| crate::ime::utf16_index(&text, i.min(len)) as i32;
            let (start, end) = edit.selection_range().unwrap_or((edit.cursor, edit.cursor));
            let (cand_start, cand_end) = edit
                .composing
                .map(|(s, e)| (at(s), at(e)))
                .unwrap_or((-1, -1));
            crate::android_ime::update_selection(at(start), at(end), cand_start, cand_end);
        }
    }

    /// Ends the focused field's composition where it stands: the keyboard is being
    /// started again, and a keyboard started again has forgotten it.
    #[cfg(android)]
    fn end_composition(&mut self) {
        if let Some(id) = self.runtime.input.focused {
            if let Some(edit) = self.runtime.edits.get_mut(&id) {
                edit.composing = None;
            }
        }
    }

    /// Remembers the Android activity's handle, the source of the system insets.
    #[cfg(android)]
    pub(crate) fn set_android_app(
        &mut self,
        android_app: winit::platform::android::activity::AndroidApp,
    ) {
        self.android_app = Some(android_app);
    }

    /// The system insets — the safe area — in **logical** px. On Android they are
    /// derived from the activity's content rect, outside the system bars; zero
    /// elsewhere.
    ///
    /// The content rect is what the system leaves the activity, so it excludes
    /// **any** decoration the theme asks for — a title bar included. An app whose
    /// manifest keeps the default theme therefore reports a top inset of the status
    /// bar *plus* 56dp of action bar that is never drawn, and the shell dutifully
    /// pads it away: a wide empty band above the app bar. The manifests here ask for
    /// `Theme.DeviceDefault.NoActionBar`, and so must any frus app.
    fn compute_insets(&self, phys_w: u32, phys_h: u32, scale: f32) -> Insets {
        #[cfg(android)]
        if let Some(app) = &self.android_app {
            let r = app.content_rect();
            // A degenerate rect, before the first layout, means no inset.
            if r.right > r.left && r.bottom > r.top {
                let left = r.left.max(0) as f32;
                let top = r.top.max(0) as f32;
                let right = (phys_w as i32 - r.right).max(0) as f32;
                let bottom = (phys_h as i32 - r.bottom).max(0) as f32;
                return Insets::new(top / scale, right / scale, bottom / scale, left / scale);
            }
        }
        let _ = (phys_w, phys_h, scale);
        Insets::ZERO
    }

    /// Asks the platform what it says about its user, and remembers the answer.
    ///
    /// Marks the build dirty when something moved: the font size reaches the layout
    /// through [`MediaQuery::scope`], so a changed scaler is a changed geometry for every
    /// widget on the screen, and a frame drawn from the cache would keep the old one.
    fn refresh_platform_settings(&mut self) {
        #[cfg(android)]
        if let Some(app) = &self.android_app {
            let read = crate::android_settings::read(app);
            if read != self.platform {
                self.platform = read;
                self.build_dirty = true;
            }
            return;
        }
        // Desktop and web report the one thing their window system knows. A text scaler
        // is **not** among it: winit exposes no equivalent of Windows'
        // `UISettings.TextScaleFactor` or of GNOME's `text-scaling-factor`, so it stays
        // at 1 there and an application that knows better says so itself. That is a
        // missing wire and is written down rather than papered over.
        let brightness = self
            .window
            .as_ref()
            .and_then(|window| window.theme())
            .map(|theme| match theme {
                winit::window::Theme::Dark => frus_widgets::Brightness::Dark,
                winit::window::Theme::Light => frus_widgets::Brightness::Light,
            })
            .unwrap_or_default();
        if brightness != self.platform.brightness {
            self.platform.brightness = brightness;
            self.build_dirty = true;
        }

        // **The reader's languages**, read once. Changing the display language on a
        // desktop means signing out and back in on Windows, and is a per-process
        // environment variable on Linux — so there is nothing to watch for, and re-reading
        // it every time the window comes back would allocate for an answer that cannot
        // have moved. Android is the platform where it *does* change under a running
        // application, and Android reads it on every walk.
        if self.platform.locales.is_empty() {
            let read = platform_locales();
            if !read.is_empty() {
                self.platform.locales = read;
                self.build_dirty = true;
            }
        }
    }
}

/// **The reader's preferred languages**, best first, from whatever the platform keeps
/// them in. Empty when it says nothing, or when there is no way to ask.
///
/// Android does not come through here: its answer lives on the activity's
/// `Configuration`, which [`crate::android_settings`] already walks.
/// On **Android** there is nothing to ask here: the answer lives on the activity's
/// `Configuration`, and the branch above returns before reaching this. A build with no
/// activity at all has no reader to ask about.
#[cfg(android)]
fn platform_locales() -> Vec<frus_widgets::Locale> {
    Vec::new()
}

#[cfg(not(android))]
fn platform_locales() -> Vec<frus_widgets::Locale> {
    #[cfg(not(web))]
    {
        sys_locale::get_locales()
            .filter_map(|tag| frus_widgets::Locale::parse(&tag))
            .collect()
    }
    #[cfg(web)]
    {
        // `navigator.languages` is the ordered list; `navigator.language` is its first
        // entry and the fallback for a browser that does not offer the list.
        let Some(navigator) = web_sys::window().map(|window| window.navigator()) else {
            return Vec::new();
        };
        let listed: Vec<frus_widgets::Locale> = navigator
            .languages()
            .iter()
            .filter_map(|value| value.as_string())
            .filter_map(|tag| frus_widgets::Locale::parse(&tag))
            .collect();
        if listed.is_empty() {
            return navigator
                .language()
                .and_then(|tag| frus_widgets::Locale::parse(&tag))
                .into_iter()
                .collect();
        }
        listed
    }
}

/// Gives back the decoded images nobody is showing, and says how much went.
fn memory_trimmed() {
    let before = frus_widgets::image_cache_bytes();
    frus_widgets::trim_image_caches();
    log::info!(
        "memory is low: decoded network images trimmed from {} to {} KB",
        before / 1024,
        frus_widgets::image_cache_bytes() / 1024
    );
}

impl<A: Application> ApplicationHandler<A::Message> for App<A> {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.window.is_some() {
            return;
        }
        // Back in the foreground, or starting up: the surface is (re)born below.
        self.set_lifecycle(Lifecycle::Resumed);
        // And so is what the platform says about its user — a trip to the system
        // settings and back is exactly this event.
        self.refresh_platform_settings();

        let mut attributes = Window::default_attributes()
            .with_title(self.app.title())
            // A sensible minimum size, in logical px, to avoid an absurd UI.
            .with_min_inner_size(winit::dpi::LogicalSize::new(360.0, 280.0));
        // The AccessKit adapter must be created **before** the window is shown, so we
        // create it hidden and reveal it afterwards. Desktop only.
        #[cfg(desktop)]
        {
            attributes = attributes.with_visible(false);
        }
        // The application's icon, on the window (Windows and X11; Wayland and macOS take it
        // from the bundle and ignore this). Windows keeps a second, larger one for the taskbar
        // and Alt+Tab, set on its own.
        #[cfg(desktop)]
        {
            let icon = crate::icon::window_icon(&self.app.icon());
            #[cfg(windows)]
            {
                use winit::platform::windows::WindowAttributesExtWindows;
                attributes = attributes.with_taskbar_icon(icon.clone());
            }
            attributes = attributes.with_window_icon(icon);
        }
        // Not on the Web: there the page sizes the canvas, with its own CSS, and asking winit
        // for a size writes it **inline** on the canvas, where it outranks the stylesheet — an
        // application that named 900 by 680 then stayed 900 by 680 in a phone-sized window,
        // cropped, its drawer off the edge of what could be seen.
        #[cfg(not(web))]
        if let Some((w, h)) = self.app.window_size() {
            attributes = attributes.with_inner_size(winit::dpi::LogicalSize::new(w, h));
        }
        // Restarted by `frus run`: where the window was, as big as it was.
        #[cfg(desktop)]
        if let Some([x, y, w, h]) = crate::dev::restore_window() {
            attributes = attributes
                .with_position(winit::dpi::PhysicalPosition::new(x, y))
                .with_inner_size(winit::dpi::PhysicalSize::new(w as u32, h as u32));
        }
        // Web: winit creates a `<canvas>` and **appends it** to the document's body.
        #[cfg(web)]
        {
            use winit::platform::web::WindowAttributesExtWebSys;
            attributes = attributes.with_append(true);
        }
        let window = match event_loop.create_window(attributes) {
            Ok(window) => {
                crate::startup::window_made();
                Arc::new(window)
            }
            Err(err) => {
                log::error!("failed to create the window: {err}");
                event_loop.exit();
                return;
            }
        };

        // Web: GPU init is **asynchronous**, blocking being impossible. We start the
        // future, and the ready renderer is picked up on the first frame — see
        // `RedrawRequested`. `init` runs right away, since it does not touch the GPU.
        #[cfg(web)]
        {
            self.scale = window.scale_factor() as f32;
            self.window = Some(window.clone());
            // The accessibility bridge (#18): the canvas exists as soon as the window
            // does, so there is no "still hidden" step to wait for here.
            self.a11y = crate::a11y_web::A11y::new(&window);
            // The browser keeps reload, the developer tools and the rest of its own shortcuts
            // while the canvas has the focus, instead of winit cancelling them.
            crate::web_keys::let_the_browser_keep_its_shortcuts();
            // The tab's icon: the application's, or the frus logo where the page has none.
            crate::web_icon::apply(&self.app.icon());
            self.build_dirty = true;
            if !self.started {
                self.started = true;
                let command = self.app.init();
                self.run_command(command);
                self.sync_subscriptions();
                self.open_launch_address(&window);
                crate::dev_commands::set_window(Some(window.clone()));
                if let Some(states) = crate::web_dev::start() {
                    self.runtime.states.restore_from(&states);
                }
                #[cfg(feature = "hot-reload")]
                {
                    crate::hot::set_window(window.clone());
                    crate::hot::connect();
                }
            }
            let slot = self.pending_renderer.clone();
            let win = window.clone();
            let size = window.inner_size();
            wasm_bindgen_futures::spawn_local(async move {
                match Renderer::new(win.clone(), size.width.max(1), size.height.max(1)).await {
                    Ok(r) => {
                        crate::startup::renderer_made(r.startup_times());
                        *slot.borrow_mut() = Some(r);
                        win.request_redraw();
                    }
                    Err(err) => log::error!("failed to initialise the renderer (Web): {err:#}"),
                }
            });
        }

        #[cfg(not(web))]
        {
            let size = window.inner_size();
            let (width, height) = (size.width.max(1), size.height.max(1));
            // On Windows, a renderer whose frames let the system's own title bar show where
            // the window's menu bar leaves the line transparent (milestone 643); the
            // ordinary one where that cannot be had.
            let see_through = if cfg!(windows) {
                match pollster::block_on(Renderer::see_through(window.clone(), width, height)) {
                    Ok(renderer) => Some(renderer),
                    Err(err) => {
                        log::info!("title bar painted by frus: {err:#}");
                        None
                    }
                }
            } else {
                None
            };
            let renderer = match see_through {
                Some(renderer) => Ok(renderer),
                None => pollster::block_on(Renderer::new(window.clone(), width, height)),
            };

            match renderer {
                Ok(renderer) => {
                    crate::startup::renderer_made(renderer.startup_times());
                    self.scale = window.scale_factor() as f32;
                    // The accessibility bridge (AccessKit), created while the window is
                    // still hidden, after which we reveal it. Inert with no screen reader.
                    #[cfg(desktop)]
                    {
                        self.a11y = Some(crate::a11y::A11y::new(event_loop, &window));
                        window.set_visible(true);
                        // A second process's link brings this window forward and asks it for
                        // a frame.
                        crate::instance::set_window(window.clone());
                    }
                    self.window = Some(window.clone());
                    // What the input bridge's wakes ask a frame of (milestone 513).
                    #[cfg(android)]
                    crate::android_ime::set_window(Some(window.clone()));
                    #[cfg(android)]
                    crate::dev_commands::set_window(Some(window.clone()));
                    self.renderer = Some(renderer);
                    // The surface was (re)created: force a full rebuild on the first frame.
                    self.build_dirty = true;
                    // The startup effect, an initial load and so on: once only, not on
                    // every surface recreation, such as returning from the background.
                    if !self.started {
                        self.started = true;
                        let command = self.app.init();
                        self.run_command(command);
                        self.sync_subscriptions();
                        #[cfg(any(android, desktop))]
                        self.open_launch_link();
                        #[cfg(any(android, desktop))]
                        self.connect_dev();
                        #[cfg(feature = "hot-reload")]
                        {
                            crate::hot::set_window(window.clone());
                            crate::hot::connect();
                        }
                    }
                    window.request_redraw();
                }
                Err(err) => {
                    log::error!("failed to initialise the renderer: {err:#}");
                    event_loop.exit();
                }
            }
        }
    }

    /// Going to the background, on Android: the native surface is destroyed. We
    /// release the renderer and the window, and `resumed` recreates them on the way
    /// back, without replaying `init` — see `started`. Harmless on desktop, where the
    /// event never fires.
    fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
        // Background: the surface is lost, so the app moves to `Paused`.
        self.set_lifecycle(Lifecycle::Paused);
        // Under `frus run`, this is how a restart begins on Android: the states are kept.
        #[cfg(android)]
        if self.dev.is_some() {
            if let Some(storage) = self
                .android_app
                .as_ref()
                .and_then(|a| a.internal_data_path())
            {
                crate::dev::keep_states(&storage, &self.runtime.states.snapshot());
            }
        }
        self.renderer = None;
        self.window = None;
        #[cfg(android)]
        crate::android_ime::set_window(None);
        #[cfg(android)]
        crate::dev_commands::set_window(None);
        self.last_frame = None;
    }

    /// The event loop is ending, on close: a final `Detached` notification, where the
    /// app can persist its state before the process disappears.
    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
        self.set_lifecycle(Lifecycle::Detached);
    }

    /// The system is short of memory (Android's low-memory callback, iOS's memory
    /// warning): the decoded images nobody is showing are given back, rather than left
    /// for the system to reclaim by ending the process.
    fn memory_warning(&mut self, _event_loop: &ActiveEventLoop) {
        memory_trimmed();
    }

    /// A message produced by an effect, on a background thread: we apply it and ask
    /// for another frame.
    fn user_event(&mut self, _event_loop: &ActiveEventLoop, message: A::Message) {
        self.dispatch(message);
        self.request_redraw();
    }

    /// The loop woke up: if the long-press deadline has been reached the recogniser
    /// **accepts eagerly** — the message is emitted and the release to come will be
    /// swallowed, the long press having evicted the tap.
    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
        if matches!(cause, StartCause::ResumeTimeReached { .. }) && self.press.poll(Instant::now())
        {
            self.hold_deadline_reached();
        }
        if matches!(cause, StartCause::ResumeTimeReached { .. }) {
            self.poll_pending_tap(Instant::now());
        }

        // The caret's turn is due: a frame to show it, or to hide it, in (milestone 513).
        if matches!(cause, StartCause::ResumeTimeReached { .. })
            && self.lifecycle == Lifecycle::Resumed
            && self.caret.next_toggle(Instant::now()).is_some()
        {
            self.request_redraw();
        }

        // Pending IME operations, from the Android input bridge.
        #[cfg(android)]
        self.drain_ime();
        // And the values an autofill service chose, from the same bridge.
        #[cfg(android)]
        self.drain_autofill();

        // Actions an assistive technology asked for, through AccessKit.
        #[cfg(desktop)]
        self.drain_a11y_actions();
        // Actions a screen reader asked for, through the DOM bridge (#18).
        #[cfg(web)]
        self.drain_a11y_actions();

        // Live reload, in development: the binary was replaced by a recompilation, so
        // capture the state and relaunch the new binary. This does not return.
        if let Some(watcher) = self.reload.as_mut() {
            if watcher.binary_changed() {
                watcher.handoff(self.app.save_state());
            }
        }
        event_loop.set_control_flow(self.idle_control_flow());
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _window_id: WindowId,
        event: WindowEvent,
    ) {
        // The AccessKit adapter observes the window events: focus, size and so on.
        #[cfg(desktop)]
        if let (Some(a11y), Some(window)) = (self.a11y.as_mut(), self.window.as_ref()) {
            a11y.process_event(window, &event);
        }

        match event {
            WindowEvent::CloseRequested => event_loop.exit(),

            // Gaining or losing focus **in the foreground**: `Resumed` ⇄ `Inactive`. We
            // leave `Paused`/`Detached` — background and closing — alone; those are
            // decided by `suspended` and `exiting`.
            WindowEvent::Focused(focused) => {
                if !matches!(self.lifecycle, Lifecycle::Paused | Lifecycle::Detached) {
                    self.set_lifecycle(if focused {
                        Lifecycle::Resumed
                    } else {
                        Lifecycle::Inactive
                    });
                }
                // The line the window shares with the system quietens with it, as the
                // system's own caption does: a frame reads the window's state again
                // (milestone 643).
                #[cfg(windows)]
                if self.title_bar_on {
                    self.request_redraw();
                }
            }

            WindowEvent::Resized(size) => {
                if let Some(renderer) = self.renderer.as_mut() {
                    renderer.resize(size.width, size.height);
                }
                if let Some(window) = &self.window {
                    window.request_redraw();
                }
            }

            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                self.scale = scale_factor as f32;
                // Reconfigure the surface to the current physical size.
                if let Some(window) = &self.window {
                    let size = window.inner_size();
                    if let Some(renderer) = self.renderer.as_mut() {
                        renderer.resize(size.width, size.height);
                    }
                }
                self.request_redraw();
            }

            WindowEvent::Occluded(occluded) => {
                self.occluded = occluded;
                if !occluded {
                    self.request_redraw();
                }
            }

            // Every pointer source, mouse and touch alike, converges on the
            // **normalised** `pointer()` input — gesture tier 0, with an explicit
            // `Cancel`. winit hands us physical px; we work in logical ones, the total
            // scale being DPI × density.
            WindowEvent::CursorMoved { position, .. } => {
                let scale = self.total_scale();
                let position = Point::new(position.x as f32 / scale, position.y as f32 / scale);
                self.pointer(
                    event_loop,
                    PointerEvent {
                        kind: PointerKind::Move,
                        position,
                        touch: false,
                    },
                );
            }

            // The mouse left the window: nothing in it is under the pointer any more.
            WindowEvent::CursorLeft { .. } => {
                self.hover.left();
                self.sync_hover();
                self.sync_regions(false);
            }

            WindowEvent::Touch(touch) => {
                let scale = self.total_scale();
                let position = Point::new(
                    touch.location.x as f32 / scale,
                    touch.location.y as f32 / scale,
                );
                let kind = match touch.phase {
                    TouchPhase::Started => PointerKind::Down,
                    TouchPhase::Moved => PointerKind::Move,
                    TouchPhase::Ended => PointerKind::Up,
                    TouchPhase::Cancelled => PointerKind::Cancel,
                };
                self.pointer(
                    event_loop,
                    PointerEvent {
                        kind,
                        position,
                        touch: true,
                    },
                );
            }

            WindowEvent::ModifiersChanged(modifiers) => {
                let state = modifiers.state();
                self.shift = state.shift_key();
                self.ctrl = state.control_key();
                self.alt = state.alt_key();
                self.meta = state.super_key();
            }

            WindowEvent::MouseInput {
                state: ElementState::Pressed,
                button: MouseButton::Left,
                ..
            } => self.pointer(
                event_loop,
                PointerEvent {
                    kind: PointerKind::Down,
                    position: self.cursor,
                    touch: false,
                },
            ),

            WindowEvent::MouseInput {
                state: ElementState::Released,
                button: MouseButton::Left,
                ..
            } => self.pointer(
                event_loop,
                PointerEvent {
                    kind: PointerKind::Up,
                    position: self.cursor,
                    touch: false,
                },
            ),

            // A right-click on a text field opens its selection bar (milestone 568), which is
            // the desktop's context menu for the four things it holds.
            WindowEvent::MouseInput {
                state: ElementState::Pressed,
                button: MouseButton::Right,
                ..
            } => self.context_click(),

            WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => {
                self.key_down(&KeyDown::from(&event), Some(event_loop));
            }

            WindowEvent::MouseWheel { delta, .. } => {
                let (mut dx, mut dy) = match delta {
                    MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_SPEED, y * SCROLL_SPEED),
                    // Physical delta → logical.
                    MouseScrollDelta::PixelDelta(pos) => {
                        let scale = self.total_scale();
                        (pos.x as f32 / scale, pos.y as f32 / scale)
                    }
                };
                // With Shift, the wheel scrolls horizontally.
                if self.shift {
                    dx = dy;
                    dy = 0.0;
                }
                // Over an interactive viewport the wheel **zooms**, anchored at the
                // pointer and bounded by the widget's min and max scales.
                if let Some((id, viewport)) = self
                    .ui
                    .as_ref()
                    .and_then(|ui| ui.interactive_at(self.cursor))
                {
                    let (min, max) = self
                        .tree
                        .as_ref()
                        .and_then(|tree| find_widget(tree.as_ref(), id))
                        .and_then(|w| w.interactive())
                        .unwrap_or((0.5, 4.0));
                    // Wheel up (`dy > 0`) zooms in, in gentle steps of about 1.1× a notch.
                    let factor = (1.0 + dy * 0.1 / SCROLL_SPEED).clamp(0.2, 5.0);
                    // Zooming cuts off a fling in progress.
                    self.runtime.interactive_velocity.remove(&id);
                    let view = self.runtime.interactive.entry(id).or_default();
                    // Zoom anchored at the pointer, then bounded to the frame.
                    *view = view
                        .zoom_at(factor, self.cursor, min, max)
                        .clamped(viewport);
                    self.request_redraw();
                    return;
                }
                // A wheel asks the same question a finger does, and the reference gates it
                // the same way: an area with everything already in sight takes no offset,
                // and the notch belongs to whatever is behind it.
                let hit = {
                    let scroll = &self.runtime.scroll;
                    self.ui.as_ref().and_then(|ui| {
                        ui.scroll_chain(self.cursor).find(|area| {
                            area.accepts_user_offset(
                                scroll.get(&area.id).copied().unwrap_or((0.0, 0.0)),
                            )
                        })
                    })
                };
                if let Some(area) = hit {
                    // Scrolling with inertia: the wheel pushes the TARGET and the
                    // spring eases across to it. How far past the ends that target
                    // may go is the physics' call — a little elastic overshoot where
                    // the platform bounces, none at all where it does not.
                    let id = area.id;
                    let physics = area.physics;
                    let over = if physics.allows_overscroll() {
                        SCROLL_OVER
                    } else {
                        0.0
                    };
                    // A notch of the wheel is a new intent: it takes over from the
                    // momentum of the last gesture.
                    self.runtime.stop_scroll_fling(id);
                    let current = self.runtime.scroll.get(&id).copied().unwrap_or((0.0, 0.0));
                    // A screen delta into offsets: the content moves opposite the number,
                    // and a reversed axis counts from the other end. One function, so a
                    // reversed area is right at every one of the places this happens.
                    let (ddx, ddy) = area.offset_delta((dx, dy));
                    let target = self.runtime.scroll_target.entry(id).or_insert(current);
                    let (wanted_x, wanted_y) = (target.0 + ddx, target.1 + ddy);
                    target.0 = wanted_x.clamp(-over, area.max_x + over);
                    target.1 = wanted_y.clamp(-over, area.max_y + over);
                    let refused = (wanted_x - target.0, wanted_y - target.1);
                    self.runtime.scroll_velocity.entry(id).or_insert((0.0, 0.0));
                    // A notch that asks to go past the end deserves the same
                    // acknowledgement a finger gets: the wheel is a gesture too.
                    let cursor = self.cursor;
                    for (refused, vertical, extent) in [
                        (refused.0, false, area.viewport.width),
                        (refused.1, true, area.viewport.height),
                    ] {
                        if refused.abs() < 1e-3 {
                            continue;
                        }
                        let edge = area.refused_edge(vertical, refused);
                        let (offset, cross) =
                            frus_widgets::glow_cross_axis(area.viewport, edge, cursor);
                        self.runtime.glow_pull(
                            id,
                            area.overscroll,
                            edge,
                            refused,
                            extent,
                            offset,
                            cross,
                        );
                        // A wheel has no "lift off", so the pull is released at once
                        // and simply fades — otherwise it would hang until the hold
                        // timer expired.
                        self.runtime.glow_scroll_end(id);
                    }
                    self.request_redraw();
                }
            }

            WindowEvent::RedrawRequested => {
                // The GPU device was lost on the last frame: a new renderer first.
                if std::mem::take(&mut self.renderer_lost) {
                    self.rebuild_renderer();
                }
                // Measured only when asked: a clock read per stage is cheap, but not free.
                let measuring = self.frame_stats.enabled();
                let frame_start = measuring.then(Instant::now);
                self.frame_costs = crate::frame_stats::FrameCosts::default();
                // Web: pick up the asynchronously initialised renderer as soon as it
                // is ready; until then, nothing is painted.
                #[cfg(web)]
                if self.renderer.is_none() {
                    match self.pending_renderer.borrow_mut().take() {
                        Some(mut renderer) => {
                            // The renderer was sized from whatever `inner_size()` read
                            // back when it was spawned — often 0×0, before the canvas
                            // had been laid out by CSS. A `Resized` event carrying the
                            // real size may have arrived and been dropped in the
                            // meantime, since `self.renderer` was still `None` then.
                            // Catching up here, against the size right now, is what
                            // makes that race harmless either way.
                            if let Some(window) = &self.window {
                                let size = window.inner_size();
                                renderer.resize(size.width.max(1), size.height.max(1));
                            }
                            self.renderer = Some(renderer);
                        }
                        None => return,
                    }
                }
                // A paste the browser has answered since the last frame goes in before
                // this one is built. Elsewhere a paste is answered on the spot and this
                // finds nothing.
                while let Some(pasted) = self.clipboard.take_answered() {
                    self.land_paste(pasted);
                }
                // The widgets hear where the focus went since the last frame, before this
                // one is built from what they answer (milestone 660).
                self.report_focus();
                // A bar whose field is no longer the focused one is over: a field focused
                // again later must not find it open.
                if self
                    .runtime
                    .selection_toolbar
                    .is_some_and(|mark| self.runtime.input.focused != Some(mark.id))
                {
                    self.runtime.selection_toolbar = None;
                }
                // Occluded window: rendering is suspended, resuming on Occluded(false).
                if self.occluded {
                    return;
                }
                let size = self
                    .window
                    .as_ref()
                    .map(|w| w.inner_size())
                    .unwrap_or_default();
                // Minimised, or zero-sized: nothing to draw, which avoids GPU errors.
                if size.width == 0 || size.height == 0 {
                    self.last_frame = None; // no dt jump when it is restored
                    return;
                }
                // The interface is described in **logical** pixels; the GPU output is
                // scaled to physical ones (DPI × density) just before rendering.
                let scale = self.total_scale();
                let (width, height) = (size.width as f32 / scale, size.height as f32 / scale);

                // A logical size change — a resize OR a density change — notifies the
                // app before the view, so it can react to the breakpoint in its logic.
                if self.last_size != Some((width, height)) {
                    self.last_size = Some((width, height));
                    self.build_dirty = true;
                    self.app.on_resize(width, height);
                }

                // Window insets: separates the static **padding** — bars and notch —
                // from the **keyboard**, which is whatever bottom inset exceeds the
                // keyboard-free baseline. The baseline is taken at the first measurement
                // for this physical size (a rotation gives a new one), and corrects
                // downwards should a barer state appear: the keyboard open at startup,
                // the bars hidden, and so on.
                let raw = self.compute_insets(size.width, size.height, scale);
                let phys = (size.width, size.height);
                let mut baseline = match self.inset_baseline {
                    Some((b, s)) if s == phys => b,
                    _ => {
                        self.inset_baseline = Some((raw, phys));
                        raw
                    }
                };
                if raw.bottom < baseline.bottom {
                    baseline = raw;
                    self.inset_baseline = Some((raw, phys));
                }
                let insets = WindowInsets::from_baseline(baseline, raw);
                if self.last_insets != insets {
                    if insets.view_insets.bottom > self.last_insets.view_insets.bottom {
                        self.reveal_after_keyboard = true;
                    }
                    self.last_insets = insets;
                    self.build_dirty = true;
                    self.app.on_insets(insets);
                }

                // The elapsed dt, clamped, for every animation.
                let now = Instant::now();
                let dt = self
                    .last_frame
                    .map(|prev| (now - prev).as_secs_f32().min(0.05))
                    .unwrap_or(0.0);
                self.last_frame = Some(now);

                // A continuous clock, in seconds, for the time-driven animations.
                self.elapsed += dt;
                self.runtime.time = self.elapsed;

                // The caret's blink (milestone 513), on the wall clock: the animation
                // clock above is clamped per frame and stands still between frames, and a
                // caret at rest is exactly when there are none. Solid while the window is
                // not the one in front, where nothing wakes the loop for it.
                let caret_now = Instant::now();
                let caret = if self.lifecycle == Lifecycle::Resumed {
                    self.caret_signature()
                } else {
                    None
                };
                self.caret.observe(caret_now, caret);
                self.runtime.caret_hidden = self.caret.hidden(caret_now);

                // The application advances its own animations: navigation, gesture.
                let mut app_animating = self.app.tick(dt);

                // And the framework advances the **theme**, which is its own work: it
                // resolves the application's themes against the brightness the platform
                // reports and the contrast the reader asked for, and crosses from the one
                // on screen to the one now wanted over `theme_animation_duration`.
                //
                // Both halves of that were the application's before milestone 452, and
                // both were being done by hand in this repo's own demonstration — which
                // is a fair sign of what every application was having to write.
                let settings = self
                    .platform
                    .accessibility
                    .with_overrides(self.app.accessibility());

                // **The ambient scopes, before anything reads them** — which the theme
                // does: the direction of the layout follows the language, so an
                // application whose theme is right-to-left in Arabic needs the language
                // installed before its theme is asked for. This used to sit further down,
                // beside the build, where it was in time for the widgets and one frame
                // late for the theme.
                //
                // Read every frame, all of it: these are the application's answers and
                // they may change while it is running.
                install_ambient(&self.app, &self.platform.locales);

                let theme_moved = self.themes.advance(
                    &self.app,
                    self.brightness(),
                    settings.high_contrast,
                    settings.disable_animations,
                    dt,
                );
                // A theme that moved is a rebuild — the view is a pure function of
                // `(state, theme, size)` — and a fade still running is another frame.
                app_animating |= theme_moved | self.themes.animating();
                let theme = self.themes.displayed(&self.app);

                // **The surface, in force for the whole frame** — not just for `view`.
                // A size becomes a number in three places: while the widgets are built,
                // while they are measured and laid out, and while they are painted.
                // Scoping the build alone left the last two at scale 1, so the layout
                // measured one size and the renderer drew another, and the reader's
                // setting reached a device without moving a single pixel (milestone 407).
                //
                // One guard, not two: the description and the font size are installed by
                // the same call and released by the same drop, so they cannot be held for
                // different lengths of time. Holding them separately is the same bug with
                // an extra step (milestone 408). It lives to the end of this frame and
                // puts back what was there, panic or not.
                let _surface = self.media_query(width, height).install();

                // === BUILD phase, conditional ===
                // The `view` is rebuilt only when the app's state or the size changed
                // (`build_dirty`), or when the app is animating, theme, navigation and
                // gesture all altering the state the view reads. A frame that animates
                // interaction alone — hover, scroll, focus, caret — **reuses the
                // retained tree** and merely repaints: the `view` is a pure function of
                // `(state, theme, size)` and never of the `Runtime`.
                // The user's motion setting reaches the runtime before anything is
                // advanced with it, and it is read every frame: a settings screen with a
                // *reduce motion* switch changes it while the application is running.
                self.runtime.still = settings.disable_animations;
                // And where the pointer stands in relation to a bar, from the previous
                // frame's registry — the only one there is at this point in the frame.
                //
                // Near a bar, it holds it open and warms the thumb; a bar that has faded
                // out entirely still answers here, and comes back for the reach. On a
                // touch platform nothing draws a bar in the first place, so the registry
                // is empty and a lingering finger position says nothing.
                self.runtime.scrollbar_hovered = self
                    .ui
                    .as_ref()
                    .and_then(|ui| ui.scrollbar_near(self.cursor))
                    .map(|bar| bar.id);
                self.runtime.scrollbar_dragged = match self.drag {
                    Some(Drag::Scrollbar { id, .. }) => Some(id),
                    _ => None,
                };
                // A switcher in flight carries each child's progress as a number built into
                // the tree, so it is rebuilt — not only repainted — until the switch settles.
                // Something a component keeps changed — a `set_state`, a hook, a controller —
                // and what it builds is built again.
                // What components asked of the shell since the last frame — a focus, a scroll,
                // work for another thread — is run first: it may ask for this very rebuild.
                let asked = self.app.effects();
                self.run_command(asked);
                self.take_dev_commands();
                #[cfg(web)]
                self.sync_address();
                #[cfg(any(desktop, android))]
                self.report_dev();
                #[cfg(desktop)]
                self.open_links_from_other_instances();
                // Work a component started brought something: build again to show it.
                let arrived = self.take_task_arrivals();
                // A hot-reload patch changed what the components build.
                #[cfg(feature = "hot-reload")]
                let arrived = crate::hot::take_patched() || arrived;
                if frus_widgets::take_rebuild_request() || arrived {
                    self.build_dirty = true;
                }
                let need_build = frame_needs_build(
                    self.build_dirty,
                    app_animating,
                    std::mem::replace(&mut self.app_was_animating, app_animating),
                    self.tree.is_none() || self.runtime.switching(),
                );
                if need_build {
                    // No scope of its own: the surface above is already installed, and
                    // covers the layout and the paint that follow as well.
                    //
                    // `build_view`, not `view`: `collect_ids` below reads this tree before
                    // the layout pass has been down it, so an unprepared tree would report
                    // no identities at all inside a deferred subtree — and everything in an
                    // `AppBar` would silently never mount, never fade in and never fade out.
                    let build_start = measuring.then(Instant::now);
                    let tree = build_view(&self.app, &theme, &self.runtime);
                    if let Some(at) = build_start {
                        self.frame_costs.build = Some(at.elapsed().as_secs_f32() * 1000.0);
                    }
                    let ids = collect_ids(tree.as_ref());
                    let present: std::collections::HashSet<_> = ids.iter().copied().collect();

                    // Leaving: snapshot the widgets present at N-1 but absent at N,
                    // so they can be faded out.
                    let leaving: std::collections::HashSet<u64> = self
                        .runtime
                        .mounted
                        .iter()
                        .filter(|id| !present.contains(id))
                        .map(|id| id.as_u64())
                        .collect();
                    if !leaving.is_empty() {
                        if let Some(ui) = &self.ui {
                            let captured: Vec<_> = ui
                                .scene()
                                .primitives()
                                .iter()
                                .filter(|p| leaving.contains(&p.owner()))
                                .cloned()
                                .collect();
                            if !captured.is_empty() {
                                self.runtime
                                    .leaving
                                    .insert(self.leaving_counter, (captured, 1.0));
                                self.leaving_counter = self.leaving_counter.wrapping_add(1);
                            }
                        }
                    }

                    // Mounting: new widgets start out fading in.
                    for &id in &ids {
                        if self.runtime.mounted.insert(id) {
                            self.runtime.anims.entry(id).or_default().opacity = 0.0;
                        }
                    }
                    self.runtime.mounted.retain(|id| present.contains(id));

                    self.tree = Some(tree);
                    // What the build asked for may be a timer — a component's
                    // `use_interval` — and it is the build that says so, which is later than
                    // the message that changed it. Diffing here starts and stops it now, not
                    // on the next message.
                    self.sync_subscriptions();

                    // The configuration may have changed, so invalidate the paint
                    // cache and its repaint boundaries. Entries from a stale generation
                    // no longer *hit*, giving a full repaint this frame and reuse on the
                    // interaction-only frames that follow.
                    self.runtime.paint_cache.borrow_mut().bump_generation();
                }
                self.build_dirty = false;

                // Focus requests (`Command::focus`), resolved against the tree just
                // (re)built — the key names the field wrapped in `keyed(k, …)`. The most
                // recent one that resolves wins, and the focus ring becomes visible
                // again, since we jump to the field as the keyboard would.
                if !self.pending_focus.is_empty() {
                    let keys = std::mem::take(&mut self.pending_focus);
                    let ids: Vec<WidgetId> = self
                        .tree
                        .as_deref()
                        .map(|tree| keys.iter().filter_map(|&k| find_by_key(tree, k)).collect())
                        .unwrap_or_default();
                    if let Some(&id) = ids.last() {
                        self.runtime.input.focused = Some(id);
                        self.runtime.focus_visible = true;
                    }
                }

                // === PAINT phase ===
                // The retained tree is (re)painted. Layout goes through the relayout
                // cache (milestone 55: taffy is called again only when the structure
                // changed); painting goes through the repaint cache (milestone 88: a
                // A row carried past the end of the list: the list comes to meet it.
                // Before the tree is borrowed for the rest of the frame, because it moves
                // an offset the build below is about to read — and this frame, not the
                // next one, or the content would lag a frame behind the finger.
                let autoscrolling = self.autoscroll_carried(dt);

                // The reorder spring, per axis, with a time constant of about 70 ms:
                // - **horizontal** (`Table` columns): the smoothed `reorder_x` catches up
                //   with the pointer — the columns slide with inertia while the ghost
                //   sticks to the real pointer;
                // - **vertical** (Kanban cards): the smoothed `reorder_y` catches up with
                //   the **chosen** slot edge, the hovered half — the insertion line and
                //   the gap *slide* between cards instead of jumping, which is the
                //   vertical counterpart of `reorder_x`;
                // - **a horizontal list's rows**: `reorder_x` catches up with the chosen
                //   slot edge, the same line turned on its side.
                let reorder_animating = self.advance_reorder_springs(dt);

                // static `RepaintBoundary` subtree is replayed without repainting while
                // its geometry and the interaction state hold still).
                let tree = self
                    .tree
                    .as_deref()
                    .expect("the view was built at least once");

                // Scroll and pan inertia; the bounds and viewports come from the
                // previous frame.
                let scroll_regions = self
                    .ui
                    .as_ref()
                    .map(|ui| ui.scroll_regions().to_vec())
                    .unwrap_or_default();
                // The refresh areas of the frame, with the `refreshing` flag each was
                // built with: that flag is what tells a spinning indicator when to stop.
                let refresh_areas = self
                    .ui
                    .as_ref()
                    .map(|ui| ui.refresh_areas().to_vec())
                    .unwrap_or_default();
                let dismissables = self
                    .ui
                    .as_ref()
                    .map(|ui| ui.dismissables().to_vec())
                    .unwrap_or_default();
                // Filled by the dismissal step below, dispatched once the tree is no
                // longer borrowed.
                let mut dismissed: Vec<A::Message> = Vec::new();
                let sheet_areas = self
                    .ui
                    .as_ref()
                    .map(|ui| ui.sheets().to_vec())
                    .unwrap_or_default();
                let interactive_bounds = self
                    .ui
                    .as_ref()
                    .map(|ui| ui.interactive_bounds())
                    .unwrap_or_default();

                // A paged view that has been asked for another page glides across to
                // it. Done before the springs are stepped, so the request is honoured
                // in the frame it arrives rather than the one after.
                self.runtime.sync_pages(&scroll_regions);
                // And a bar whose selected item has moved out of its window slides back
                // to it. Same moment, same reason: the request is honoured in the frame
                // it arrives rather than the one after.
                self.runtime.sync_visible(&scroll_regions);
                // And the scroll requests an application has just returned. Same moment
                // and the same reason, with one addition: a region that has only just
                // appeared is not in the registry above, which was built last frame, so
                // what does not resolve here is tried again below against this frame's.
                let requests = std::mem::take(&mut self.pending_scroll);
                let (retry, scrolled) =
                    apply_scroll_requests(&mut self.runtime, tree, requests, &scroll_regions);
                self.retry_scroll = retry;
                // And the sheets it has asked to move, on the same terms: before the sheets
                // are stepped, so an animated request starts in the frame it arrives in.
                let requests = std::mem::take(&mut self.pending_sheet);
                let (retry, sheeted) =
                    apply_sheet_requests(&mut self.runtime, tree, requests, &sheet_areas);
                self.retry_sheet = retry;

                // Every family is stepped, in this order, whatever an earlier one answered; each
                // answer is kept by name, so that frame statistics can say which kept the frames
                // coming (milestone 609).
                let moving: [(&str, bool); 25] = [
                    ("scrolled", scrolled),
                    ("sheeted", sheeted),
                    ("anims", self.runtime.advance(dt)),
                    ("leaving", self.runtime.advance_leaving(dt)),
                    ("switchers", self.runtime.advance_switchers(tree, dt)),
                    ("values", self.runtime.advance_values(tree, dt)),
                    ("colors", self.runtime.advance_colors(tree, dt)),
                    ("sizes", self.runtime.advance_sizes(tree, dt)),
                    ("radii", self.runtime.advance_radii(tree, dt)),
                    ("paddings", self.runtime.advance_paddings(tree, dt)),
                    ("offsets", self.runtime.advance_offsets(tree, dt)),
                    ("pins", self.runtime.advance_pins(tree, dt)),
                    ("fractions", self.runtime.advance_fractions(tree, dt)),
                    ("text_styles", self.runtime.advance_text_styles(tree, dt)),
                    ("transforms", self.runtime.advance_transforms(tree, dt)),
                    ("scroll", self.runtime.advance_scroll(&scroll_regions, dt)),
                    ("glow", self.runtime.advance_glow(dt)),
                    ("refresh", self.runtime.advance_refresh(&refresh_areas, dt)),
                    ("dismiss", {
                        // A dismissed item announces itself only once its gap has
                        // finished closing. The messages are *collected* here and
                        // dispatched below: the retained tree is borrowed for the whole
                        // of this frame, and `dispatch` rebuilds it.
                        let (moving, done) = self.runtime.advance_dismiss(&dismissables, dt);
                        dismissed.extend(done.into_iter().filter_map(|(id, direction)| {
                            find_widget(tree, id).and_then(|widget| widget.on_dismissed(direction))
                        }));
                        moving
                    }),
                    ("sheets", {
                        // A sheet lowered to nothing says so once it has arrived there,
                        // collected like a dismissal and for the same reason.
                        let (moving, closed) = self.runtime.advance_sheets(&sheet_areas, dt);
                        dismissed.extend(closed.into_iter().filter_map(|id| {
                            find_widget(tree, id).and_then(|widget| widget.on_sheet_dismissed())
                        }));
                        // A throw that carried a sheet to full height goes on into its
                        // list, under the list's own physics (milestone 520).
                        let mut handed = false;
                        for (list, velocity) in self.runtime.take_sheet_handovers() {
                            if let Some(area) = scroll_regions.iter().find(|a| a.id == list) {
                                handed |=
                                    self.runtime
                                        .fling_scroll(*area, area.physics, (0.0, velocity));
                            }
                        }
                        moving | handed
                    }),
                    (
                        "interactive",
                        self.runtime.advance_interactive(&interactive_bounds, dt),
                    ),
                    ("ink", self.runtime.advance_ink(dt)),
                    ("reorder", reorder_animating),
                    ("autoscroll", autoscrolling),
                    ("app", app_animating),
                ];
                let animating = moving.iter().any(|(_, on)| *on);
                self.frame_stats.note_moving(&moving);
                // With the inspector on, the same build collects the observed nodes,
                // and the overlay — outlines plus a card for the hovered widget — is
                // painted on top of a copy of the scene.
                let layout_start = measuring.then(Instant::now);
                // So do debug paint (outlines alone, no card) and the dumps `frus run` asks
                // for (milestone 668).
                let inspected = self.inspector
                    || self.debug.outlines
                    || self.inspector_dump
                    || self.debug.focus_dump;
                let (ui, scene) = if inspected {
                    let (ui, nodes) = frus_widgets::build_ui_inspected(
                        tree,
                        Size::new(width, height),
                        &self.runtime,
                        &theme,
                    );
                    if std::mem::take(&mut self.inspector_dump) {
                        // Through `log`, so it reaches logcat and the browser too.
                        log::info!(target: "frus::inspector", "
{}", frus_widgets::dump_tree(&nodes));
                    }
                    if std::mem::take(&mut self.debug.focus_dump) {
                        let focusable: Vec<WidgetId> = ui.focusable_ids().collect();
                        log::info!(target: "frus::inspector", "focus, in tab order:
{}", dump_focus(&nodes, &focusable, self.runtime.input.focused));
                    }
                    let mut scene = if self.inspector {
                        // The card goes over the application's text, which a scene draws after
                        // its shapes: the application's frame as one layer, under it.
                        on_top_of(ui.scene())
                    } else {
                        ui.scene().clone()
                    };
                    if self.inspector || self.debug.outlines {
                        frus_widgets::paint_inspector_overlay(
                            &nodes,
                            self.inspector.then_some(self.cursor),
                            Size::new(width, height),
                            &theme,
                            &mut scene,
                        );
                    }
                    // Scene: logical → physical (DPI × density).
                    (ui, scene.scaled(scale))
                } else {
                    let ui = build_ui(tree, Size::new(width, height), &self.runtime, &theme);
                    // The preview of a column reorder, or a lifted item, on top of the
                    // scene.
                    let scene = if matches!(self.drag, Some(Drag::Reorder { moved: true, .. })) {
                        let mut scene = ui.scene().clone();
                        self.paint_reorder_preview(&ui, &theme, &mut scene);
                        scene.scaled(scale)
                    } else if matches!(self.drag, Some(Drag::Item { moved: true, .. })) {
                        let mut scene = ui.scene().clone();
                        self.paint_drag_ghost(&ui, &theme, &mut scene);
                        scene.scaled(scale)
                    } else {
                        // Scene: logical → physical (DPI × density), for a crisp render.
                        ui.scene().scaled(scale)
                    };
                    (ui, scene)
                };
                if let Some(at) = layout_start {
                    self.frame_costs.layout_paint = at.elapsed().as_secs_f32() * 1000.0;
                    self.frame_costs.layers = count_layers(scene.primitives());
                }
                self.report_overflows(&ui);
                // Laid out: the components the build no longer reached are let go, and the
                // effects it asked for run. An effect that changed something asks for the
                // frame that shows it.
                self.runtime.states.end_frame();
                crate::startup::laid_out();
                #[cfg(web)]
                crate::web_dev::keep(|| self.runtime.states.snapshot());
                if frus_widgets::rebuild_requested() {
                    self.request_redraw();
                }
                // A see-through frame starts transparent: the window's background under
                // everything but the line the system paints (milestone 643).
                let scene = if self.renderer.as_ref().is_some_and(Renderer::sees_through) {
                    backdrop_under(scene, width * scale, height * scale, self.system_line())
                } else {
                    scene
                };
                // What the keys of `frus run` asked of this frame (milestone 668).
                if std::mem::take(&mut self.debug.semantics_dump) {
                    log::info!(target: "frus::inspector", "semantics, in reading order:
{}", dump_semantics(ui.semantics()));
                }
                let scene = if self.debug.performance {
                    // The application's frame as one layer, the panel over it: in a scene of
                    // its own, the application's text would be drawn over the panel's
                    // rectangle — the renderer draws a scene's shapes, then its text.
                    let mut scene = on_top_of(&scene);
                    let costs = self.debug.last_costs.as_ref().map(|(costs, _)| costs);
                    // Below the status bar, where the system draws its own.
                    let top = self.last_insets.padding.top * scale;
                    paint_performance(
                        &mut scene,
                        costs,
                        &self.debug.history,
                        self.debug.fps,
                        width * scale,
                        top,
                        scale,
                    );
                    scene
                } else {
                    scene
                };
                #[cfg(desktop)]
                if let Some(path) = self.debug.screenshot.take() {
                    write_screenshot(&scene, width * scale, height * scale, &path);
                }
                let mut device_lost = false;
                if let Some(renderer) = self.renderer.as_mut() {
                    let render_start = measuring.then(Instant::now);
                    match renderer.render(&scene) {
                        frus_gpu::RenderOutcome::Presented => crate::startup::presented(),
                        frus_gpu::RenderOutcome::NeedsReconfigure => {
                            renderer.reconfigure();
                        }
                        frus_gpu::RenderOutcome::DeviceLost => device_lost = true,
                        frus_gpu::RenderOutcome::Skipped => {}
                    }
                    // The page's picture, read in the task that drew it: a WebGPU canvas keeps
                    // what was drawn only until the task ends.
                    #[cfg(web)]
                    if std::mem::take(&mut self.debug.page_screenshot) {
                        if let Some(window) = self.window.as_ref() {
                            crate::web_dev::send_screenshot(window);
                        }
                    }
                    if let Some(at) = render_start {
                        self.frame_costs.render = at.elapsed().as_secs_f32() * 1000.0;
                        let timings = renderer.last_timings();
                        self.frame_costs.acquire = timings.acquire;
                        self.frame_costs.draw = timings.draw;
                        self.frame_costs.gpu = timings.gpu;
                    }
                }
                // The GPU device is gone: a new renderer on the same window, at the next frame's
                // start, which draws the interface again (milestone 686, #217).
                if device_lost {
                    self.renderer_lost = true;
                    if let Some(window) = self.window.as_ref() {
                        window.request_redraw();
                    }
                }
                // A continuously animating widget, a spinner say, forces a redraw. So
                // does an image still on its way: without a frame to draw it in, the
                // frame that would show it never happens.
                //
                // The fetch is asked about **here** rather than inside the tree, and as a
                // count rather than a flag on the widget: showing a placeholder means
                // taking the image out of the tree, so a hook read off `Image` would go
                // quiet at exactly the moment it is needed. Asking here also keeps `Ui`
                // answering for its own widgets alone (milestone 411).
                let widget_asks = ui.wants_animation();
                let loading =
                    frus_widgets::images_in_flight() > 0 || frus_widgets::tasks_in_flight() > 0;
                let wants_animation = widget_asks || loading;

                // Keep the interface, for hit testing. The tree is already retained.
                self.ui = Some(ui);
                // The keyboard took room from the bottom of the window: what the reader is
                // typing in is brought back above it, by the least scroll that does it, and
                // by the same glide Tab uses. This frame's layout is the shortened one, so
                // the viewports asked are the ones left above the keyboard. A frame with
                // nothing focused, or no region around what is, moves nothing.
                let revealed = std::mem::take(&mut self.reveal_after_keyboard) && {
                    let moves = match (self.runtime.input.focused, self.ui.as_ref()) {
                        (Some(id), Some(ui)) => ui.reveal(id, &self.runtime),
                        _ => Vec::new(),
                    };
                    let moved = !moves.is_empty();
                    for (area, offset) in moves {
                        self.runtime.scroll_ballistic.remove(&area);
                        self.runtime.scroll_velocity.remove(&area);
                        self.runtime.scroll_target.insert(area, offset);
                    }
                    moved
                };
                // The tree may have changed under a still pointer — a tap that opened a
                // screen — so what it is over is asked of this frame, as the reference
                // does after every frame. Not during a drag: a slider dragged past its
                // end is still the one being pressed, and the move path leaves it so.
                //
                // Field by field rather than through `sync_hover`, which borrows the whole
                // shell: the frame still holds part of it here. A change is shown the way
                // the reference shows it, on the next frame — the tree is built again,
                // since a tooltip's bubble is decided while the tree is walked.
                let rehovered = self.drag.is_none() && {
                    let hovered = self.ui.as_ref().and_then(|ui| self.hover.target(ui));
                    let changed = hovered != self.runtime.input.hovered;
                    self.runtime.input.hovered = hovered;
                    changed
                };
                if rehovered {
                    self.build_dirty = true;
                }
                let wants_animation = wants_animation || rehovered || revealed;

                // The paged views that have just turned a page, read off **this**
                // frame's regions: a page change is worth reporting the moment it
                // reads as one, not a frame later.
                let paged = self
                    .ui
                    .as_ref()
                    .map(|ui| ui.scroll_regions().to_vec())
                    .unwrap_or_default();
                // A region whose content shrank this frame under an offset nobody owns was
                // drawn where it now rests; the runtime keeps it there before anything reads
                // the offset back — the reports below, a press, the next frame's springs.
                // Without it the row was drawn right once and pressed wrong (milestone 533).
                self.runtime.keep_scroll_in_range(&paged);
                let turned: Vec<A::Message> = self
                    .runtime
                    .page_changes(&paged)
                    .into_iter()
                    .filter_map(|(id, page)| {
                        find_widget(tree, id).and_then(|widget| widget.on_page_changed(page))
                    })
                    .collect();

                // The scroll requests the previous frame's registry could not place:
                // tried once against **this** frame's, which is where a region that has
                // only just appeared turns up. This is the last chance they get.
                let (_, moved_late) = apply_scroll_requests(
                    &mut self.runtime,
                    tree,
                    std::mem::take(&mut self.retry_scroll),
                    &paged,
                );
                // The same for the sheet requests: a sheet shown by the very message that
                // asked it to move is in this frame's sheets and not the last one's.
                let (_, sheeted_late) = {
                    let sheets = self
                        .ui
                        .as_ref()
                        .map(|ui| ui.sheets().to_vec())
                        .unwrap_or_default();
                    apply_sheet_requests(
                        &mut self.runtime,
                        tree,
                        std::mem::take(&mut self.retry_sheet),
                        &sheets,
                    )
                };

                // The regions that have moved since they last said so, read off **this**
                // frame's registry so that the offset and the extents reported together
                // come from the same frame. A region nobody is listening to costs the
                // comparison and nothing else.
                let scrolled: Vec<A::Message> = {
                    let grain =
                        |id| find_widget(tree, id).map_or(0.0, |widget| widget.scroll_grain());
                    self.runtime
                        .scroll_changes(&paged, grain)
                        .into_iter()
                        .filter_map(|(id, position)| {
                            find_widget(tree, id).and_then(|widget| widget.on_scroll(position))
                        })
                        .collect()
                };

                // The rows whose gap has just finished closing, the pages that have
                // turned and the regions that have moved: the tree is no longer
                // borrowed, so the application can be told — and rebuild.
                for message in dismissed.into_iter().chain(turned).chain(scrolled) {
                    self.dispatch(message);
                }
                // A screen that changed under a still pointer enters and leaves regions too,
                // as the reference's mouse tracker does after every frame (milestone 583).
                self.sync_regions(false);
                if moved_late || sheeted_late {
                    // Nothing else this frame knows the offset changed: the springs ran
                    // before the request was placed.
                    self.request_redraw();
                }

                // Focus return: when the focused widget has **vanished**, an overlay
                // having closed, go back to the trigger. Done before the AccessKit
                // announcement, so the focus it publishes is current.
                self.reconcile_focus();

                // Publish the frame's semantic tree to AccessKit.
                #[cfg(desktop)]
                if let Some(a11y) = self.a11y.as_mut() {
                    let focus = self.runtime.input.focused;
                    let title = self.app.title();
                    if let Some(ui) = self.ui.as_ref() {
                        a11y.update(ui.semantics(), focus, &title, &self.announce);
                    }
                }
                // Publish the frame's semantic tree to the DOM bridge (#18).
                #[cfg(web)]
                if let Some(a11y) = self.a11y.as_mut() {
                    let focus = self.runtime.input.focused;
                    let title = self.app.title();
                    if let Some(ui) = self.ui.as_ref() {
                        a11y.update(ui.semantics(), focus, &title, &self.announce);
                    }
                }

                // The system bars follow the frame: the regions under them, then the theme.
                self.sync_system_bars(&theme);

                // The Android software keyboard follows the text fields' focus.
                self.sync_soft_input();
                // And the autofill service follows the form being edited.
                #[cfg(android)]
                self.sync_autofill();

                // While an animation is running, ask for another frame.
                if animating || wants_animation {
                    self.request_redraw();
                }
                if let Some(start) = frame_start {
                    use crate::frame_stats::Why;
                    let why = [
                        (app_animating, Why::APP),
                        (animating, Why::RUNTIME),
                        (widget_asks, Why::WIDGET),
                        (loading, Why::LOADING),
                        (rehovered || revealed, Why::POINTER),
                    ];
                    self.frame_costs.why = why
                        .into_iter()
                        .filter(|(on, _)| *on)
                        .fold(Why::NONE, |all, (_, why)| all | why);
                    self.frame_stats.frame(start, self.frame_costs);
                    if self.debug.performance {
                        if let Some((_, before)) = self.debug.last_costs {
                            let gap = start.saturating_duration_since(before).as_secs_f32();
                            if gap > 0.0 {
                                self.debug.fps = 1.0 / gap;
                            }
                        }
                        // The first frame measured: one more shows what it cost.
                        if self.debug.last_costs.is_none() {
                            self.request_redraw();
                        }
                        self.debug.last_costs = Some((self.frame_costs, start));
                        self.debug.history.push(&self.frame_costs);
                    }
                }
                // The title bar's line, shared with the content when it asks (milestone 640).
                #[cfg(windows)]
                self.sync_title_bar();
            }

            _ => {}
        }
    }
}

/// What the keys of `frus run` turned on or asked for (milestone 668).
#[derive(Default)]
struct DebugAsks {
    /// Outlines around every widget, without the inspector's card: debug paint (`p`).
    outlines: bool,
    /// The focusable widgets to print on the next frame, the focused one marked (`f`).
    focus_dump: bool,
    /// The accessibility tree to print on the next frame (`S`).
    semantics_dump: bool,
    /// The brightness the theme is resolved with instead of the platform's (`b`).
    brightness: Option<frus_widgets::Brightness>,
    /// The performance panel: the last frame's costs, over the interface (`P`).
    performance: bool,
    /// The last frame's costs and when it began, for the panel.
    last_costs: Option<(crate::frame_stats::FrameCosts, Instant)>,
    /// The latest frames' costs, oldest first, for the panel's graphs (milestone 676).
    history: FrameHistory,
    /// Frames per second, from the gap between the last two.
    fps: f32,
    /// Where to write the next frame as a PNG (`s`).
    #[cfg_attr(not(desktop), allow(dead_code))]
    screenshot: Option<std::path::PathBuf>,
    /// The page's next frame to send to `frus run` as a PNG (`s` on the web, milestone 675).
    #[cfg_attr(not(web), allow(dead_code))]
    page_screenshot: bool,
}

/// The order `o` goes through the platforms in.
const PLATFORM_CYCLE: [frus_widgets::TargetPlatform; 6] = [
    frus_widgets::TargetPlatform::Android,
    frus_widgets::TargetPlatform::Ios,
    frus_widgets::TargetPlatform::Windows,
    frus_widgets::TargetPlatform::MacOs,
    frus_widgets::TargetPlatform::Linux,
    frus_widgets::TargetPlatform::Fuchsia,
];

/// The platform after `current` in [`PLATFORM_CYCLE`].
fn next_platform(current: frus_widgets::TargetPlatform) -> frus_widgets::TargetPlatform {
    let at = PLATFORM_CYCLE
        .iter()
        .position(|p| *p == current)
        .unwrap_or(0);
    PLATFORM_CYCLE[(at + 1) % PLATFORM_CYCLE.len()]
}

/// The focusable widgets of a frame, in tab order, the focused one marked.
fn dump_focus(
    nodes: &[frus_widgets::InspectorNode],
    focusable: &[WidgetId],
    focused: Option<WidgetId>,
) -> String {
    let mut out = String::new();
    for id in focusable {
        let node = nodes.iter().rev().find(|n| n.id == *id);
        let mark = if Some(*id) == focused { "▶ " } else { "  " };
        match node {
            Some(n) => out.push_str(&format!(
                "{mark}{}  {:.0},{:.0}  {:.0}×{:.0}  #{:08x}\n",
                n.name,
                n.rect.x,
                n.rect.y,
                n.rect.width,
                n.rect.height,
                id.as_u64() as u32
            )),
            None => out.push_str(&format!("{mark}#{:08x}\n", id.as_u64() as u32)),
        }
    }
    if out.is_empty() {
        out.push_str("  (nothing focusable)\n");
    }
    out
}

/// The accessibility tree of a frame, one node a line, in reading order.
fn dump_semantics(nodes: &[(WidgetId, Rect, frus_widgets::SemanticsProperties)]) -> String {
    let mut out = String::new();
    for (_, rect, props) in nodes {
        out.push_str(&format!("  {:?}", props.role));
        if let Some(label) = &props.label {
            out.push_str(&format!(" \"{label}\""));
        }
        if let Some(value) = &props.value {
            out.push_str(&format!(" = {value}"));
        }
        if props.clickable {
            out.push_str(" clickable");
        }
        if props.disabled {
            out.push_str(" disabled");
        }
        out.push_str(&format!(
            "  {:.0},{:.0}  {:.0}×{:.0}\n",
            rect.x, rect.y, rect.width, rect.height
        ));
    }
    if out.is_empty() {
        out.push_str("  (empty)\n");
    }
    out
}

/// The performance panel, in the top right corner of a `width`×`height` frame drawn at
/// `scale`: the last frame's costs and the rate of frames.
#[allow(clippy::too_many_arguments)]
fn paint_performance(
    scene: &mut frus_widgets::Scene,
    costs: Option<&crate::frame_stats::FrameCosts>,
    history: &FrameHistory,
    fps: f32,
    width: f32,
    top: f32,
    scale: f32,
) {
    let lines = match costs {
        Some(costs) => performance_lines(costs, fps),
        None => vec!["measuring…".to_string()],
    };
    paint_panel(scene, lines, history, width, top, scale);
}

/// How many frames the graphs show.
const HISTORY: usize = 90;
/// A frame's budget at 60 Hz, in milliseconds: the line the bars are measured against.
const BUDGET_MS: f32 = 1000.0 / 60.0;
/// The height of a graph, in milliseconds: two budgets.
const GRAPH_MS: f32 = BUDGET_MS * 2.0;

/// The latest frames' costs for the performance panel: what the interface took (build, layout,
/// paint) and what drawing took (encoding, submitting, waiting for the GPU and the display).
#[derive(Default)]
struct FrameHistory {
    ui: std::collections::VecDeque<f32>,
    render: std::collections::VecDeque<f32>,
}

impl FrameHistory {
    fn push(&mut self, costs: &crate::frame_stats::FrameCosts) {
        let ui = costs.build.unwrap_or(0.0) + costs.layout_paint;
        for (list, value) in [(&mut self.ui, ui), (&mut self.render, costs.render)] {
            if list.len() == HISTORY {
                list.pop_front();
            }
            list.push_back(value);
        }
    }

    /// The bars of one graph, `height` high: for each frame its height, and whether it was
    /// over budget. A frame over the graph's top fills it.
    fn bars(values: &std::collections::VecDeque<f32>, height: f32) -> Vec<(f32, bool)> {
        values
            .iter()
            .map(|ms| ((ms / GRAPH_MS).min(1.0) * height, *ms > BUDGET_MS))
            .collect()
    }
}

/// A scene holding `scene` as one layer, for something to be painted over all of it: within a
/// scene, the renderer draws the shapes first and the text after, so a panel's rectangle in the
/// same scene would sit under the application's text.
fn on_top_of(scene: &Scene) -> Scene {
    let mut over = Scene::new();
    over.layer(1.0, |inner| {
        for primitive in scene.primitives() {
            inner.push_primitive(primitive.clone());
        }
    });
    over
}

/// The panel's lines for a frame that cost `costs`.
fn performance_lines(costs: &crate::frame_stats::FrameCosts, fps: f32) -> Vec<String> {
    let build = costs
        .build
        .map_or_else(|| "kept".to_string(), |ms| format!("{ms:.1} ms"));
    let mut lines = vec![
        // One frame alone has no rate: the interface is idle.
        if fps > 0.0 {
            format!("{fps:.0} fps")
        } else {
            "idle".to_string()
        },
        format!("build {build}  layout+paint {:.1} ms", costs.layout_paint),
        format!(
            "render {:.1} ms (acquire {:.1}, draw {:.1})",
            costs.render, costs.acquire, costs.draw
        ),
    ];
    if let Some(gpu) = costs.gpu {
        lines.push(format!("GPU {gpu:.1} ms"));
    }
    lines
}

/// `lines` in a dark panel in the top right corner of a frame `width` physical pixels wide,
/// `top` pixels down.
fn paint_panel(
    scene: &mut frus_widgets::Scene,
    lines: Vec<String>,
    history: &FrameHistory,
    width: f32,
    top: f32,
    scale: f32,
) {
    let size = 12.0 * scale;
    let style = frus_widgets::TextStyle::new(size).resolved();
    let pad = 6.0 * scale;
    let line_h = size * 1.4;
    // Estimated rather than measured: the panel is a tool's, and a little room to spare is
    // all an estimate costs.
    let longest = lines
        .iter()
        .map(|line| line.chars().count())
        .max()
        .unwrap_or(0);
    // Two graphs under the text, one bar a frame.
    let bar_w = 2.0 * scale;
    let graph_w = HISTORY as f32 * bar_w;
    let graph_h = 36.0 * scale;
    let graphs_h = if history.ui.is_empty() {
        0.0
    } else {
        2.0 * (graph_h + line_h) + pad
    };
    let text_w = (longest as f32 * size * 0.6).max(graph_w);
    let panel = Rect::new(
        (width - text_w - pad * 3.0).max(0.0),
        top + pad,
        text_w + pad * 2.0,
        line_h * lines.len() as f32 + pad * 2.0 + graphs_h,
    );
    scene.set_clip(Rect::UNBOUNDED);
    scene.set_owner(0);
    // Opaque: a translucent one blends in linear light and paints as a grey.
    scene.draw_rect(
        panel,
        frus_widgets::Color::rgb(0.05, 0.05, 0.05),
        4.0 * scale,
        0.0,
        frus_widgets::Color::TRANSPARENT,
    );
    let count = lines.len();
    for (i, line) in lines.into_iter().enumerate() {
        scene.text(
            frus_widgets::Point::new(panel.x + pad, panel.y + pad + line_h * i as f32),
            line,
            &style,
            frus_widgets::Color::rgb(0.55, 1.0, 0.55),
        );
    }
    if history.ui.is_empty() {
        return;
    }
    let mut y = panel.y + pad + line_h * count as f32 + pad;
    for (title, values) in [
        ("interface (build, layout, paint)", &history.ui),
        ("drawing (encode, submit, present)", &history.render),
    ] {
        scene.text(
            frus_widgets::Point::new(panel.x + pad, y),
            title.to_string(),
            &style,
            frus_widgets::Color::rgb(0.75, 0.75, 0.75),
        );
        y += line_h;
        let area = Rect::new(panel.x + pad, y, graph_w, graph_h);
        scene.draw_rect(
            area,
            frus_widgets::Color::rgb(0.12, 0.12, 0.12),
            0.0,
            0.0,
            frus_widgets::Color::TRANSPARENT,
        );
        // The bars, the newest on the right.
        let bars = FrameHistory::bars(values, graph_h);
        let start = area.x + area.width - bars.len() as f32 * bar_w;
        for (i, (h, over)) in bars.into_iter().enumerate() {
            if h <= 0.0 {
                continue;
            }
            let color = if over {
                frus_widgets::Color::rgb(1.0, 0.35, 0.3)
            } else {
                frus_widgets::Color::rgb(0.4, 0.85, 0.45)
            };
            scene.fill_rect(
                Rect::new(
                    start + i as f32 * bar_w,
                    area.y + area.height - h,
                    bar_w * 0.8,
                    h,
                ),
                color,
            );
        }
        // The budget: a frame drawn at 60 Hz stays under this line.
        let budget_y = area.y + area.height * (1.0 - BUDGET_MS / GRAPH_MS);
        scene.fill_rect(
            Rect::new(area.x, budget_y, area.width, scale.max(1.0)),
            frus_widgets::Color::rgb(0.95, 0.95, 0.95),
        );
        y += graph_h + pad / 2.0;
    }
}

/// Writes `scene`, a frame `width`×`height` physical pixels, to `path` as a PNG, drawn again
/// offscreen: the window's own image cannot be read back. Says where in the log, or why not.
#[cfg(desktop)]
fn write_screenshot(scene: &Scene, width: f32, height: f32, path: &std::path::Path) {
    let (w, h) = (
        width.round().max(1.0) as u32,
        height.round().max(1.0) as u32,
    );
    let Some(frame) = frus_gpu::render_offscreen(scene, w, h, frus_gpu::backdrop()) else {
        log::warn!(target: "frus::dev", "screenshot: no GPU to draw it with");
        return;
    };
    let png = crate::dev_commands::png(frame.width, frame.height, &frame.rgba);
    match std::fs::write(path, png) {
        Ok(()) => log::debug!(
            target: "frus::dev",
            "screenshot {}×{} written to {}",
            frame.width,
            frame.height,
            path.display()
        ),
        Err(error) => log::warn!(target: "frus::dev", "screenshot: {}: {error}", path.display()),
    }
}

impl<A: Application> App<A> {
    /// Carries out what the keys of `frus run` asked since the last frame (milestone 668).
    /// Each says what it did in the log, which `frus run` shows.
    /// A new renderer on the window, after its GPU device was lost — a driver reset, a GPU
    /// removed or restarted —, of the same kind as the old one: the application goes on, its
    /// interface drawn again on the next frame (milestone 686, #217).
    fn rebuild_renderer(&mut self) {
        let see_through = self.renderer.as_ref().is_some_and(Renderer::sees_through);
        // The old renderer — its surface on this window among it — goes first.
        self.renderer = None;
        let Some(window) = self.window.clone() else {
            return;
        };
        let size = window.inner_size();
        let (width, height) = (size.width.max(1), size.height.max(1));
        log::warn!("the GPU device was lost: drawing again with a new one");
        #[cfg(not(web))]
        {
            let made = if see_through {
                pollster::block_on(Renderer::see_through(window.clone(), width, height))
            } else {
                pollster::block_on(Renderer::new(window.clone(), width, height))
            };
            match made {
                Ok(renderer) => self.renderer = Some(renderer),
                Err(err) => {
                    log::error!("the GPU device was lost, and no new one could be made: {err:#}")
                }
            }
        }
        #[cfg(web)]
        {
            let _ = see_through;
            let slot = self.pending_renderer.clone();
            let win = window.clone();
            wasm_bindgen_futures::spawn_local(async move {
                match Renderer::new(win.clone(), width, height).await {
                    Ok(renderer) => {
                        *slot.borrow_mut() = Some(renderer);
                        win.request_redraw();
                    }
                    Err(err) => {
                        log::error!(
                            "the GPU device was lost, and no new one could be made: {err:#}"
                        )
                    }
                }
            });
        }
        self.build_dirty = true;
        window.request_redraw();
    }

    fn take_dev_commands(&mut self) {
        for command in crate::dev_commands::take_commands() {
            let (name, argument) = command
                .split_once(' ')
                .map_or((command.as_str(), ""), |(n, a)| (n, a.trim()));
            let on_off = |on: bool| if on { "on" } else { "off" };
            match name {
                "inspector" => {
                    self.inspector = !self.inspector;
                    self.inspector_dump = self.inspector;
                    log::info!(target: "frus::dev", "inspector {}", on_off(self.inspector));
                }
                "outlines" => {
                    self.debug.outlines = !self.debug.outlines;
                    log::info!(target: "frus::dev", "debug paint {}", on_off(self.debug.outlines));
                }
                "widgets" => self.inspector_dump = true,
                "focus" => self.debug.focus_dump = true,
                "semantics" => self.debug.semantics_dump = true,
                "platform" => {
                    let next = next_platform(frus_widgets::default_target_platform());
                    if cfg!(debug_assertions) {
                        frus_widgets::set_debug_default_target_platform_override(Some(next));
                        log::info!(target: "frus::dev", "target platform: {next:?}");
                    } else {
                        log::warn!(target: "frus::dev", "the platform can be switched in a debug build only");
                    }
                }
                "brightness" => {
                    let now = self.debug.brightness.unwrap_or(self.platform.brightness);
                    let next = match now {
                        frus_widgets::Brightness::Light => frus_widgets::Brightness::Dark,
                        frus_widgets::Brightness::Dark => frus_widgets::Brightness::Light,
                    };
                    self.debug.brightness = Some(next);
                    log::info!(
                        target: "frus::dev",
                        "brightness: {next:?} (an application without a theme for it stays as it is)"
                    );
                }
                "performance" => {
                    self.debug.performance = !self.debug.performance;
                    self.debug.last_costs = None;
                    self.debug.history = FrameHistory::default();
                    self.frame_stats.set_enabled(self.debug.performance);
                    // This frame began unmeasured: the next one is, and shows its figures.
                    self.request_redraw();
                    log::info!(target: "frus::dev", "performance panel {}", on_off(self.debug.performance));
                }
                // The system's low-memory call, on demand (milestone 687).
                "trim-memory" => memory_trimmed(),
                // A driver reset, on purpose: what follows is the recovery (milestone 686).
                "lose-gpu" => {
                    if let Some(renderer) = self.renderer.as_ref() {
                        log::warn!(target: "frus::dev", "losing the GPU device, as a driver reset would");
                        renderer.lose_device_for_testing();
                        self.request_redraw();
                    }
                }
                "screenshot" if !argument.is_empty() => {
                    #[cfg(desktop)]
                    {
                        self.debug.screenshot = Some(std::path::PathBuf::from(argument));
                    }
                    #[cfg(web)]
                    {
                        self.debug.page_screenshot = true;
                    }
                    #[cfg(android)]
                    log::warn!(target: "frus::dev", "the application takes no screenshot of itself here");
                }
                _ => {
                    log::warn!(target: "frus::dev", "frus run asked for `{command}`, which this frus does not know")
                }
            }
            self.build_dirty = true;
        }
    }

    /// The brightness the theme is resolved with: the platform's, unless `b` said otherwise.
    fn brightness(&self) -> frus_widgets::Brightness {
        self.debug.brightness.unwrap_or(self.platform.brightness)
    }

    /// How tall the title bar's line the system paints is, in physical pixels: `0` where
    /// it paints none (milestone 643).
    fn system_line(&self) -> f32 {
        // The line the content was told: the one its row covers.
        match self.title_bar {
            Some(line) if self.title_bar_on && line.system_paints => {
                line.height * self.total_scale()
            }
            _ => 0.0,
        }
    }

    /// The total scale: system DPI × app density (physical = logical × this).
    fn total_scale(&self) -> f32 {
        (self.scale * self.app.density()).max(0.1)
    }

    /// The surface description installed around every call to `view`, so that any
    /// widget built there can read it with `MediaQuery::of()` instead of having the
    /// application carry it down by hand.
    ///
    /// Everything in it is already known to the shell — the logical size it is about
    /// to lay out for, the DPI scale, the app's density, and the insets last reported
    /// by the platform. It is assembled here, in one place, rather than at each of the
    /// call sites.
    /// The **platform** answers, and the application overrides what it chose to speak for.
    ///
    /// That order is the one the reference uses and the only one that stays honest: the
    /// settings belong to the person using the device, so the framework asks them first,
    /// and an application with a *reduce motion* switch of its own says only that. An
    /// [`AccessibilityOverrides`] whose fields are all `None` — the default — leaves every
    /// answer to the user, which is what an application that has no settings screen means.
    fn media_query(&self, width: f32, height: f32) -> MediaQuery {
        MediaQuery::new(Size::new(width, height))
            .with_device_pixel_ratio(self.scale)
            .with_density(self.app.density())
            .with_text_scaler(self.platform.text_scaler)
            .with_platform_brightness(self.brightness())
            .with_accessibility(
                self.platform
                    .accessibility
                    .with_overrides(self.app.accessibility()),
            )
            .with_insets(self.last_insets)
            .with_title_bar(self.title_bar)
    }

    /// **Shares the window's title bar line with the content** when the frame asks for it,
    /// gives it back when it no longer does, and tells the content what the system keeps on
    /// it (milestone 640). See `title_bar.rs`.
    #[cfg(windows)]
    fn sync_title_bar(&mut self) {
        use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
        let Some(window) = self.window.clone() else {
            return;
        };
        let hwnd = match window.window_handle().map(|h| h.as_raw()) {
            Ok(RawWindowHandle::Win32(win)) => {
                win.hwnd.get() as windows_sys::Win32::Foundation::HWND
            }
            _ => return,
        };
        let wants = self.ui.as_ref().is_some_and(|ui| ui.wants_title_bar());
        if wants != self.title_bar_on {
            // SAFETY: the window is alive and was made on this thread.
            unsafe {
                if wants {
                    crate::title_bar::enable(hwnd);
                    let wake = window.clone();
                    crate::title_bar::on_change(move || wake.request_redraw());
                } else {
                    crate::title_bar::disable(hwnd);
                }
            }
            self.title_bar_on = wants;
        }
        let next = if self.title_bar_on {
            let scale = self.total_scale();
            let band = crate::title_bar::height() as f32 / scale;
            // What the content has on the line is its own; the rest moves the window.
            if let Some(ui) = &self.ui {
                let to_px = |r: frus_widgets::Rect| windows_sys::Win32::Foundation::RECT {
                    left: (r.x * scale).floor() as i32,
                    top: (r.y * scale).floor() as i32,
                    right: ((r.x + r.width) * scale).ceil() as i32,
                    bottom: ((r.y + r.height) * scale).ceil() as i32,
                };
                let interactive = ui
                    .hit_rects()
                    .filter(|r| r.y < band && r.width < self.logical_width())
                    .map(to_px)
                    .collect();
                let icon = ui
                    .title_bar_regions()
                    .iter()
                    .find(|(_, role)| *role == frus_widgets::TitleBarRole::Icon)
                    .map(|(r, _)| to_px(*r));
                crate::title_bar::publish(interactive, icon);
            }
            // SAFETY: as above.
            let buttons = unsafe { crate::title_bar::buttons(hwnd) }.map(|r| {
                frus_widgets::Rect::new(
                    r.left as f32 / scale,
                    r.top as f32 / scale,
                    (r.right - r.left) as f32 / scale,
                    (r.bottom - r.top) as f32 / scale,
                )
            });
            let button = |code: u32| {
                use windows_sys::Win32::UI::WindowsAndMessaging::{
                    HTCLOSE, HTMAXBUTTON, HTMINBUTTON,
                };
                match code {
                    HTMINBUTTON => Some(frus_widgets::CaptionButton::Minimize),
                    HTMAXBUTTON => Some(frus_widgets::CaptionButton::Maximize),
                    HTCLOSE => Some(frus_widgets::CaptionButton::Close),
                    _ => None,
                }
            };
            let (hovered, pressed) = crate::title_bar::buttons_state();
            if self.window_icon.is_none() {
                self.window_icon = self
                    .app
                    .icon()
                    .png()
                    .map(|png| &*Box::leak(png.to_vec().into_boxed_slice()));
            }
            // The caption the system would draw: dark as the window's own, which follows the
            // system's apps (milestone 642).
            let active = window.has_focus();
            let dark = window.theme() == Some(winit::window::Theme::Dark);
            let (background, foreground) = crate::title_bar::caption_colors(dark, active);
            Some(frus_widgets::TitleBar {
                // The line ends where the system's buttons do: maximized, the window's
                // resizing border is off the screen and the buttons sit higher, and the words
                // centred in the line stay level with them (milestone 643).
                height: buttons.map_or(band, |b| (b.y + b.height).clamp(1.0, band)),
                leading: 0.0,
                buttons,
                icon: self.window_icon,
                hovered: button(hovered),
                pressed: button(pressed),
                maximized: window.is_maximized(),
                active,
                background: Some(background),
                foreground: Some(foreground),
                // The system shows its own caption through a see-through frame, where it
                // paints a backdrop on the line (milestone 643).
                system_paints: self.renderer.as_ref().is_some_and(Renderer::sees_through)
                    // SAFETY: as above.
                    && unsafe { crate::title_bar::system_backdrop(hwnd, dark) },
            })
        } else {
            None
        };
        if next != self.title_bar {
            log::debug!(
                target: "frus::title_bar",
                "the line: {:?}",
                next.map(|line| (line.height, line.buttons, line.active, line.system_paints))
            );
            self.title_bar = next;
            self.build_dirty = true;
            self.request_redraw();
        }
    }

    /// The current layout direction; RTL flips both the layout and the gestures.
    fn is_rtl(&self) -> bool {
        self.themes.displayed(&self.app).direction.is_rtl()
    }

    /// The window's **logical** width, in px, for the edge thresholds.
    fn logical_width(&self) -> f32 {
        let scale = self.total_scale();
        self.window
            .as_ref()
            .map(|w| w.inner_size().width as f32 / scale)
            .unwrap_or(1.0)
            .max(1.0)
    }

    fn request_redraw(&self) {
        if let Some(window) = &self.window {
            window.request_redraw();
        }
    }

    /// The **normalised** pointer input (gesture tier 0): mouse and touch converge
    /// here, with an explicit `Cancel`. The long-press recogniser is fed along the way,
    /// and the loop is woken at its deadline.
    fn pointer(&mut self, event_loop: &ActiveEventLoop, event: PointerEvent) {
        self.pointer_event(event);
        // Wake the loop exactly at the next deadline, and rest otherwise.
        event_loop.set_control_flow(self.idle_control_flow());
    }

    /// Everything [`pointer`](Self::pointer) does with an event but wake the loop: the one
    /// place a press, a movement and a release are routed, and so what a test drives. The
    /// regions the pointer is in are brought up to date after it (milestone 583).
    fn pointer_event(&mut self, event: PointerEvent) {
        let kind = event.kind;
        // The raw events first, against the frame the pointer is over: a listener hears the
        // press before anything it leads to rebuilds the tree (milestone 586).
        self.cursor = event.position;
        self.route_listeners(kind, event.touch);
        self.route_pointer_event(event);
        self.pointer_held = match kind {
            PointerKind::Down => true,
            PointerKind::Up | PointerKind::Cancel => false,
            PointerKind::Move => self.pointer_held,
        };
        self.sync_regions(kind == PointerKind::Move);
    }

    /// Routes one pointer event: see [`pointer_event`](Self::pointer_event).
    fn route_pointer_event(&mut self, event: PointerEvent) {
        self.cursor = event.position;
        self.hover.event(event.kind, event.position, event.touch);
        // Whether the gesture under way could still end as a tap, before this event moves
        // it on: the press is shared with it until it cannot (milestone 534).
        let could_tap = gesture_was_a_tap(self.drag.as_ref());
        match event.kind {
            PointerKind::Down => {
                // What is under the pointer **now**: a finger has no move before its
                // press, and a press only shows while it is also the hovered widget.
                self.sync_hover();
                // A pointer interaction: the keyboard focus ring fades away.
                self.runtime.focus_visible = false;
                self.pointer_down(event.touch);
                let (long_press, lift) = hold_candidates(
                    self.drag.as_ref(),
                    self.ui.as_ref(),
                    self.tree.as_deref(),
                    self.cursor,
                );
                self.long_press_msg = long_press;
                self.pending_lift = lift;
                let interested = self.long_press_msg.is_some()
                    || self.pending_lift.is_some()
                    || self.pending_reorder.is_some()
                    || self.pending_word.is_some()
                    || self.pending_region_hold;
                self.press.down(self.cursor, Instant::now(), interested);
            }
            PointerKind::Move => {
                self.press.moved(self.cursor);
                self.pointer_move();
                // The inspector follows the pointer to highlight, so it redraws even
                // over inert widgets, which have no hover animation.
                if self.inspector {
                    self.request_redraw();
                }
            }
            PointerKind::Up => {
                // The recogniser is always told, but a lifted item owes a drop: the
                // long press that started it must not also eat its ending.
                let swallow = self.press.up();
                self.pending_lift = None;
                self.pending_reorder = None;
                self.pending_word = None;
                self.pending_region_hold = false;
                // A row lifted by the hold owes its drop for the same reason a lifted
                // item does: the release is what says where it goes.
                if swallow
                    && !matches!(
                        self.drag,
                        Some(Drag::Item { moved: true, .. } | Drag::Reorder { moved: true, .. })
                    )
                {
                    // The long press evicted the tap, so the release is swallowed.
                    self.drag = None;
                    self.runtime.input.pressed = None;
                    self.request_redraw();
                } else {
                    self.pointer_up();
                }
            }
            PointerKind::Cancel => {
                self.press.cancel();
                self.pending_lift = None;
                self.pending_reorder = None;
                self.pending_word = None;
                self.pending_region_hold = false;
                // A cancelled gesture still owes the offset back, or the region
                // would stay frozen under a finger that is no longer there.
                if let Some(Drag::Dismiss { item, .. }) = self.drag {
                    // A cancelled swipe asks for nothing: zero velocity puts it back.
                    self.runtime.dismiss_release(
                        item.id,
                        0.0,
                        0.0,
                        item.spec.axis,
                        // Unreachable threshold: a cancel never dismisses, however far
                        // the item had already travelled.
                        f32::INFINITY,
                    );
                }
                // A value a cancelled drag held settles back, and says nothing.
                if let Some(Drag::Gesture { id, .. }) = self.drag {
                    self.runtime.release_value(id);
                }
                if let Some(Drag::Scroll { id, .. }) = self.drag {
                    self.runtime.release_scroll(id);
                    self.runtime.glow_scroll_end(id);
                    // A cancelled gesture asks for nothing: the indicator slides back
                    // rather than promising a refresh nobody requested.
                    if let Some(host) = self.refresh_host_of(id) {
                        self.runtime.refresh_cancel(host);
                    }
                }
                // A sheet under a cancelled finger settles from where it was left.
                let sheet = match self.drag {
                    Some(Drag::Sheet { id, available, .. }) => self
                        .ui
                        .as_ref()
                        .and_then(|ui| ui.sheet(id))
                        .map(|sheet| (sheet.id, sheet.spec.clone(), available)),
                    Some(Drag::Scroll { id, .. }) => self
                        .ui
                        .as_ref()
                        .and_then(|ui| ui.sheet_holding(id))
                        .map(|sheet| (sheet.id, sheet.spec.clone(), sheet.available)),
                    _ => None,
                };
                if let Some((id, spec, available)) = sheet {
                    self.runtime.sheet_release(id, &spec, available, 0.0, None);
                }
                self.drag = None;
                self.runtime.input.pressed = None;
                self.request_redraw();
            }
        }
        // A press a gesture has taken, or one whose pointer has gone, is let go of — after
        // the routing, which is what reads it (milestone 534).
        if settle_press(
            &mut self.runtime.input,
            event.kind,
            could_tap,
            self.drag.as_ref(),
            event.touch,
        ) {
            self.request_redraw();
        }
        // After the release has been routed — it reads the press, not the hover — a
        // finger that has lifted stops hovering (milestone 505).
        if matches!(event.kind, PointerKind::Up | PointerKind::Cancel) {
            self.sync_hover();
        }
    }

    /// A press held still for the long-press delay: what it was a candidate for is decided.
    fn hold_deadline_reached(&mut self) {
        // Two claims on one hold: a widget asking for a message, and an item asking
        // to be lifted. Serving both would do a discrete action *and* start a drag
        // from the same gesture, which is never what anyone meant. **The lift
        // wins** — it changes what the rest of the gesture means, and the message
        // would be acting on something the finger is still holding.
        let lifting = self.pending_lift.is_some() || self.pending_reorder.is_some();
        // A hold in a text field selects the word under the finger (milestone 511),
        // and is that — not also the long press of whatever the field sits in.
        let word = self.pending_word.take();
        // A hold on words in a selection area selects the word, unless something held asked
        // for the hold first: a lift, a field, a widget's own long press.
        let region = std::mem::take(&mut self.pending_region_hold)
            && !lifting
            && word.is_none()
            && self.long_press_msg.is_none();
        if let Some(message) = self.long_press_msg.take() {
            if !lifting && word.is_none() {
                self.dispatch(message);
            }
        }
        if let Some(id) = word {
            self.select_held_word(id);
        }
        if region && self.select_region_word_held() {
            // The page under the finger stops being scrolled by it: the hold was a selection.
            if let Some(Drag::Scroll { id, .. }) = self.drag {
                self.runtime.release_scroll(id);
            }
        }
        let lift = self.pending_lift.take();
        let reorder = self.pending_reorder.take();
        // The scroll hands the gesture over to what the hold lifted.
        if lift.is_some() || reorder.is_some() {
            if let Some(Drag::Scroll { id, .. }) = self.drag {
                self.runtime.release_scroll(id);
            }
        }
        self.drag = drag_after_hold(self.drag.take(), lift, reorder, self.cursor);
        if matches!(self.drag, Some(Drag::Reorder { .. })) {
            self.reorder_x = self.cursor.x;
            self.reorder_y = self.cursor.y;
        }
        self.request_redraw();
    }

    /// The loop's idle policy: wake at the **nearest** deadline — the long press, the
    /// live-reload poll, the caret's next turn — and otherwise wait outright.
    fn idle_control_flow(&self) -> ControlFlow {
        let press = self.press.deadline();
        let reload = self.reload.as_ref().map(|w| w.deadline());
        // Twice a second while a field has the caret and the window is in front, and never
        // otherwise (milestone 513).
        let caret = (self.lifecycle == Lifecycle::Resumed)
            .then(|| self.caret.next_toggle(Instant::now()))
            .flatten();
        // A first tap that may still become a double tap is sent when its wait is over.
        let tap = self.pending_tap.as_ref().map(|p| p.at + DOUBLE_TAP_TIMEOUT);
        match [press, reload, caret, tap].into_iter().flatten().min() {
            Some(at) => ControlFlow::WaitUntil(at),
            None => ControlFlow::Wait,
        }
    }

    /// The focused field's caret, as its blink sees it: which field, where its caret and
    /// selection are, and a digest of its value. `None` when what has focus takes no
    /// typing, which has no caret to blink.
    fn caret_signature(&self) -> Option<crate::caret::Signature> {
        use std::hash::{Hash, Hasher};
        let field = self.runtime.input.focused?;
        let widget = find_widget(self.tree.as_ref()?.as_ref(), field)?;
        let text = widget.text_value()?;
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        text.hash(&mut hasher);
        Some(crate::caret::Signature {
            field,
            edit: self.runtime.edits.get(&field).copied().unwrap_or_default(),
            value: hasher.finish(),
        })
    }

    /// Pointer movement, mouse or finger: continues a drag under way, and otherwise
    /// updates the hover.
    fn pointer_move(&mut self) {
        if self.drag.is_some() {
            self.handle_drag();
            return;
        }
        let hovered = self.sync_hover();
        // The system cursor follows the hovered sub-region (milestone 205): a hand
        // over a clickable icon, and so on. Recomputed on every move, since the
        // sub-region can change without the hovered widget changing.
        self.update_cursor_icon(hovered);
    }

    /// Asks the frame what is under the hovering pointer, and records it.
    ///
    /// The only way the hover changes, so it can never name a widget of another frame:
    /// an id is a position in the tree, and the same position on the next screen is a
    /// different widget (milestone 505).
    fn sync_hover(&mut self) -> Option<WidgetId> {
        let hovered = self.ui.as_ref().and_then(|ui| self.hover.target(ui));
        if hovered != self.runtime.input.hovered {
            self.runtime.input.hovered = hovered;
            self.request_redraw();
        }
        hovered
    }

    /// Whether work a component started has brought something since this shell last looked
    /// (milestone 585).
    fn take_task_arrivals(&mut self) -> bool {
        let now = frus_widgets::task_arrivals();
        std::mem::replace(&mut self.task_arrivals, now) != now
    }

    /// Hands one raw pointer event to the widgets that hear them (milestone 586): a press to
    /// every one under the pointer, the innermost first, which then hear that pointer until
    /// it lifts, wherever it goes; a mouse moving with nothing held, to those under it.
    fn route_listeners(&mut self, kind: PointerKind, touch: bool) {
        use frus_widgets::ListenerEventKind as Raw;
        let at = self.cursor;
        let heard: Vec<(WidgetId, Rect, Raw)> = match kind {
            PointerKind::Down => {
                self.captured = self
                    .ui
                    .as_ref()
                    .map(|ui| ui.pointer_listeners_at(at))
                    .unwrap_or_default();
                self.captured
                    .iter()
                    .map(|(id, rect)| (*id, *rect, Raw::Down))
                    .collect()
            }
            PointerKind::Move if self.pointer_held => self
                .captured
                .iter()
                .map(|(id, rect)| (*id, *rect, Raw::Move))
                .collect(),
            PointerKind::Move if !touch => self
                .ui
                .as_ref()
                .map(|ui| ui.pointer_listeners_at(at))
                .unwrap_or_default()
                .into_iter()
                .map(|(id, rect)| (id, rect, Raw::Hover))
                .collect(),
            PointerKind::Move => Vec::new(),
            PointerKind::Up | PointerKind::Cancel => {
                let raw = if kind == PointerKind::Up {
                    Raw::Up
                } else {
                    Raw::Cancel
                };
                std::mem::take(&mut self.captured)
                    .into_iter()
                    .map(|(id, rect)| (id, rect, raw))
                    .collect()
            }
        };
        let messages: Vec<A::Message> = heard
            .into_iter()
            .flat_map(|(id, rect, kind)| {
                let event = frus_widgets::ListenerEvent {
                    kind,
                    local: Point::new(at.x - rect.x, at.y - rect.y),
                    touch,
                };
                self.tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), id))
                    .map(|widget| widget.on_pointer_event(event))
                    .unwrap_or_default()
            })
            .collect();
        for message in messages {
            self.dispatch(message);
            self.request_redraw();
        }
    }

    /// Brings the regions the pointer is in up to date (milestone 583): an exit for each it has
    /// left, innermost first, an enter for each it has come into, outermost first, and — when
    /// the pointer `moved` with nothing held — a move for each it is still in.
    fn sync_regions(&mut self, moved: bool) {
        let point = self.hover.at();
        let now: Vec<(WidgetId, Rect)> = match (point, self.ui.as_ref()) {
            (Some(point), Some(ui)) => ui
                .hover_regions_at(point)
                .into_iter()
                .map(|(id, rect, _)| (id, rect))
                .collect(),
            _ => Vec::new(),
        };
        let at = point.unwrap_or(self.cursor);
        let local = |rect: Rect| Point::new(at.x - rect.x, at.y - rect.y);
        let before = std::mem::replace(&mut self.entered, now.clone());
        let mut events = Vec::new();
        for (id, rect) in &before {
            if !now.iter().any(|(n, _)| n == id) {
                events.push((
                    *id,
                    frus_widgets::HoverEvent::Exit {
                        local: local(*rect),
                    },
                ));
            }
        }
        for (id, rect) in now.iter().rev() {
            if !before.iter().any(|(b, _)| b == id) {
                events.push((
                    *id,
                    frus_widgets::HoverEvent::Enter {
                        local: local(*rect),
                    },
                ));
            } else if moved && !self.pointer_held {
                events.push((
                    *id,
                    frus_widgets::HoverEvent::Move {
                        local: local(*rect),
                    },
                ));
            }
        }
        let messages: Vec<_> = events
            .into_iter()
            .filter_map(|(id, event)| {
                self.tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), id))
                    .and_then(|widget| widget.on_hover_event(event))
            })
            .collect();
        for message in messages {
            self.dispatch(message);
            self.request_redraw();
        }
    }

    /// The cursor to show: what the widget under the pointer asks for, `requested`, first;
    /// then the text cursor over a field that can be focused, as a platform shows it; then
    /// the innermost region the pointer is in that asks for one (milestone 583); otherwise
    /// the default.
    fn region_cursor(&self, requested: Option<UiCursor>) -> UiCursor {
        requested
            .or_else(|| {
                let point = self.hover.at()?;
                let (id, _) = self.ui.as_ref()?.focus_hit(point)?;
                let widget = find_widget(self.tree.as_ref()?.as_ref(), id)?;
                is_text_field(widget).then_some(UiCursor::Text)
            })
            .or_else(|| {
                self.hover.at().and_then(|point| {
                    self.ui
                        .as_ref()?
                        .hover_regions_at(point)
                        .into_iter()
                        .find_map(|(_, _, region)| region.cursor)
                })
            })
            .unwrap_or(UiCursor::Default)
    }

    /// Applies the cursor shape the hovered widget asks for at the pointer's local
    /// position (milestone 205), and the default cursor otherwise. Translates
    /// `frus_widgets::Cursor` into winit's.
    fn update_cursor_icon(&mut self, hovered: Option<WidgetId>) {
        let requested = hovered.and_then(|id| {
            let rect = self.ui.as_ref()?.widget_rect(id)?;
            let widget = find_widget(self.tree.as_ref()?.as_ref(), id)?;
            widget.cursor_icon(
                self.cursor.x - rect.x,
                self.cursor.y - rect.y,
                rect.width,
                rect.height,
            )
        });
        let shown = self.region_cursor(requested);
        if let Some(window) = &self.window {
            window.set_cursor_visible(shown != UiCursor::None);
            window.set_cursor(cursor_icon(shown));
        }
        // Sub-region highlighting (milestone 208): the pointer's position is retained
        // while it hovers an interactive sub-region, that is, while cursor_icon answered.
        // A change repaints — the status hash includes hover_cursor — so the halo
        // follows the pointer or goes away.
        let hover_cursor = requested.map(|_| self.cursor);
        if hover_cursor != self.runtime.input.hover_cursor {
            self.runtime.input.hover_cursor = hover_cursor;
            self.request_redraw();
        }
    }

    /// A pointer press, mouse or finger, at `self.cursor`. `touch` enables finger
    /// scrolling when no other gesture captures the press.
    fn pointer_down(&mut self, touch: bool) {
        self.pointer_touch = touch;
        // A first tap still waiting for its second is a tap after all if this press is not
        // that second one: somewhere else, or too late.
        self.poll_pending_tap(Instant::now());
        if let Some(pending) = self.pending_tap.as_ref() {
            let here = self.ui.as_ref().and_then(|ui| ui.hit(self.cursor));
            let (dx, dy) = (
                self.cursor.x - pending.position.x,
                self.cursor.y - pending.position.y,
            );
            if here != Some(pending.id) || dx.hypot(dy) > DOUBLE_TAP_SLOP {
                self.flush_pending_tap();
            }
        }
        self.pending_word = None;
        self.pending_region_hold = false;
        // A press **on the bar** comes first: the bar is drawn over everything, the handles
        // included, and the desktop menu hangs from the selection's top, over its handles
        // (milestone 618). It acts on the focused field, so nothing here may touch the
        // focus, the selection or the handles: it is only recorded, and `pointer_up`
        // resolves it to the button's action.
        if self
            .ui
            .as_ref()
            .is_some_and(|ui| ui.toolbar_contains(self.cursor))
        {
            press_at(&mut self.runtime, self.ui.as_ref(), self.cursor);
            self.request_redraw();
            return;
        }
        // Then a selection handle. It hangs below its line, over whatever is drawn
        // there, so nothing else may claim the press before it; and any other press puts
        // the handles away (milestone 511).
        // A selection area's handle likewise: a press on one widens or narrows the selection
        // rather than putting it away.
        if let Some(drag) = self.grab_region_handle() {
            self.drag = Some(drag);
            if let Some(selection) = self.runtime.region.as_mut() {
                selection.bar = false;
            }
            self.request_redraw();
            return;
        }
        if let Some(drag) = self.grab_selection_handle() {
            self.drag = Some(drag);
            // The bar is put away while a handle is dragged, and comes back when it is let
            // go (`pointer_up`): a bar that followed a moving selection would flicker.
            self.runtime.selection_toolbar = None;
            self.request_redraw();
            return;
        }
        if self.runtime.selection_handles.take().is_some() {
            self.request_redraw();
        }
        self.hide_selection_toolbar();
        // A selection an area holds goes with any press: the one that begins another puts a
        // new one in its place, below.
        if self.runtime.region.take().is_some() {
            self.request_redraw();
        }
        // 0) The back gesture: a press on the **leading edge** — left under LTR,
        // right under RTL — if the app allows it. It takes the pages back, so it starts on
        // them and not on what is above them: the window's menu bar, whose first word sits
        // in the edge, or an overlay — the menu it opens, a dialog (milestone 642).
        let above_the_pages = self.ui.as_ref().is_some_and(|ui| {
            ui.over_overlay(self.cursor)
                || ui
                    .title_bar_row()
                    .is_some_and(|row| row.contains(self.cursor))
        });
        let on_back_edge = !above_the_pages
            && if self.is_rtl() {
                self.cursor.x > self.logical_width() - BACK_EDGE
            } else {
                self.cursor.x < BACK_EDGE
            };
        if on_back_edge && self.app.can_go_back() {
            self.drag = Some(Drag::Back {
                start_x: self.cursor.x,
            });
            self.begin_gesture();
            self.build_dirty = true;
            self.app.back_gesture(0.0);
            self.request_redraw();
            return;
        }

        // 1) Is this a scrollbar drag?
        if let Some(bar) = self.ui.as_ref().and_then(|ui| ui.scrollbar_at(self.cursor)) {
            let (along, thumb_start) = if bar.vertical {
                (self.cursor.y, bar.thumb.y)
            } else {
                (self.cursor.x, bar.thumb.x)
            };
            self.drag = Some(Drag::Scrollbar {
                id: bar.id,
                vertical: bar.vertical,
                grab: along - thumb_start,
                track_start: bar.track_start,
                track_len: bar.track_len,
                thumb_len: bar.thumb_len,
                max: bar.max,
                reverse: bar.reverse,
            });
            self.request_redraw();
            return;
        }

        // 1b) Is this a draggable widget, a Slider for instance?
        if let Some((id, rect)) = self.ui.as_ref().and_then(|ui| ui.draggable_at(self.cursor)) {
            let (x, rtl) = (self.cursor.x, self.is_rtl());
            let track = self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), id))
                .map_or(frus_widgets::DragTrack::WHOLE, |widget| widget.drag_track());
            let active = track.engages(rect, x, rtl);
            let thumbs = matches!(track.mode, frus_widgets::DragMode::Thumbs { .. });
            let thumb = track.pick_thumb(rect, x, 0.0, rtl);
            self.drag = Some(Drag::Widget {
                id,
                rect,
                last_x: x,
                press_x: x,
                track,
                active,
                thumb,
            });
            if thumbs {
                // Two thumbs: the one the press took jumps to it, as one alone would.
                if let Some(thumb) = thumb {
                    let at = track.fraction(rect, x, rtl);
                    self.thumb_drag(id, thumb, frus_widgets::ThumbDrag::Start, at);
                    self.thumb_drag(id, thumb, frus_widgets::ThumbDrag::Move, at);
                }
            } else if active {
                // The bracket opens **before** the first value: an application that means
                // to hold the expensive work until the finger lifts has to know the finger
                // went down first, and a press that jumps the value straight away would
                // otherwise deliver the change before the start.
                self.dispatch_drag_edge(id, Edge::Start, 0.0);
                // A zero delta on press: only a slider whose press moves it jumps.
                self.apply_widget_drag(id, 0.0, track.value_at(rect, x, x, false, rtl));
            }
            self.request_redraw();
            return;
        }

        // 1c) A reorder: a press on a reorderable — a table header, a Kanban card, a
        // list's grip. We do not `return` — focus and `pressed`, where a tap means sort,
        // are settled below; the drag engages only past the threshold, and otherwise the
        // release sorts.
        //
        // A row that asked for a **hold** takes nothing now. The press is left to
        // whatever else wants it, which inside a list is the scroll, and the deadline
        // below decides between them: a finger that stays put was never scrolling.
        if let Some((id, from, hold)) = self.reorderable_at(self.cursor) {
            if hold {
                self.pending_reorder = Some((id, from, self.cursor));
            } else {
                self.drag = Some(Drag::Reorder {
                    id,
                    from,
                    start: self.cursor,
                    moved: false,
                    carried: None,
                });
                self.reorder_x = self.cursor.x; // starts glued to the pointer, with no jerk
                self.reorder_y = self.cursor.y; // likewise for the vertical insertion line
            }
        }

        if press_at(&mut self.runtime, self.ui.as_ref(), self.cursor) {
            self.request_redraw();
        }
        // 2) Focus and caret placement, and the start of a text selection.
        let previously_focused = self.runtime.input.focused;
        let focus = self.ui.as_ref().and_then(|ui| ui.focus_hit(self.cursor));
        // A press outside the focused widget tells it so, before the focus moves
        // (milestone 660).
        if let Some(held) = previously_focused {
            let inside = focus.is_some_and(|(id, _)| id == held);
            let outside = (!inside)
                .then(|| {
                    self.tree
                        .as_ref()
                        .and_then(|tree| find_widget(tree.as_ref(), held))
                        .and_then(|widget| widget.on_tap_outside())
                })
                .flatten();
            if let Some(message) = outside {
                self.dispatch(message);
            }
        }
        self.runtime.input.focused = focus.map(|(id, _)| id);
        if let Some((id, rect)) = focus {
            let local_x = self.cursor.x - rect.x;
            // The retained vertical scroll, in a multi-line field, is part of the
            // content coordinate: we add it so the click lands on the right line.
            let local_y =
                self.cursor.y - rect.y + self.runtime.scroll.get(&id).map(|s| s.1).unwrap_or(0.0);
            // The scroll shown just before this click, computed from the current caret
            // when the field was already focused, and 0 otherwise.
            let scroll_cursor = if previously_focused == Some(id) {
                self.runtime.edits.get(&id).map(|e| e.cursor).unwrap_or(0)
            } else {
                0
            };
            // Only **text fields** (`cursor_at` → `Some`) start a selection; the other
            // focusables — buttons, checkboxes — keep focus but must NOT capture the
            // click, which would otherwise be swallowed on release as the end of a drag.
            let cursor = self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), id))
                .and_then(|widget| widget.cursor_at(local_x, local_y, rect.width, scroll_cursor));
            if let Some(cursor) = cursor {
                // Placing the caret with the mouse forgets the vertical goal column.
                self.goal_x = None;
                self.runtime.edits.insert(
                    id,
                    Edit {
                        cursor,
                        anchor: None,
                        composing: None,
                    },
                );
                self.drag = Some(Drag::TextSelect { id, rect });
                // A finger that stays put selects the word instead (milestone 511).
                if touch {
                    self.pending_word = Some(id);
                }
                // The caret moved, so the run of typing ends here: typing at one place,
                // then at another, then Ctrl+Z should take back only the second.
                self.runtime.close_edit_run(id);
                // Tapping in a field **reopens** the keyboard, even one the app already
                // considers shown but which the system back closed — see
                // `request_soft_input`.
                self.request_soft_input();

                // A double click selects the word under the pointer.
                let now = Instant::now();
                let double = self
                    .last_click_time
                    .map(|t| (now - t).as_secs_f32() < 0.4)
                    .unwrap_or(false);
                self.last_click_time = Some(now);
                if double {
                    if let Some((start, end)) = self
                        .tree
                        .as_ref()
                        .and_then(|tree| find_widget(tree.as_ref(), id))
                        .and_then(|widget| widget.word_at(cursor))
                    {
                        self.runtime.edits.insert(
                            id,
                            Edit {
                                cursor: end,
                                anchor: Some(start),
                                composing: None,
                            },
                        );
                        self.drag = None;
                    }
                }
            }
        }

        // 2b) Words in a selection area, with nothing else having a claim on the press: a
        // selection begins, and may be dragged across the texts of the area. A finger is
        // left to scroll, and a finger that stays put selects the word instead (milestone 576).
        if self.drag.is_none() && focus.is_none() {
            if touch {
                self.pending_region_hold = self.region_press_target().is_some();
            } else {
                self.begin_region_selection();
            }
        }

        // 3) Touch: when nothing captured the gesture — no scrollbar, no widget, no
        // text selection — prepare a finger scroll on the area under the finger. A
        // release without movement, under TOUCH_SLOP, stays a tap.
        if touch && self.drag.is_none() {
            // The innermost area that would actually take a finger. An area whose content
            // fits refuses the offset outright — the reference takes its drag recognisers
            // away for exactly this — so it neither swallows the press nor lights an edge,
            // and the page behind it, or a dismissible row under it, gets its turn.
            let landed = {
                let scroll = &self.runtime.scroll;
                self.ui.as_ref().and_then(|ui| {
                    ui.scroll_chain(self.cursor).find(|area| {
                        area.accepts_user_offset(
                            scroll.get(&area.id).copied().unwrap_or((0.0, 0.0)),
                        )
                    })
                })
            };
            if let Some(area) = landed {
                // A finger back on the content catches it: the fling stops where it
                // is rather than sliding under the finger, and hands the next
                // release whatever momentum the platform lets a swipe build on.
                let physics = area.physics;
                let carried = self.runtime.catch_scroll_fling(area.id, physics);
                // The offset belongs to the finger until it lifts.
                self.runtime.hold_scroll(area.id);
                // And so does the sheet it sits in, if one is still settling: the finger
                // may be about to move it, and a sheet sliding away under a finger that
                // has caught its list is a sheet that ignored the catch.
                if let Some(sheet) = self
                    .ui
                    .as_ref()
                    .and_then(|ui| ui.sheet_holding(area.id))
                    .map(|sheet| sheet.id)
                {
                    self.runtime.sheet_hold(sheet);
                }
                self.drag = Some(Drag::Scroll {
                    id: area.id,
                    last: self.cursor,
                    moved: false,
                    carried,
                    dismiss: self
                        .ui
                        .as_ref()
                        .and_then(|ui| ui.dismissable_at(self.cursor)),
                    axis: None,
                    pan: self.pan_target(),
                });
                self.begin_gesture();
                // A fling on a scroll area is read the way its scroll behaviour reads one
                // (milestone 616), as the reference's scrollable builds its recognizer.
                self.gesture_velocity = area.velocity_tracker();
            }
        }

        // 3a) A sheet's panel with nothing under the finger that scrolls: the finger moves
        // the sheet itself. A pointer too — on a desktop there is no other way to raise one.
        if self.drag.is_none() {
            if let Some((id, available)) = self
                .ui
                .as_ref()
                .and_then(|ui| ui.sheet_at(self.cursor))
                .map(|sheet| (sheet.id, sheet.available))
            {
                self.runtime.sheet_hold(id);
                self.drag = Some(Drag::Sheet {
                    id,
                    last: self.cursor,
                    moved: false,
                    available,
                });
                self.begin_gesture();
            }
        }

        // 3b) A dismissible item with nothing scrollable under it: there is no gesture to
        // arbitrate against, so the swipe is prepared directly. It still waits for the
        // threshold, or a tap on the row would start sliding it.
        if self.drag.is_none() {
            if let Some(item) = self
                .ui
                .as_ref()
                .and_then(|ui| ui.dismissable_at(self.cursor))
            {
                self.drag = Some(Drag::Dismiss {
                    item,
                    last: self.cursor,
                    moved: false,
                });
                self.begin_gesture();
            }
        }

        // 3c) A draggable item, when nothing above has taken the gesture. It comes
        // **after** the touch scroll on purpose: a widget that took every drag inside a
        // list would silently stop that list scrolling, and a list that does not scroll
        // is a worse bug than an item that does not lift. With a pointer there is no
        // touch scroll to lose to, so it lifts everywhere.
        if self.drag.is_none() {
            if let Some(source) = self
                .ui
                .as_ref()
                .and_then(|ui| ui.drag_source_at(self.cursor))
                .filter(|source| {
                    // One that asked for a hold waits for the deadline instead.
                    !self
                        .tree
                        .as_ref()
                        .and_then(|tree| find_widget(tree.as_ref(), source.id))
                        .is_some_and(|widget| widget.drag_needs_long_press())
                })
            {
                self.drag = Some(Drag::Item {
                    source,
                    start: self.cursor,
                    moved: false,
                    over: None,
                });
                self.begin_gesture();
            }
        }

        // 3d) A detector that takes a drag, with no scroll under it to share the gesture with
        // (milestone 582): prepared, and engaged past the slop, so a tap still goes through.
        if self.drag.is_none() {
            if let Some((id, axis)) = self.pan_target() {
                self.drag = Some(Drag::Gesture {
                    id,
                    axis,
                    start: self.cursor,
                    last: self.cursor,
                    moved: false,
                });
                self.begin_gesture();
            }
        }

        // 4) An interactive viewport (`InteractiveViewer`) under the pointer: prepare a
        // **pan**, with mouse or finger. Like the touch scroll it engages only past the
        // threshold, so a tap goes through to the child, a button for instance.
        if self.drag.is_none() {
            if let Some((id, viewport)) = self
                .ui
                .as_ref()
                .and_then(|ui| ui.interactive_at(self.cursor))
            {
                // The press stops a fling in progress: we take the content back in hand.
                self.runtime.interactive_velocity.remove(&id);
                self.drag = Some(Drag::Pan {
                    id,
                    last: self.cursor,
                    moved: false,
                    viewport,
                });
                self.begin_gesture();
            }
        }
        self.request_redraw();
    }

    /// A pointer release, mouse or finger: it ends a drag, or commits a click or tap
    /// when the release lands back on the widget that was pressed.
    /// What widget `id` emits for a click at the pointer on one of its sub-regions — see
    /// [`Widget::positional_click`]. Local coordinates are the pointer minus the widget's
    /// corner.
    fn positional_click_on(&self, id: WidgetId) -> Option<A::Message> {
        let rect = self.ui.as_ref()?.widget_rect(id)?;
        let widget = find_widget(self.tree.as_ref()?.as_ref(), id)?;
        widget.positional_click(
            self.cursor.x - rect.x,
            self.cursor.y - rect.y,
            rect.width,
            rect.height,
        )
    }

    fn pointer_up(&mut self) {
        let ended = self.drag.take();
        if let Some(Drag::Back { .. }) = ended {
            // The app decides — commit or cancel — from the velocity, which it wants
            // in **fractions of the screen** per second, not pixels.
            let sign = if self.is_rtl() { -1.0 } else { 1.0 };
            let velocity = sign * self.gesture_estimate().velocity.x / self.logical_width();
            self.build_dirty = true;
            self.app.back_gesture_end(velocity);
            self.request_redraw();
            return;
        }
        // A touch scroll, a pan or a swipe that never moved is a plain tap: we let it
        // follow the ordinary click path below.
        let was_tap = gesture_was_a_tap(ended.as_ref());
        // The bracket closes. A press that never moved still gets its end: it changed
        // the value once, and a caller that defers its expensive work until the release
        // would otherwise never be told the release happened.
        if let Some(Drag::Widget {
            id,
            rect,
            press_x,
            track,
            active: true,
            thumb,
            ..
        }) = ended
        {
            let rtl = self.is_rtl();
            if matches!(track.mode, frus_widgets::DragMode::Thumbs { .. }) {
                if let Some(thumb) = thumb {
                    let at = track.fraction(rect, self.cursor.x, rtl);
                    self.thumb_drag(id, thumb, frus_widgets::ThumbDrag::End, at);
                }
            } else {
                let released = track.released_at(rect, press_x, self.cursor.x, rtl);
                self.dispatch_drag_edge(id, Edge::End, released);
            }
        }
        // The keyboard is told where a dragged handle left the selection.
        #[cfg(android)]
        if let Some(Drag::SelectionHandle { id, .. }) = ended {
            self.push_ime_context(id);
        }
        if let Some(Drag::SelectionHandle { id, .. }) = ended {
            self.show_selection_toolbar(id);
        }
        // A handle of a selection area let go: its bar comes back over what is selected now.
        if let Some(Drag::RegionHandle { .. }) = ended {
            if let Some(selection) = self.runtime.region.as_mut() {
                selection.bar = true;
            }
        }
        // Reordering: on the drop, the target column is the reorderable header under
        // the pointer, and we route the grabbed header's `on_reorder(from, to)`.
        if let Some(Drag::Reorder {
            id,
            from,
            moved: true,
            carried,
            ..
        }) = &ended
        {
            let target = self.reorder_drop_target(*id, *from, *carried);
            let tree = self.tree.as_ref();
            let base = target
                .and_then(|tid| tree.and_then(|t| find_widget(t.as_ref(), tid)))
                .and_then(|widget| widget.reorder_index());
            // The **trailing** half of a hovered target that is inserted at — the lower
            // half down a list, the right half across one (the left, right to left) —
            // means inserting **after** it, index +1: the effective drop slot follows the
            // insertion line that was painted. No effect for `Table` columns, or off target.
            let to = match (base, target) {
                (Some(base), Some(tid)) => {
                    let after = self
                        .ui
                        .as_ref()
                        .and_then(|ui| ui.widget_rect(tid))
                        .map(|rect| self.reorder_insert_after(tid, rect))
                        .unwrap_or(false);
                    Some(base + after as usize)
                }
                _ => None,
            };
            // Dropping **onto itself** moves nothing, even in the lower half, where
            // `to = from + 1` would slip past the `to != from` guard — otherwise we would
            // emit a null move and announce it.
            let self_drop = target == Some(*id);
            let message = match to {
                Some(to) if to != *from && !self_drop => tree
                    .and_then(|t| find_widget(t.as_ref(), *id))
                    .and_then(|widget| widget.on_reorder(to)),
                _ => None,
            };
            if let Some(message) = message {
                let to = to.unwrap_or(*from);
                let widget = tree.and_then(|t| find_widget(t.as_ref(), *id));
                let axis = widget
                    .map(|w| w.reorder_axis())
                    .unwrap_or(ReorderAxis::Horizontal);
                // The move is spoken to the screen reader — the ghost's counterpart for
                // a blind user. A widget whose index **is** a position says so itself; a
                // `Kanban` card's is a flat `column × stride + position` that means
                // nothing read aloud, so the fallback speaks of the axis and gives no
                // number at all.
                let announcement = widget
                    .and_then(|w| w.reorder_announcement(to))
                    .unwrap_or_else(|| match axis {
                        ReorderAxis::Horizontal => format!("Column moved to position {}", to + 1),
                        ReorderAxis::Vertical => "Card moved".to_string(),
                    });
                self.dispatch(message);
                self.set_announcement(announcement);
            }
        }
        // Fling: the finger's momentum is handed to the area's physics, which
        // returns the motion that follows — a spline that stops at the edge, or
        // friction that hands over to a spring and bounces.
        // A swiped item: the release velocity decides between flying out and sliding
        // back, using the same fitted estimate a fling uses.
        if let Some(Drag::Dismiss { item, moved, .. }) = &ended {
            if *moved {
                let estimate = self.gesture_estimate();
                let horizontal = item.spec.axis.is_horizontal();
                let (along, across) = if horizontal {
                    (estimate.velocity.x, estimate.velocity.y)
                } else {
                    (estimate.velocity.y, estimate.velocity.x)
                };
                self.runtime.dismiss_release(
                    item.id,
                    along,
                    across,
                    item.spec.axis,
                    item.spec.threshold,
                );
                self.request_redraw();
                return;
            }
        }
        // A sheet let go of by its panel settles from wherever the finger left it — and
        // one only pressed settles too, since the press caught it if it was moving.
        if let Some(Drag::Sheet {
            id,
            moved,
            available,
            ..
        }) = &ended
        {
            let velocity = if *moved {
                -self.fling_velocity(self.gesture_estimate()).1
            } else {
                0.0
            };
            // Thrown by its handle, a sheet with one list in it carries that list on at the
            // top, as the reference's does: there its whole content is the list.
            let sheet = self.ui.as_ref().and_then(|ui| ui.sheet(*id)).map(|sheet| {
                let list = match sheet.areas.as_slice() {
                    [only] => Some(*only),
                    _ => None,
                };
                (sheet.spec.clone(), list)
            });
            if let Some((spec, list)) = sheet {
                self.runtime
                    .sheet_release(*id, &spec, *available, velocity, list);
            }
            if *moved {
                self.request_redraw();
                return;
            }
        }
        if let Some(Drag::Item {
            source,
            moved: true,
            over,
            ..
        }) = &ended
        {
            // The drop, then the source's own answer. In that order: an application
            // that reacts to both should see the thing arrive before it is told the
            // journey is over.
            self.runtime.drag_over = None;
            let accepted = over.is_some();
            let dropped = over.and_then(|id| {
                self.tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), id))
                    .and_then(|widget| widget.on_drop(source.payload))
            });
            let ended_msg = self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), source.id))
                .and_then(|widget| widget.on_dropped(accepted));
            for message in dropped.into_iter().chain(ended_msg) {
                self.dispatch(message);
            }
            self.request_redraw();
            return;
        }
        if let Some(Drag::Item { .. }) = &ended {
            // Lifted but never moved: nothing was dropped, and the click below still
            // has its say.
            self.runtime.drag_over = None;
        }
        // Set when a sheet takes the release of a list inside it, which then does not
        // fling as well (milestone 515).
        let mut sheet_took = false;
        if let Some(Drag::Scroll { id, .. }) = &ended {
            let sheet = self
                .ui
                .as_ref()
                .and_then(|ui| ui.sheet_holding(*id))
                .cloned();
            if let Some(sheet) = sheet {
                // In the sheet's terms, positive growing it: a list's offset grows the
                // same way, on an axis that is not reversed.
                let velocity = match &ended {
                    Some(Drag::Scroll {
                        moved: true,
                        axis: Some(true),
                        carried,
                        ..
                    }) => -self.fling_velocity(self.gesture_estimate()).1 + carried.1,
                    _ => 0.0,
                };
                let offset = self.runtime.scroll.get(id).map_or(0.0, |o| o.1);
                let size = self.runtime.sheet_size(sheet.id, &sheet.spec);
                sheet_took = velocity != 0.0
                    && frus_widgets::sheet_takes_release(
                        velocity,
                        offset,
                        size,
                        &sheet.spec,
                        sheet.available,
                    );
                // Whoever takes it, the sheet is let go of: settled by the throw, or
                // from where it is — which is a stop, whenever the list keeps the throw.
                self.runtime.sheet_release(
                    sheet.id,
                    &sheet.spec,
                    sheet.available,
                    if sheet_took { velocity } else { 0.0 },
                    Some(*id),
                );
            }
        }
        if let Some(Drag::Scroll { id, .. }) = &ended {
            // The finger gives the offset back before anything is flung at it.
            self.runtime.release_scroll(*id);
            // A pull held against an edge now fades at the "let go" rate.
            self.runtime.glow_scroll_end(*id);
            // And a pull-to-refresh gesture is answered: releasing it armed is the
            // whole point of the gesture, so the message goes out now rather than
            // after the indicator has finished settling.
            self.release_refresh(*id);
        }
        if let Some(Drag::Scroll {
            id,
            moved: true,
            carried,
            axis,
            ..
        }) = &ended
        {
            // In **scroll space**: the content moves opposite the finger — and along the
            // axis the gesture was claimed by, or the release would fling the way the drag
            // was not allowed to go.
            let estimate = self.gesture_estimate();
            let velocity = self.fling_velocity(estimate);
            // Through the same conversion the drag went through, so the release carries
            // on the way the finger was going — on a reversed axis too.
            let velocity = match self.ui.as_ref().and_then(|u| u.scroll_region(*id)) {
                Some(area) => area.offset_delta(velocity),
                None => (-velocity.0, -velocity.1),
            };
            // The momentum carried in from an interrupted fling is masked with the rest:
            // a gesture held to one axis must not launch along the other on the strength
            // of what the *previous* one was doing.
            let launch = (velocity.0 + carried.0, velocity.1 + carried.1);
            if sheet_took {
                self.request_redraw();
            } else {
                self.fling(
                    *id,
                    match axis {
                        Some(true) => (0.0, launch.1),
                        Some(false) => (launch.0, 0.0),
                        None => launch,
                    },
                );
            }
        }
        // A detector's drag let go: its end, with the velocity it was let go at (milestone
        // 582). One that never moved was a tap, and goes on to the click below.
        if let Some(Drag::Gesture {
            id,
            axis,
            moved: true,
            ..
        }) = &ended
        {
            let velocity = self.fling_velocity(self.gesture_estimate());
            let velocity = mask_pan(*axis, Point::new(velocity.0, velocity.1));
            // No faster than a finger can throw: the reference's `kMaxFlingVelocity`.
            let speed = velocity.x.hypot(velocity.y);
            let velocity = if speed > MAX_PAN_VELOCITY {
                let k = MAX_PAN_VELOCITY / speed;
                Point::new(velocity.x * k, velocity.y * k)
            } else {
                velocity
            };
            self.send_pan(*id, frus_widgets::PanEvent::End { velocity });
        }
        // A pan fling: the momentum launches the content, which `advance_interactive`
        // decelerates and bounds frame by frame.
        if let Some(Drag::Pan {
            id, moved: true, ..
        }) = &ended
        {
            let estimate = self.gesture_estimate();
            let velocity = self.fling_velocity(estimate);
            if velocity.0.hypot(velocity.1) > PAN_FLING_MIN {
                self.runtime.interactive_velocity.insert(*id, velocity);
            }
        }
        if ended.is_some() && !was_tap {
            self.request_redraw();
            return;
        }
        // A click only counts when press and release land on the same widget.
        let released = self.ui.as_ref().and_then(|ui| ui.hit(self.cursor));
        // A built-in button of the selection bar sends no message: the shell performs its
        // action on the field the bar is open on (milestone 568).
        let bar_action = match (self.runtime.input.pressed, released) {
            (Some(pressed), Some(released)) if pressed == released => {
                self.ui.as_ref().and_then(|ui| ui.edit_action_for(pressed))
            }
            _ => None,
        };
        let on_bar = self
            .ui
            .as_ref()
            .is_some_and(|ui| ui.toolbar_contains(self.cursor));
        // A field answers no tap of its own, so it is no hit target and `released` never
        // names it: its clickable suffix is asked through the focusable the press landed
        // on, when the release lands on it too. It wins over a tappable parent, the way
        // the inner target always does.
        let field_positional = if bar_action.is_some() {
            None
        } else {
            self.ui
                .as_ref()
                .and_then(|ui| ui.focus_hit(self.cursor))
                .map(|(id, _)| id)
                .filter(|id| self.runtime.input.focused == Some(*id))
                .and_then(|id| self.positional_click_on(id))
        };
        let (message, announce) = match (self.runtime.input.pressed, released) {
            (Some(_), Some(_)) if bar_action.is_some() => (None, None),
            _ if field_positional.is_some() => (field_positional, None),
            (Some(pressed), Some(released)) if pressed == released => {
                // A **positional** click, on a sub-region such as a chart's point, takes
                // priority over `on_click`.
                let positional = self.positional_click_on(released);
                let message =
                    positional.or_else(|| self.ui.as_ref().and_then(|ui| ui.msg_for(pressed)));
                // The spoken announcement of the effect — a sort, a selection — read off
                // the clicked widget before `dispatch` rebuilds the tree.
                let announce = self
                    .tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), pressed))
                    .and_then(|widget| widget.announce());
                (message, announce)
            }
            _ => (None, None),
        };
        // Something that takes a double tap: this tap is its second, or a first that waits.
        let message = match (self.runtime.input.pressed, released) {
            (Some(pressed), Some(released)) if pressed == released && bar_action.is_none() => {
                self.double_tap(pressed, message)
            }
            _ => message,
        };
        // The tap completed on the widget it started on: its ink finishes growing and
        // fades. Anything else leaves the splash unconfirmed, and `advance_ink` sweeps
        // it away quickly — the finger slid off, and the ink says so.
        if let (Some(pressed), Some(released)) = (self.runtime.input.pressed, released) {
            if pressed == released {
                self.runtime.ink_confirm(pressed);
            }
        }
        self.runtime.input.pressed = None;
        if let Some(action) = bar_action {
            self.perform_edit_action(action);
        } else if on_bar && message.is_some() {
            // An item of the application's own: it has sent its message, and the bar is
            // done with.
            self.runtime.selection_handles = None;
            self.hide_selection_toolbar();
        }
        if let Some(message) = message {
            self.dispatch(message);
            if let Some(announce) = announce {
                self.set_announcement(announce);
            }
        }
        self.request_redraw();
    }

    /// A tap on `id`, which answered `message`. If `id` also takes a double tap, the tap is
    /// either the second of one, and the double tap's message is sent in its place, or a
    /// first, which waits for [`DOUBLE_TAP_TIMEOUT`] before it is a tap (milestone 581).
    fn double_tap(&mut self, id: WidgetId, message: Option<A::Message>) -> Option<A::Message> {
        let Some(double) = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.on_double_tap())
        else {
            return message;
        };
        let now = Instant::now();
        let second = self.pending_tap.as_ref().is_some_and(|pending| {
            let (dx, dy) = (
                self.cursor.x - pending.position.x,
                self.cursor.y - pending.position.y,
            );
            pending.id == id
                && now.duration_since(pending.at) <= DOUBLE_TAP_TIMEOUT
                && dx.hypot(dy) <= DOUBLE_TAP_SLOP
        });
        if second {
            self.pending_tap = None;
            return Some(double);
        }
        self.flush_pending_tap();
        self.pending_tap = Some(PendingTap {
            id,
            at: now,
            position: self.cursor,
            single: message,
        });
        None
    }

    /// Sends the waiting first tap's own message, if one is waiting.
    fn flush_pending_tap(&mut self) {
        if let Some(message) = self.pending_tap.take().and_then(|pending| pending.single) {
            self.dispatch(message);
            self.request_redraw();
        }
    }

    /// The waiting first tap, sent if its wait is over by `now`. Whether one was.
    fn poll_pending_tap(&mut self, now: Instant) -> bool {
        let due = self
            .pending_tap
            .as_ref()
            .is_some_and(|pending| now.duration_since(pending.at) >= DOUBLE_TAP_TIMEOUT);
        if due {
            self.flush_pending_tap();
        }
        due
    }

    /// Speaks a message aloud through the screen reader's **live region**, for a
    /// column reorder and the like. With no screen reader running it costs nothing. The
    /// text is re-spoken only on a change. Desktop and web; a no-op on Android and iOS,
    /// which have no bridge yet.
    #[cfg(any(desktop, web))]
    fn set_announcement(&mut self, message: String) {
        self.announce = message;
    }
    #[cfg(not(any(desktop, web)))]
    fn set_announcement(&mut self, _message: String) {}

    /// Returning focus when an overlay closes: if the focused widget has **vanished**
    /// from the frame, a menu or modal having closed, focus goes back to the
    /// **trigger** — the most recent focusable in the history that is still present.
    /// Every transition is recorded along the way: the old focus, if still present,
    /// becomes a candidate trigger. The focus ring is drawn on the following frame
    /// (`request_redraw` when focus moved).
    fn reconcile_focus(&mut self) {
        let present: std::collections::HashSet<WidgetId> = match self.ui.as_ref() {
            Some(ui) => ui.focusable_ids().collect(),
            None => return,
        };
        // A widget that takes the focus on appearing, and has just appeared, takes it. The
        // focus it takes it from is recorded below as any move is, so it goes back there
        // when this one goes: a submenu closing hands it back to its row.
        let autofocus: Vec<WidgetId> = self
            .ui
            .as_ref()
            .map(|ui| ui.autofocus_ids().collect())
            .unwrap_or_default();
        let appeared = autofocus
            .iter()
            .find(|id| !self.autofocused.contains(id))
            .copied();
        self.autofocused = autofocus.into_iter().collect();
        if let Some(id) = appeared {
            self.runtime.input.focused = Some(id);
        }
        let before = self.runtime.input.focused;
        let after = resolve_focus(
            before,
            &present,
            &mut self.focus_history,
            &mut self.prev_focus,
        );
        if after != before || appeared.is_some() {
            self.runtime.input.focused = after;
            self.request_redraw();
        }
    }

    /// Tells the widgets **where the focus went** since they were last told (milestone 660):
    /// each one whose subtree it left or entered, through `Widget::on_focus_change`.
    fn report_focus(&mut self) {
        let now = self.runtime.input.focused;
        // Nothing moved, nothing to say — and no walk of the tree, which is the point: the
        // answer would be empty anyway.
        if now == self.focus_reported {
            return;
        }
        let before = std::mem::replace(&mut self.focus_reported, now);
        let messages = self
            .tree
            .as_ref()
            .map(|tree| focus_changes(tree.as_ref(), before, now))
            .unwrap_or_default();
        for message in messages {
            self.dispatch(message);
        }
    }

    /// Applies a message to the application, runs its effects, then re-evaluates the
    /// subscriptions, the state having possibly changed which ones should run.
    fn dispatch(&mut self, message: A::Message) {
        // The app may have changed state, so the `view` must be rebuilt.
        self.build_dirty = true;
        let command = self.app.update(message);
        self.run_command(command);
        let asked = self.app.effects();
        self.run_command(asked);
        #[cfg(web)]
        self.sync_address();
        #[cfg(any(desktop, android))]
        self.report_dev();
        self.sync_subscriptions();
    }

    /// The link the program was started with — on Android the activity's intent, on a desktop an
    /// argument — handed to the application as a location. Once, before the first frame.
    #[cfg(any(android, desktop))]
    fn open_launch_link(&mut self) {
        #[cfg(android)]
        let link = self
            .android_app
            .as_ref()
            .and_then(crate::android_link::launch_link);
        // A link on the command line, or where `frus run` restarted the application from.
        #[cfg(desktop)]
        let link = crate::link::link_among(std::env::args()).or_else(crate::dev::restore_link);
        if let Some(location) = link.as_deref().and_then(crate::link::location_of_link) {
            let command = self.app.open_location(&location);
            self.run_command(command);
        }
    }

    /// Opens the channel to `frus run`, when it started this application with one.
    #[cfg(any(android, desktop))]
    fn connect_dev(&mut self) {
        #[cfg(desktop)]
        {
            self.dev = crate::dev::address()
                .as_deref()
                .and_then(crate::dev::DevChannel::connect);
            crate::dev_commands::set_window(self.window.clone());
            if let Some(states) = crate::dev::restored_states() {
                self.runtime.states.restore_from(&states);
            }
        }
        // On Android the extra only says that `frus run` is listening, and it listens to the log.
        #[cfg(android)]
        {
            let asked = self
                .android_app
                .as_ref()
                .and_then(|app| crate::android_link::launch_extra(app, crate::dev::DEV_EXTRA));
            // Started by `frus run --hot`'s engine, which cannot add the extra (milestone 680).
            #[cfg(feature = "hot-reload")]
            let asked = asked.or_else(|| crate::hot::under_engine().then(String::new));
            self.dev = asked.map(|_| crate::dev::DevChannel::through_log());
            if self.dev.is_some() {
                let storage = self
                    .android_app
                    .as_ref()
                    .and_then(|app| app.internal_data_path());
                if let Some(states) = storage.as_deref().and_then(crate::dev::restored_states) {
                    self.runtime.states.restore_from(&states);
                }
                if let Some(dir) = storage {
                    crate::dev_commands::poll_commands(dir);
                }
            }
        }
    }

    /// Tells `frus run` where the application is and where its window sits, when either
    /// changed; a channel that can no longer be written to is closed.
    #[cfg(any(android, desktop))]
    fn report_dev(&mut self) {
        let Some(dev) = self.dev.as_mut() else {
            return;
        };
        #[cfg(desktop)]
        let window = self.window.as_ref().and_then(|window| {
            let at = window.outer_position().ok()?;
            let size = window.inner_size();
            Some([at.x, at.y, size.width as i32, size.height as i32])
        });
        #[cfg(android)]
        let window = None;
        if !dev.report(self.app.location(), window) {
            self.dev = None;
            return;
        }
        let states = &self.runtime.states;
        dev.save_if_asked(|| states.snapshot());
    }

    /// The links a second process handed to this one since the last frame.
    #[cfg(desktop)]
    fn open_links_from_other_instances(&mut self) {
        for link in crate::instance::take_links() {
            if let Some(location) = crate::link::location_of_link(&link) {
                let command = self.app.open_location(&location);
                self.run_command(command);
                self.build_dirty = true;
                self.request_redraw();
            }
        }
    }

    /// The address the page was opened at, handed to the application, and the browser's own
    /// moves from here on listened to. Once, before the first frame.
    #[cfg(web)]
    fn open_launch_address(&mut self, window: &Arc<Window>) {
        let strategy = self.app.location_strategy();
        let base = crate::address::base();
        let (location, index) = crate::address::current(strategy, &base);
        self.history.opened(location.clone(), index);
        crate::address::listen(window.clone(), strategy, base.clone());
        self.address = (strategy, base);
        if let Some(location) = location {
            let command = self.app.open_location(&location);
            self.run_command(command);
            // Opened deep in the application: the pages beneath get entries of their own.
            let (strategy, base) = &self.address;
            for (step, index) in self.history.seed(&self.app.location_stack()) {
                crate::address::apply(step, *strategy, base, index);
            }
        }
    }

    /// What the browser did since the last look is told to the application, and where the
    /// application is is shown in the address bar — the agreement of [`crate::history`].
    #[cfg(web)]
    fn sync_address(&mut self) {
        if !self.started {
            return;
        }
        for (location, state) in crate::address::take_popped() {
            if self.history.popped(location.clone(), state) {
                let command = self.app.open_location(&location);
                self.run_command(command);
                self.build_dirty = true;
                // The move it starts — a page sliding — is ticked by the frames after this
                // one, which was decided to be still before the address was read.
                self.request_redraw();
            }
        }
        if let Some(location) = self.app.location() {
            if let Some(step) = self
                .history
                .reflect(&location, self.app.location_replaces())
            {
                let (strategy, base) = &self.address;
                crate::address::apply(step, *strategy, base, self.history.index());
            }
        }
    }

    /// Runs a command, and whatever message it produces comes back into the loop
    /// through the proxy. Focus requests are **queued**, then resolved against the
    /// freshly built tree on the next frame.
    ///
    /// Where each kind of effect goes:
    ///
    /// | | native | Web |
    /// |---|---|---|
    /// | synchronous task | its own thread | a `spawn_local` microtask |
    /// | asynchronous task | the shell's executor | the browser |
    /// | timer | a task on the executor's reactor | `setTimeout` |
    ///
    /// A **synchronous** task keeps its thread: it blocks by definition, and that is
    /// what a thread is for. An **asynchronous** one no longer gets one — it is a
    /// task among others on a pool of four, which is the whole point of milestone
    /// 303. See [`crate::runtime`].
    fn run_command(&mut self, command: crate::command::Command<A::Message>) {
        let parts = command.into_parts();
        self.pending_focus.extend(parts.focus);
        self.pending_scroll.extend(parts.scrolls);
        self.pending_sheet.extend(parts.sheets);
        for task in parts.tasks {
            let proxy = self.proxy.clone();
            #[cfg(not(web))]
            std::thread::spawn(move || {
                if let Some(message) = task() {
                    let _ = proxy.send_event(message);
                }
            });
            #[cfg(web)]
            wasm_bindgen_futures::spawn_local(async move {
                if let Some(message) = task() {
                    let _ = proxy.send_event(message);
                }
            });
        }
        for future in parts.async_tasks {
            let proxy = self.proxy.clone();
            // Native: a task on the shared executor. `detach` because an effect must
            // outlive the handle — nothing here wants to cancel it, unlike a
            // subscription.
            #[cfg(not(web))]
            crate::runtime::spawn(async move {
                if let Some(message) = future.await {
                    let _ = proxy.send_event(message);
                }
            })
            .detach();
            // Web: the browser drives the future, single-threaded — `fetch` and friends
            // genuinely `await`, without blocking the loop.
            #[cfg(web)]
            wasm_bindgen_futures::spawn_local(async move {
                if let Some(message) = future.await {
                    let _ = proxy.send_event(message);
                }
            });
        }
        for (delay, message) in parts.timers {
            let proxy = self.proxy.clone();
            #[cfg(not(web))]
            crate::runtime::spawn(async move {
                crate::runtime::sleep(delay).await;
                let _ = proxy.send_event(message);
            })
            .detach();
            #[cfg(web)]
            web_timer::after(delay.as_millis() as i32, move || {
                let _ = proxy.send_event(message);
            });
        }
    }

    /// Diffs the subscriptions the app declares against those running: starts the new
    /// ones and stops those that vanished, by dropping their `Sender`.
    fn sync_subscriptions(&mut self) {
        let entries = self.app.subscription().into_entries();
        let declared: std::collections::HashSet<u64> = entries.iter().map(|e| e.id).collect();

        // Stop the subscriptions that are no longer declared.
        self.running_subs.retain(|id, _| declared.contains(id));

        // Start the new ones.
        for entry in entries {
            if self.running_subs.contains_key(&entry.id) {
                continue;
            }
            let handle = self.start_subscription(entry.kind);
            self.running_subs.insert(entry.id, handle);
        }
    }

    /// Starts a subscription as a task on the shell's executor, and returns its
    /// cancellation handle — **dropping the handle cancels the task**, which is what
    /// `sync_subscriptions` above relies on when the application stops declaring it.
    ///
    /// This used to be a thread per subscription, parked in `recv_timeout` and woken
    /// by the timeout or by its `Sender` being dropped. A timer is the clearest case
    /// there is of work that only ever waits, so it is the clearest case for not
    /// spending a thread on it.
    #[cfg(not(web))]
    fn start_subscription(&self, kind: crate::subscription::Kind<A::Message>) -> SubHandle {
        let proxy = self.proxy.clone();
        match kind {
            crate::subscription::Kind::Every { interval, make } => {
                crate::runtime::spawn(async move {
                    loop {
                        crate::runtime::sleep(interval).await;
                        // The loop having closed is the other way this ends, and the
                        // application is gone by then, so there is nobody to tell.
                        if proxy.send_event(make(Instant::now())).is_err() {
                            break;
                        }
                    }
                })
            }
        }
    }

    /// Starts a subscription on the **Web**: a browser `setInterval`, with no thread.
    /// Returns its cancellation handle, which calls `clearInterval` on drop. The proxy
    /// feeds the message back into the loop on every tick.
    #[cfg(web)]
    fn start_subscription(&self, kind: crate::subscription::Kind<A::Message>) -> SubHandle {
        let proxy = self.proxy.clone();
        match kind {
            crate::subscription::Kind::Every { interval, make } => {
                let ms = interval.as_millis() as i32;
                web_timer::Interval::new(ms, move || {
                    let _ = proxy.send_event(make(Instant::now()));
                })
            }
        }
    }

    /// Applies the mouse drag under way.
    fn handle_drag(&mut self) {
        let Some(mut drag) = self.drag.take() else {
            return;
        };
        // How far this pointer has to travel before a press counts as a drag.
        let slop = self.hit_slop();
        match &mut drag {
            Drag::Scrollbar {
                id,
                vertical,
                grab,
                track_start,
                track_len,
                thumb_len,
                max,
                reverse,
            } => {
                let along = if *vertical {
                    self.cursor.y
                } else {
                    self.cursor.x
                };
                let travel = (*track_len - *thumb_len).max(1.0);
                let thumb_start = (along - *grab).clamp(*track_start, *track_start + travel);
                let fraction = (thumb_start - *track_start) / travel;
                // A reversed axis numbers its offsets from the far end, so the thumb's
                // position along the track reads backwards.
                let fraction = if *reverse { 1.0 - fraction } else { fraction };
                let offset = (fraction * *max).clamp(0.0, *max);
                let entry = self.runtime.scroll.entry(*id).or_insert((0.0, 0.0));
                if *vertical {
                    entry.1 = offset;
                } else {
                    entry.0 = offset;
                }
                // A precise drag: the target follows the offset and inertia is cut off.
                let synced = *entry;
                self.runtime.scroll_target.insert(*id, synced);
                self.runtime.scroll_velocity.remove(&*id);
            }
            Drag::RegionSelect { area } => {
                let area = *area;
                self.extend_region_selection(area);
            }
            Drag::RegionHandle { area, handle, grab } => {
                let (area, handle, grab) = (*area, *handle, *grab);
                self.drag_region_handle(area, handle, grab);
            }
            Drag::TextSelect { id, rect } => {
                let local_x = self.cursor.x - rect.x;
                let local_y = self.cursor.y - rect.y
                    + self.runtime.scroll.get(id).map(|s| s.1).unwrap_or(0.0);
                // The field is focused during the drag, so scroll from the current caret.
                let scroll_cursor = self.runtime.edits.get(id).map(|e| e.cursor).unwrap_or(0);
                let cursor = self
                    .tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), *id))
                    .and_then(|widget| {
                        widget.cursor_at(local_x, local_y, rect.width, scroll_cursor)
                    });
                if let Some(cursor) = cursor {
                    let edit = self.runtime.edits.entry(*id).or_default();
                    if edit.anchor.is_none() {
                        edit.anchor = Some(edit.cursor);
                    }
                    edit.cursor = cursor;
                }
            }
            Drag::SelectionHandle {
                id,
                rect,
                handle,
                grab,
            } => {
                // The text position the handle stands for, carried with the finger, and
                // the retained vertical scroll folded in as for a press.
                let local_x = self.cursor.x - rect.x + grab.x;
                let local_y = self.cursor.y - rect.y
                    + grab.y
                    + self.runtime.scroll.get(id).map(|s| s.1).unwrap_or(0.0);
                let edit = self.runtime.edits.get(id).copied().unwrap_or_default();
                let moved = self
                    .tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), *id))
                    .and_then(|widget| widget.cursor_at(local_x, local_y, rect.width, edit.cursor))
                    .and_then(|to| crate::selection::drag(edit, *handle, to));
                if let Some(moved) = moved {
                    self.runtime.edits.insert(*id, moved);
                }
            }
            Drag::Widget {
                id,
                rect,
                last_x,
                press_x,
                track,
                active,
                thumb,
            } => {
                let dx = self.cursor.x - *last_x;
                *last_x = self.cursor.x;
                if matches!(track.mode, frus_widgets::DragMode::Thumbs { .. }) {
                    let rtl = self.is_rtl();
                    let at = track.fraction(*rect, self.cursor.x, rtl);
                    match *thumb {
                        Some(picked) => {
                            self.thumb_drag(*id, picked, frus_widgets::ThumbDrag::Move, at);
                        }
                        // A press on both thumbs: the first movement says which.
                        None => {
                            let moved = self.cursor.x - *press_x;
                            if let Some(picked) = track.pick_thumb(*rect, *press_x, moved, rtl) {
                                *thumb = Some(picked);
                                self.thumb_drag(*id, picked, frus_widgets::ThumbDrag::Start, at);
                                self.thumb_drag(*id, picked, frus_widgets::ThumbDrag::Move, at);
                            }
                        }
                    }
                } else if *active {
                    let value = track.value_at(*rect, *press_x, self.cursor.x, true, self.is_rtl());
                    self.apply_widget_drag(*id, dx, value);
                }
            }
            Drag::Reorder { start, moved, .. } => {
                // Past the threshold this is a real drag, and no longer a sort.
                let dx = self.cursor.x - start.x;
                let dy = self.cursor.y - start.y;
                if !*moved && (dx * dx + dy * dy) > slop * slop {
                    *moved = true;
                }
                // The ghost card follows the pointer, so redraw on every move.
                if *moved {
                    self.request_redraw();
                }
            }
            Drag::Gesture {
                id,
                axis,
                start,
                last,
                moved,
            } => {
                let (id, axis) = (*id, *axis);
                if !*moved {
                    // Past the slop it is a drag and no longer a tap. (The reference's pan
                    // waits for twice this, but its tap has given up at once: a movement in
                    // between is neither. One threshold keeps a press either a tap or a drag.)
                    let (tx, ty) = (self.cursor.x - start.x, self.cursor.y - start.y);
                    let travelled = match axis {
                        frus_widgets::PanAxis::Free => tx.hypot(ty),
                        frus_widgets::PanAxis::Horizontal => tx.abs(),
                        frus_widgets::PanAxis::Vertical => ty.abs(),
                    };
                    if travelled > slop {
                        *moved = true;
                        let local = self.pan_local(id, *start);
                        self.send_pan(id, frus_widgets::PanEvent::Start { local });
                    }
                }
                if *moved {
                    let delta = mask_pan(
                        axis,
                        Point::new(self.cursor.x - last.x, self.cursor.y - last.y),
                    );
                    *last = self.cursor;
                    self.track_gesture();
                    if delta.x != 0.0 || delta.y != 0.0 {
                        let local = self.pan_local(id, self.cursor);
                        self.send_pan(id, frus_widgets::PanEvent::Update { local, delta });
                    }
                }
            }
            Drag::Pan {
                id,
                last,
                moved,
                viewport,
            } => {
                let dx = self.cursor.x - last.x;
                let dy = self.cursor.y - last.y;
                if !*moved && (dx * dx + dy * dy) > slop * slop {
                    *moved = true;
                }
                if *moved {
                    let view = self.runtime.interactive.entry(*id).or_default();
                    // The finger pushes the content, bounded to the frame.
                    *view = view.pan(dx, dy).clamped(*viewport);
                    *last = self.cursor;
                    self.track_gesture();
                }
            }
            Drag::Item {
                source,
                start,
                moved,
                over,
            } => {
                let dx = self.cursor.x - start.x;
                let dy = self.cursor.y - start.y;
                // Under the threshold nothing is lifted: the press may still be a click
                // on whatever the draggable wraps.
                if !*moved && (dx * dx + dy * dy) > slop * slop {
                    *moved = true;
                }
                if !*moved {
                    return;
                }
                // The target under the pointer, but only if it would take this payload:
                // a target that refuses is not highlighted, so the answer is visible
                // before the finger lifts rather than after.
                let payload = source.payload;
                let candidate = self
                    .ui
                    .as_ref()
                    .and_then(|ui| ui.drop_zone_at(self.cursor))
                    .filter(|zone| {
                        self.tree
                            .as_ref()
                            .and_then(|tree| find_widget(tree.as_ref(), zone.id))
                            .is_some_and(|widget| widget.accepts_drag(payload))
                    })
                    .map(|zone| zone.id);
                if *over != candidate {
                    *over = candidate;
                    self.runtime.drag_over = candidate;
                }
                self.request_redraw();
            }
            Drag::Scroll {
                id,
                last,
                moved,
                carried,
                dismiss,
                axis,
                pan,
            } => {
                let dx = self.cursor.x - last.x;
                let dy = self.cursor.y - last.y;
                // Under the threshold we do not scroll yet; the gesture may be a tap.
                if !*moved && (dx * dx + dy * dy) > slop * slop {
                    *moved = true;
                    // The moment of arbitration. A scroll and a swipe start identically,
                    // so the question is not who is on top but **which way the finger
                    // went**: along the item's swipe axis it is a dismissal, across it a
                    // scroll. Deciding once, here, is what keeps the loser out of the
                    // gesture entirely — a swipe that also scrolled the list would be
                    // worse than either.
                    // A detector's drag, by the same rule: one kept to an axis takes a movement
                    // along it; a free one takes a movement no scroll under it runs along —
                    // the reference's pan, which loses a vertical movement to a vertical scroll
                    // because its slop is twice the scroll's (milestone 582).
                    if let Some((target, pan_axis)) = pan.take() {
                        let down = dy.abs() >= dx.abs();
                        let wins = match pan_axis {
                            frus_widgets::PanAxis::Horizontal => !down,
                            frus_widgets::PanAxis::Vertical => down,
                            frus_widgets::PanAxis::Free => {
                                let chain: Vec<_> = self
                                    .ui
                                    .as_ref()
                                    .map(|ui| ui.scroll_chain(*last).collect())
                                    .unwrap_or_default();
                                // Nothing under the finger scrolls that way (`claim_area`
                                // without its fallback to the area pressed on).
                                !chain.iter().any(|a| a.takes_user_scroll(down))
                            }
                        };
                        if wins {
                            // The scroll gives its offset back untouched: it never moved.
                            self.runtime.release_scroll(*id);
                            let start = *last;
                            self.drag = Some(Drag::Gesture {
                                id: target,
                                axis: pan_axis,
                                start,
                                last: start,
                                moved: false,
                            });
                            self.handle_drag();
                            return;
                        }
                    }
                    if let Some(item) = dismiss.take() {
                        let along = if item.spec.axis.is_horizontal() {
                            dx.abs() > dy.abs()
                        } else {
                            dy.abs() > dx.abs()
                        };
                        if along {
                            // The list gives the offset back untouched: it never moved.
                            self.runtime.release_scroll(*id);
                            self.drag = Some(Drag::Dismiss {
                                item,
                                last: *last,
                                moved: true,
                            });
                            self.handle_drag();
                            return;
                        }
                    }
                    // And the same arbitration between the two **axes** — which settles,
                    // with it, *which* of the scrollables under the finger the gesture
                    // belongs to. The reference does both at once in its arena: every
                    // scrollable in the stack enters a recogniser for its own axis, the
                    // one the finger matches wins, and the losers are out of the gesture
                    // entirely. Without the first half a page scrolling down drifts
                    // sideways the whole way, since no finger travels in a straight line;
                    // without the second, a strip of chips that only slides across stops
                    // the page behind it from scrolling at all.
                    let chain: Vec<_> = self
                        .ui
                        .as_ref()
                        .map(|ui| ui.scroll_chain(*last).collect())
                        .unwrap_or_default();
                    let down = dy.abs() >= dx.abs();
                    if let Some(area) = claim_area(&chain, *id, down) {
                        if area.id != *id {
                            // The area under the finger lost: it gives its offset back
                            // untouched, since it never moved. The winner is caught and
                            // held exactly as the press would have done to it.
                            self.runtime.release_scroll(*id);
                            let physics = area.physics;
                            *carried = self.runtime.catch_scroll_fling(area.id, physics);
                            self.runtime.hold_scroll(area.id);
                            *id = area.id;
                        }
                        *axis = Some(claim_axis(
                            dx,
                            dy,
                            area.takes_user_scroll(false),
                            area.takes_user_scroll(true),
                        ));
                    } else {
                        *axis = Some(down);
                    }
                }
                // Only the claimed axis moves. The other delta is not held back for later:
                // it is not part of this gesture at all.
                let (dx, mut dy) = match *axis {
                    Some(true) => (0.0, dy),
                    Some(false) => (dx, 0.0),
                    None => (dx, dy),
                };
                if *moved && *axis == Some(true) {
                    // A list inside a sheet shares the finger with it (milestone 515).
                    // Every movement is split — the sheet first going up, the list
                    // first going down — so the gesture changes hands in the middle of a
                    // drag, and what the list is left with goes through its physics below
                    // exactly as a movement of its own would.
                    let sheet = self
                        .ui
                        .as_ref()
                        .filter(|ui| ui.scroll_region(*id).is_some_and(|a| !a.reverse_y))
                        .and_then(|ui| ui.sheet_holding(*id))
                        .filter(|sheet| sheet.available > 0.0)
                        .cloned();
                    if let Some(sheet) = sheet {
                        let px = sheet.available;
                        let offset = self.runtime.scroll.get(id).map_or(0.0, |o| o.1);
                        let size = self.runtime.sheet_size(sheet.id, &sheet.spec) * px;
                        let (grown, listed) = frus_widgets::split_sheet_drag(
                            -dy,
                            offset,
                            size,
                            sheet.spec.floor() * px,
                            sheet.spec.max * px,
                        );
                        if grown != 0.0 {
                            self.runtime
                                .sheet_drag(sheet.id, &sheet.spec, grown / px, px);
                        }
                        dy = -listed;
                    }
                }
                if *moved {
                    let area = self.ui.as_ref().and_then(|u| u.scroll_region(*id));
                    // A region gone from the frame moves as the application's behaviour says.
                    let physics = area.map(|a| a.physics).unwrap_or_else(|| {
                        self.app
                            .scroll_behavior()
                            .scroll_physics(&self.themes.displayed(&self.app))
                    });
                    let cur = self.runtime.scroll.get(id).copied().unwrap_or((0.0, 0.0));
                    // The finger pushes the content, so we follow the delta at once —
                    // but only as far as the physics allows. Past an edge, bouncing
                    // physics resists more and more (the rubber band) while clamping
                    // physics refuses the move outright.
                    // What the physics refuses is exactly the distance the user asked
                    // for and did not get — which is what the glow acknowledges.
                    let axis = |metrics: frus_widgets::ScrollMetrics, delta: f32| {
                        let applied = physics.apply_user_offset(metrics, delta);
                        let proposed = metrics.pixels + applied;
                        let refused = physics.apply_boundary_conditions(metrics, proposed);
                        (proposed - refused, refused)
                    };
                    let (nx, ny, refused) = match area {
                        Some(area) => {
                            let (ddx, ddy) = area.offset_delta((dx, dy));
                            let (nx, rx) = axis(area.metrics_x(cur.0), ddx);
                            let (ny, ry) = axis(area.metrics_y(cur.1), ddy);
                            (nx, ny, Some((area, rx, ry)))
                        }
                        None => (cur.0 - dx, cur.1 - dy, None),
                    };
                    if let Some((area, rx, ry)) = refused {
                        // A pull-to-refresh area listening above this scrollable takes
                        // the **top** edge; the glow takes the other three. Both answer
                        // "there is nothing more that way", and giving both would say it
                        // twice — the indicator being the more useful of the two, since
                        // it leads somewhere.
                        if let Some(host) = area.refresh {
                            self.feed_refresh(host, physics, area.viewport.height, cur.1, ny, ry);
                        }
                        let cursor = self.cursor;
                        for (refused, vertical, extent) in [
                            (rx, false, area.viewport.width),
                            (ry, true, area.viewport.height),
                        ] {
                            if refused.abs() < 1e-3 {
                                continue;
                            }
                            let edge = area.refused_edge(vertical, refused);
                            // The refresh area takes the edge the axis **starts** at,
                            // which is the bottom of a reversed one.
                            if area.refresh.is_some() && edge == area.start_edge(vertical) {
                                continue;
                            }
                            let (offset, cross) =
                                frus_widgets::glow_cross_axis(area.viewport, edge, cursor);
                            self.runtime.glow_pull(
                                area.id,
                                area.overscroll,
                                edge,
                                refused,
                                extent,
                                offset,
                                cross,
                            );
                        }
                        // Content that moves again lets its stretch go, as the
                        // reference's does on any scroll that is not an overscroll.
                        if rx.abs() < 1e-3 && ry.abs() < 1e-3 && (nx, ny) != cur {
                            self.runtime.stretch_release(area.id);
                        }
                    }
                    self.runtime.scroll.insert(*id, (nx, ny));
                    self.runtime.scroll_target.insert(*id, (nx, ny));
                    self.runtime.scroll_velocity.remove(id);
                    *last = self.cursor;
                    self.track_gesture();
                }
            }
            Drag::Dismiss { item, last, moved } => {
                let dx = self.cursor.x - last.x;
                let dy = self.cursor.y - last.y;
                if !*moved && (dx * dx + dy * dy) > slop * slop {
                    *moved = true;
                }
                if *moved {
                    let delta = if item.spec.axis.is_horizontal() {
                        dx
                    } else {
                        dy
                    };
                    self.runtime
                        .dismiss_drag(item.id, delta, item.extent(), item.spec.axis);
                    *last = self.cursor;
                    self.track_gesture();
                }
            }
            Drag::Sheet {
                id,
                last,
                moved,
                available,
            } => {
                let dx = self.cursor.x - last.x;
                let dy = self.cursor.y - last.y;
                if !*moved && (dx * dx + dy * dy) > slop * slop {
                    *moved = true;
                }
                if *moved && *available > 0.0 {
                    let spec = self
                        .ui
                        .as_ref()
                        .and_then(|ui| ui.sheet(*id))
                        .map(|sheet| sheet.spec.clone());
                    if let Some(spec) = spec {
                        // Up grows it: the screen's y runs the other way.
                        self.runtime
                            .sheet_drag(*id, &spec, -dy / *available, *available);
                    }
                    *last = self.cursor;
                    self.track_gesture();
                }
            }
            Drag::Back { start_x } => {
                let width = self.logical_width();
                // Under RTL the finger slides **left** from the right edge, so progress
                // runs the other way.
                let sign = if self.is_rtl() { -1.0 } else { 1.0 };
                let progress = (sign * (self.cursor.x - *start_x) / width).clamp(0.0, 1.0);
                self.track_gesture();
                self.build_dirty = true;
                self.app.back_gesture(progress);
            }
        }
        self.drag = Some(drag);
        self.request_redraw();
    }

    /// The refresh area a scrollable sits inside, if any.
    fn refresh_host_of(&self, scrollable: WidgetId) -> Option<WidgetId> {
        self.ui
            .as_ref()
            .and_then(|ui| ui.scroll_region(scrollable))
            .and_then(|area| area.refresh)
    }

    /// Ends the pull of whichever refresh area holds `scrollable`, and dispatches its
    /// message when the pull was armed.
    fn release_refresh(&mut self, scrollable: WidgetId) {
        let Some(host) = self.refresh_host_of(scrollable) else {
            return;
        };
        if !self.runtime.refresh_release(host) {
            return;
        }
        let message = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), host))
            .and_then(|widget| widget.on_refresh());
        if let Some(message) = message {
            self.dispatch(message);
        }
    }

    /// Feeds one move of a drag into the pull of the refresh area `host`.
    ///
    /// The two physics put the overscroll in **different places**, so the signal is
    /// read differently:
    ///
    /// - **Clamping** refuses the movement and pins the offset at the edge, so the
    ///   refused amount is the only trace the gesture leaves. It is incremental, and
    ///   the physics returns nothing at all for a move back towards the content — so
    ///   an eased-off pull holds rather than retracting, which is right: the finger has
    ///   not let go.
    /// - **Bouncing** lets the offset go past the edge, so the *depth* it reached is
    ///   the signal, and the change in that depth is signed. The indicator therefore
    ///   follows the rubber band back in as the finger returns, which is also right:
    ///   there, the content itself is already saying so.
    ///
    /// Leaving the top edge at all ends the pull. The gesture has become an ordinary
    /// scroll, and an indicator still hanging there would be promising something the
    /// release is no longer going to deliver.
    fn feed_refresh(
        &mut self,
        host: WidgetId,
        physics: frus_widgets::ScrollPhysics,
        extent: f32,
        before: f32,
        after: f32,
        refused_y: f32,
    ) {
        if after > 0.5 {
            self.runtime.refresh_cancel(host);
            return;
        }
        let pulled = if physics.allows_overscroll() {
            (-after).max(0.0) - (-before).max(0.0)
        } else {
            -refused_y
        };
        if pulled.abs() > 1e-3 {
            self.runtime.refresh_pull(host, pulled, extent);
        }
    }

    /// How far the pointer must travel before a press becomes a drag, given what
    /// kind of pointer it is.
    fn hit_slop(&self) -> f32 {
        if self.pointer_touch {
            TOUCH_SLOP
        } else {
            PRECISE_SLOP
        }
    }

    /// Seconds since the drag under way began — the clock the velocity tracker's
    /// samples are stamped with.
    fn gesture_now(&self) -> f32 {
        match self.gesture_clock {
            // The test driver's clock: the frames it has run, not the wall's.
            Some((now, start)) => now - start,
            None => (Instant::now() - self.gesture_start).as_secs_f32(),
        }
    }

    /// Starts a fresh gesture: the history of the previous one must not leak into
    /// the next, or a flick left then right would fling the wrong way.
    ///
    /// The tracker is the application's scroll behaviour's; a drag on a scroll area
    /// replaces it with the area's own.
    fn begin_gesture(&mut self) {
        self.gesture_velocity = self
            .app
            .scroll_behavior()
            .velocity_tracker(&self.themes.displayed(&self.app));
        self.gesture_start = Instant::now();
        if let Some((now, start)) = self.gesture_clock.as_mut() {
            *start = *now;
        }
        self.track_gesture();
    }

    /// Records where the pointer is now.
    fn track_gesture(&mut self) {
        let now = self.gesture_now();
        self.gesture_velocity.add_position(now, self.cursor);
    }

    /// What the gesture tracker makes of the drag as it stands.
    fn gesture_estimate(&self) -> VelocityEstimate {
        self.gesture_velocity
            .estimate(self.gesture_now())
            .unwrap_or(VelocityEstimate::STILL)
    }

    /// [`fling_velocity`], gated on this pointer's slop.
    fn fling_velocity(&self, estimate: VelocityEstimate) -> (f32, f32) {
        fling_velocity(estimate, self.hit_slop())
    }

    /// A scroll fling: projects each axis's ballistic destination, friction in closed
    /// form, bounds it with the elastic overshoot, and primes the scroll spring with
    /// the finger's momentum.
    fn fling(&mut self, id: WidgetId, velocity: (f32, f32)) {
        let Some(area) = self.ui.as_ref().and_then(|ui| ui.scroll_region(id)) else {
            return;
        };
        let physics = area.physics;
        // The physics decides everything from here: whether there is a fling at all,
        // how far it runs, and what happens at the edges. A release too slow to
        // fling still gets a chance to spring an overscroll back.
        if self.runtime.fling_scroll(area, physics, velocity) {
            self.request_redraw();
        }
    }

    /// The topmost **reorderable** widget under `point`, as `(id, flat index)`. It
    /// uses the reorderables' registry, which is independent of clicking, and so covers
    /// the Kanban cards and drop zones, which are not clickable.
    fn reorderable_at(&self, point: Point) -> Option<(WidgetId, usize, bool)> {
        let id = self.ui.as_ref()?.reorderable_at(point)?;
        let widget = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))?;
        // A target-**only** widget, a drop zone: reorderable but not grabbable, so no
        // drag starts on it. Dropping still aims at it, through `ui.reorderable_at`.
        if !widget.reorder_draggable() {
            return None;
        }
        let from = widget.reorder_index()?;
        Some((id, from, widget.drag_needs_long_press()))
    }

    /// **What is actually moving**, given what was grabbed: its id and its box.
    ///
    /// Usually they are the same widget. They are not when what was grabbed is a **grip**
    /// — a source that is not a target — because a grip is a 40-pixel gutter inside a much
    /// larger row, and everything the preview is made of is the row's: the ghost is the
    /// row lifted out of the frame, the gap that closes behind it is the row's height, and
    /// the band the neighbours are matched against is the row's width. Taking the grip's
    /// box instead would lift an icon and open a slot two centimetres too narrow.
    ///
    /// The row is found by the index the two share, among the reorderables under the
    /// grip's own middle — which is inside its row by construction.
    fn reorder_source(&self, id: WidgetId, from: usize) -> Option<(WidgetId, Rect)> {
        let ui = self.ui.as_ref()?;
        let tree = self.tree.as_ref()?;
        let own = ui.widget_rect(id)?;
        let grabbed = find_widget(tree.as_ref(), id)?;
        if grabbed.reorder_droppable() {
            return Some((id, own));
        }
        let middle = Point::new(own.x + own.width * 0.5, own.y + own.height * 0.5);
        let slot = ui.reorderables_at(middle).find(|other| {
            find_widget(tree.as_ref(), *other)
                .is_some_and(|w| w.reorder_droppable() && w.reorder_index() == Some(from))
        })?;
        // A grip whose row is nowhere to be found still moves something: itself, which is
        // wrong-looking but not a crash, and cannot happen while the two are built
        // together.
        Some((slot, ui.widget_rect(slot).unwrap_or(own)))
    }

    /// The row the reorder under way carries, and its box: the one taken when the drag was
    /// first carried, moved with the content since — or, before any frame has carried it,
    /// the frame's.
    fn reorder_carried(&self) -> Option<(WidgetId, Rect)> {
        match &self.drag {
            Some(Drag::Reorder {
                carried: Some(carried),
                ..
            }) => Some(*carried),
            Some(Drag::Reorder { id, from, .. }) => self.reorder_source(*id, *from),
            _ => None,
        }
    }

    /// Takes the carried row's box from the frame, once: the first frame a reorder is carried
    /// in, before anything has scrolled it. From then on it goes with the content, and the
    /// frame is no longer asked — a row carried to an edge is clipped by it, and a row
    /// scrolled out of sight is not in the frame at all.
    fn keep_carried_box(&mut self) {
        let source = match &self.drag {
            Some(Drag::Reorder {
                id,
                from,
                moved: true,
                carried: None,
                ..
            }) => self.reorder_source(*id, *from),
            _ => return,
        };
        if let Some(Drag::Reorder { carried, .. }) = self.drag.as_mut() {
            *carried = source;
        }
    }

    /// The topmost reorderable under `point` that something can actually be **dropped**
    /// on. It is not always the topmost reorderable: a list row's grip is a source and
    /// not a target, and what is under it is the row the drop is really aimed at.
    fn reorder_target_at(&self, point: Point) -> Option<WidgetId> {
        let ui = self.ui.as_ref()?;
        let tree = self.tree.as_ref()?;
        ui.reorderables_at(point)
            .find(|id| find_widget(tree.as_ref(), *id).is_some_and(|w| w.reorder_droppable()))
    }

    /// Where the reorderable `id`, grabbed at index `from`, is **dropped** if released now:
    /// the target under the pointer, or — over no target at all — the nearest slot of its own
    /// list, for one inserted between its neighbours, along the axis it is reordered on.
    ///
    /// The insertion line and the release both ask this, so the line cannot promise a place
    /// the drop does not keep. The second half is milestone 518: a row carried to the bottom
    /// of a phone's list is over what follows the list, and the release used to put it back.
    /// Milestone 527 turned it on its side, for a list whose rows run across.
    fn reorder_drop_target(
        &self,
        id: WidgetId,
        from: usize,
        carried: Option<(WidgetId, Rect)>,
    ) -> Option<WidgetId> {
        if let Some(target) = self.reorder_target_at(self.cursor) {
            return Some(target);
        }
        let tree = self.tree.as_ref()?;
        let Some(ReorderMotion::Slots(axis)) = find_widget(tree.as_ref(), id).map(reorder_motion)
        else {
            return None;
        };
        // Among the slots of the row that moves, which is not the grip that was grabbed —
        // and which may have been scrolled out of the frame by the carry itself.
        let row = match carried {
            Some((row, _)) => row,
            None => self.reorder_source(id, from)?.0,
        };
        let slots = reorder_siblings(self.ui.as_ref()?, tree.as_ref(), row);
        let boxes: Vec<Rect> = slots.iter().map(|(_, rect)| *rect).collect();
        nearest_reorder_slot(self.cursor, &boxes, axis).map(|index| slots[index].0)
    }

    /// What is being **carried** this frame, where it is now: the box the ghost is drawn
    /// at, for a reorder or for a lifted item. `None` when nothing is engaged.
    ///
    /// It is the ghost's box and not the pointer, because the reference scrolls when the
    /// *item* reaches the edge, and that is the honest moment: a row half off the bottom
    /// is already asking to go further, whatever the finger holding it is over.
    fn carried_rect(&self) -> Option<Rect> {
        match &self.drag {
            Some(Drag::Reorder {
                start, moved: true, ..
            }) => {
                let (_, src) = self.reorder_carried()?;
                // The same offsets the ghost is painted at, and for the same reason a
                // column's ghost only rises: it moves along its own axis.
                let (gx, gy) = ghost_offset(
                    self.dragged_reorder_motion()
                        .unwrap_or(ReorderMotion::Columns),
                    (self.cursor.x - start.x, self.cursor.y - start.y),
                );
                Some(src.translate(gx, gy))
            }
            Some(Drag::Item {
                source,
                start,
                moved: true,
                ..
            }) => Some(
                source
                    .rect
                    .translate(self.cursor.x - start.x, self.cursor.y - start.y),
            ),
            _ => None,
        }
    }

    /// Scrolls the area under the pointer while what is being carried hangs past one of
    /// its edges — the gap `Draggable` has had since milestone 285, and what a list longer
    /// than a screen needs before it can be reordered at all.
    ///
    /// The area is the innermost one under the **pointer** that a user could move by
    /// hand: an area that refuses a finger refuses this too, so a list that fits its
    /// viewport never twitches.
    fn autoscroll_carried(&mut self, dt: f32) -> bool {
        self.keep_carried_box();
        let Some(carried) = self.carried_rect() else {
            return false;
        };
        let area = {
            let scroll = &self.runtime.scroll;
            self.ui.as_ref().and_then(|ui| {
                ui.scroll_chain(self.cursor).find(|area| {
                    area.accepts_user_offset(scroll.get(&area.id).copied().unwrap_or((0.0, 0.0)))
                })
            })
        };
        let Some(area) = area else {
            return false;
        };
        let offset = self
            .runtime
            .scroll
            .get(&area.id)
            .copied()
            .unwrap_or((0.0, 0.0));
        // What is still hidden on either side, in **screen** terms: on a reversed axis
        // the offset is measured from the other end, so the two swap over.
        let room = |offset: f32, max: f32, reverse: bool| {
            if reverse {
                (max - offset, offset)
            } else {
                (offset, max - offset)
            }
        };
        let view = area.viewport;
        let dx = edge_autoscroll(
            (carried.x, carried.x + carried.width),
            (view.x, view.x + view.width),
            room(offset.0, area.max_x, area.reverse_x),
            dt,
        )
        .unwrap_or(0.0);
        let dy = edge_autoscroll(
            (carried.y, carried.y + carried.height),
            (view.y, view.y + view.height),
            room(offset.1, area.max_y, area.reverse_y),
            dt,
        )
        .unwrap_or(0.0);
        if dx == 0.0 && dy == 0.0 {
            return false;
        }
        // A movement of the content becomes a change of offset the area's own way, which
        // is the one place the sign of a reversed axis is decided.
        let delta = area.offset_delta((dx, dy));
        let next = (
            (offset.0 + delta.0).clamp(0.0, area.max_x),
            (offset.1 + delta.1).clamp(0.0, area.max_y),
        );
        if next == offset {
            return false;
        }
        self.runtime.scroll.insert(area.id, next);
        // The target follows, or the inertia the area was resting at would spring the
        // list straight back out from under the row.
        self.runtime.scroll_target.insert(area.id, next);
        self.runtime.scroll_velocity.remove(&area.id);
        // What is carried stays under the finger. Its ghost is drawn at the box the frame
        // puts it at, offset by how far the finger has moved since the press; the frame now
        // puts that box where the content went, so the press goes there too. Otherwise the
        // ghost rides up with the list, stops hanging over the edge, and the scroll it
        // started starves itself — seen on a phone, milestone 517.
        if let Some(drag) = self.drag.as_mut() {
            follow_content(
                drag,
                area.offset_delta((next.0 - offset.0, next.1 - offset.1)),
            );
        }
        true
    }

    /// How the reorderable currently **grabbed** moves, if a drag is under way. It is what
    /// keeps the **pointer spring** (`reorder_x` following the pointer) to `Table`'s columns;
    /// the Kanban cards and a list's rows spring their insertion line instead.
    fn dragged_reorder_motion(&self) -> Option<ReorderMotion> {
        let Some(Drag::Reorder { id, .. }) = self.drag else {
            return None;
        };
        self.tree
            .as_ref()
            .and_then(|t| find_widget(t.as_ref(), id))
            .map(reorder_motion)
    }

    /// Steps the reorder springs one frame, per gesture — see the frame loop — and says
    /// whether they are still moving.
    fn advance_reorder_springs(&mut self, dt: f32) -> bool {
        let reorder_motion = matches!(self.drag, Some(Drag::Reorder { moved: true, .. }))
            .then(|| self.dragged_reorder_motion())
            .flatten();
        match reorder_motion {
            Some(ReorderMotion::Columns) => {
                self.reorder_x = spring_toward(self.reorder_x, self.cursor.x, dt, 0.07);
                (self.cursor.x - self.reorder_x).abs() > 0.5
            }
            Some(ReorderMotion::Slots(ReorderAxis::Vertical)) => {
                match self.reorder_drop_line(drag_preview::INSERT_THICKNESS) {
                    Some(target) => {
                        self.reorder_y = spring_toward(self.reorder_y, target.y, dt, 0.07);
                        (target.y - self.reorder_y).abs() > 0.5
                    }
                    None => false,
                }
            }
            Some(ReorderMotion::Slots(ReorderAxis::Horizontal)) => {
                match self.reorder_drop_line(drag_preview::INSERT_THICKNESS) {
                    Some(target) => {
                        self.reorder_x = spring_toward(self.reorder_x, target.x, dt, 0.07);
                        (target.x - self.reorder_x).abs() > 0.5
                    }
                    None => false,
                }
            }
            None => false,
        }
    }

    /// Paints the **reorder preview** on top of the scene, unclipped: the source
    /// column dimmed, a **drop indicator** at the target column's insertion edge, and a
    /// **lifted card** — shadow plus a `primary` border — following the pointer. No
    /// effect outside an engaged header drag.
    /// Names, on the console, every box this frame whose children did not fit inside it.
    ///
    /// The reference treats an overflowing flex as an error condition, paints a striped
    /// band along the offending edge and writes to the console; nothing here said anything
    /// at all, which is how a task row's delete button came to be laid out past the window
    /// and stayed there for three milestones — drawn nowhere, hittable nowhere. Half of
    /// that is now here: the words, once per site, with the two ways out the reference
    /// suggests. The striped band is not.
    ///
    /// Once per site, because a layout that does not fit does not fit on every frame, and
    /// sixty lines a second is the same as silence.
    fn report_overflows(&self, ui: &Ui<A::Message>) {
        for o in ui.overflows() {
            // The site: a box, an edge, and the amount rounded to the pixel. Enough to
            // stay quiet while a window is resized past the same defect, and to speak up
            // when the defect changes.
            let mut key = std::collections::hash_map::DefaultHasher::new();
            use std::hash::{Hash, Hasher};
            (
                o.rect.width.to_bits(),
                o.rect.height.to_bits(),
                o.side as u8,
                o.amount.round() as i32,
            )
                .hash(&mut key);
            if !self.reported_overflows.borrow_mut().insert(key.finish()) {
                continue;
            }
            let side = match o.side {
                frus_widgets::Side::Left => "left",
                frus_widgets::Side::Right => "right",
                frus_widgets::Side::Top => "top",
                frus_widgets::Side::Bottom => "bottom",
            };
            log::warn!(
                "a box {:.0}x{:.0} is overflowed by {:.0} px on the {side}: its children do not \
                 fit inside it, and what runs past the edge is drawn outside its parent — \
                 invisible where something clips it, and untappable where it leaves the window. \
                 Give the child that should give way an `Expanded`, or put the content in a \
                 `SingleChildScrollView`.",
                o.rect.width,
                o.rect.height,
                o.amount,
            );
        }
    }

    /// Winit's key event as a [`KeyStroke`] — the general vocabulary shortcuts are bound
    /// to, as opposed to [`Key`], which is the one text editing needs.
    ///
    /// `None` for anything with no place in a shortcut: a dead key, a compose sequence, a
    /// modifier pressed on its own.
    fn keystroke(&self, event: &KeyDown) -> Option<KeyStroke> {
        let key = match &event.logical_key {
            WinitKey::Named(NamedKey::Enter) => ShortcutKey::Enter,
            WinitKey::Named(NamedKey::Escape) => ShortcutKey::Escape,
            WinitKey::Named(NamedKey::Tab) => ShortcutKey::Tab,
            WinitKey::Named(NamedKey::Space) => ShortcutKey::Space,
            WinitKey::Named(NamedKey::Backspace) => ShortcutKey::Backspace,
            WinitKey::Named(NamedKey::Delete) => ShortcutKey::Delete,
            WinitKey::Named(NamedKey::ArrowUp) => ShortcutKey::Up,
            WinitKey::Named(NamedKey::ArrowDown) => ShortcutKey::Down,
            WinitKey::Named(NamedKey::ArrowLeft) => ShortcutKey::Left,
            WinitKey::Named(NamedKey::ArrowRight) => ShortcutKey::Right,
            WinitKey::Named(NamedKey::Home) => ShortcutKey::Home,
            WinitKey::Named(NamedKey::End) => ShortcutKey::End,
            WinitKey::Named(NamedKey::PageUp) => ShortcutKey::PageUp,
            WinitKey::Named(NamedKey::PageDown) => ShortcutKey::PageDown,
            WinitKey::Named(NamedKey::F1) => ShortcutKey::F(1),
            WinitKey::Named(NamedKey::F2) => ShortcutKey::F(2),
            WinitKey::Named(NamedKey::F3) => ShortcutKey::F(3),
            WinitKey::Named(NamedKey::F4) => ShortcutKey::F(4),
            WinitKey::Named(NamedKey::F5) => ShortcutKey::F(5),
            WinitKey::Named(NamedKey::F6) => ShortcutKey::F(6),
            WinitKey::Named(NamedKey::F7) => ShortcutKey::F(7),
            WinitKey::Named(NamedKey::F8) => ShortcutKey::F(8),
            WinitKey::Named(NamedKey::F9) => ShortcutKey::F(9),
            WinitKey::Named(NamedKey::F10) => ShortcutKey::F(10),
            WinitKey::Named(NamedKey::F11) => ShortcutKey::F(11),
            WinitKey::Character(text) => ShortcutKey::Char(text.chars().next()?),
            _ => return None,
        };
        Some(KeyStroke {
            key,
            ctrl: self.ctrl,
            shift: self.shift,
            alt: self.alt,
            meta: self.meta,
        })
    }

    fn paint_reorder_preview(&self, ui: &Ui<A::Message>, theme: &Theme, scene: &mut Scene) {
        let Some(Drag::Reorder {
            start, moved: true, ..
        }) = self.drag
        else {
            return;
        };
        // What moves is the row, even when what was grabbed is the grip inside it — at the
        // box it was carried from, which has gone with the content.
        let Some((id, src)) = self.reorder_carried() else {
            return;
        };
        let motion = self
            .tree
            .as_ref()
            .and_then(|t| find_widget(t.as_ref(), id))
            .map(reorder_motion)
            .unwrap_or(ReorderMotion::Columns);
        let dx = self.cursor.x - start.x;
        let dy = self.cursor.y - start.y;

        // The ghost's offset, per motion — see `ghost_offset`.
        let (gx, gy) = ghost_offset(motion, (dx, dy));

        // The owners of the grabbed item's **subtree**: used by the ghost, to capture a
        // rich card's content, which its children paint (milestone 251), **and** by the
        // vertical reflow, to lift the card out of the preview. Fallback: the card alone.
        let owners: std::collections::HashSet<u64> = self
            .tree
            .as_ref()
            .and_then(|t| find_widget(t.as_ref(), id))
            .map(|w| subtree_ids(w, id).iter().map(|i| i.as_u64()).collect())
            .unwrap_or_else(|| std::iter::once(id.as_u64()).collect());

        match motion {
            ReorderMotion::Columns => {
                // Reflow the neighbouring columns: the source's gap closes and the drop
                // slot opens, following the pointer's **smoothed** abscissa — a gentle
                // inertial slide, while the ghost sticks to the real pointer.
                let reflowed =
                    reflow_reorder_columns(scene.primitives(), src, self.reorder_x, id.as_u64());
                scene.clear();
                for primitive in reflowed {
                    scene.push_primitive(primitive);
                }
            }
            ReorderMotion::Slots(axis) => {
                // Reflow the **cards**: the lifted card's gap closes in the source
                // column and a slot opens under the **insertion line** in the target one.
                // Then the line is laid on top, at the chosen edge — the hovered half,
                // milestone 252.
                //
                // A **smoothed** line (milestone 265): the chosen slot's width, abscissa
                // and thickness are kept, but the **ordinate** is replaced by the
                // `reorder_y` spring — the line *and* the gap slide between cards, with
                // vertical inertia, instead of jumping a notch. A horizontal list's line
                // stands on its end, and its **abscissa** is the one that springs.
                let line =
                    self.reorder_drop_line(drag_preview::INSERT_THICKNESS)
                        .map(|r| match axis {
                            ReorderAxis::Vertical => Rect {
                                y: self.reorder_y,
                                ..r
                            },
                            ReorderAxis::Horizontal => Rect {
                                x: self.reorder_x,
                                ..r
                            },
                        });
                // Only what can be reordered makes room — a card, a row, a drop zone, and
                // what each of them paints. The reflow is geometric, and a button floating
                // over the list or the navigation bar under it shares the band without being
                // part of the list: moved with it, the first left its `+` a row above its own
                // disc on a phone (milestone 517).
                let movable = self
                    .tree
                    .as_ref()
                    .map(|tree| reorderable_owners(ui, tree.as_ref()))
                    .unwrap_or_default();
                let reflowed =
                    reflow_reorder_cards(scene.primitives(), src, line, &owners, &movable, axis);
                scene.clear();
                for primitive in reflowed {
                    scene.push_primitive(primitive);
                }
                if let Some(line) = line {
                    // Rounded across its thickness, whichever way it stands.
                    let thickness = match axis {
                        ReorderAxis::Vertical => line.height,
                        ReorderAxis::Horizontal => line.width,
                    };
                    scene.set_clip(Rect::UNBOUNDED);
                    scene.draw_rect(
                        line,
                        theme.primary,
                        theme.radius.min(thickness * 0.5),
                        0.0,
                        Color::TRANSPARENT,
                    );
                }
            }
        }

        // A faithful ghost: the grabbed item's primitives, taken from the original
        // scene, translated and **un-clipped**, since they would otherwise be cropped at
        // the source. In a **rich card** the background is painted by the card but its
        // content — label, tags, the × button — by children, under other owners, so we
        // capture the primitives of the item's **whole subtree**; see `owners` above.
        let ghost: Vec<Primitive> = ui
            .scene()
            .primitives()
            .iter()
            .filter(|p| owners.contains(&p.owner()))
            .map(|p| p.translated(gx, gy).with_clip(Rect::UNBOUNDED))
            .collect();
        draw_ghost_card(scene, theme, src.translate(gx, gy), &ghost);
    }

    /// The lifted item: its own primitives dimmed where it sits, and a copy of them
    /// floating under the pointer.
    ///
    /// The copy is taken from the frame rather than built again, so it cannot drift
    /// from what is on screen — a rebuilt "feedback" widget is a second definition of
    /// the same thing, and two definitions is one too many. The same reason the
    /// reorder ghost works this way.
    fn paint_drag_ghost(&self, ui: &Ui<A::Message>, theme: &Theme, scene: &mut Scene) {
        let Some(Drag::Item {
            source,
            start,
            moved: true,
            ..
        }) = &self.drag
        else {
            return;
        };
        let widget = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), source.id));
        // A rich item paints its background itself and its content through children,
        // under other owners, so the whole subtree is captured — the same reason the
        // reorder ghost does.
        let owners: std::collections::HashSet<u64> = widget
            .map(|w| {
                subtree_ids(w, source.id)
                    .iter()
                    .map(|i| i.as_u64())
                    .collect()
            })
            .unwrap_or_else(|| std::iter::once(source.id.as_u64()).collect());
        let opacity = widget.map(|w| w.drag_ghost_opacity()).unwrap_or(1.0);
        let dx = self.cursor.x - start.x;
        let dy = self.cursor.y - start.y;

        // What is left behind, faded in place: the item is being carried, not deleted.
        let original: Vec<Primitive> = scene.primitives().to_vec();
        scene.clear();
        for primitive in &original {
            if owners.contains(&primitive.owner()) {
                scene.push_faded(primitive, opacity);
            } else {
                scene.push_primitive(primitive.clone());
            }
        }

        let ghost: Vec<Primitive> = ui
            .scene()
            .primitives()
            .iter()
            .filter(|p| owners.contains(&p.owner()))
            .map(|p| p.translated(dx, dy).with_clip(Rect::UNBOUNDED))
            .collect();
        draw_ghost_card(scene, theme, source.rect.translate(dx, dy), &ghost);
    }

    /// The **insertion** line of the preview: a thin band at the edge of the hovered
    /// reorderable slot, a card, a row or a drop zone — the edge **before** it when the
    /// pointer is in its leading half, the edge **after** it in its trailing half. Across a
    /// vertical list; standing on its end in a horizontal one. `None` when the release would
    /// land nowhere.
    fn reorder_drop_line(&self, thickness: f32) -> Option<Rect> {
        let Some(Drag::Reorder {
            id, from, carried, ..
        }) = self.drag
        else {
            return None;
        };
        // The reorderable slot — card, row or drop zone — the release would land on: the
        // one under the pointer, or the nearest of the list's own.
        let target = self.reorder_drop_target(id, from, carried)?;
        let rect = self.ui.as_ref()?.widget_rect(target)?;
        let axis = match self
            .tree
            .as_ref()
            .and_then(|t| find_widget(t.as_ref(), target))
            .map(reorder_motion)
        {
            Some(ReorderMotion::Slots(axis)) => axis,
            _ => ReorderAxis::Vertical,
        };
        Some(drop_insertion_line(
            rect,
            thickness,
            self.reorder_insert_after(target, rect),
            axis,
            self.is_rtl(),
        ))
    }

    /// For a slot a reorderable is **inserted** at, tells whether insertion happens
    /// **after** it (index +1, between it and the next) — the pointer in its trailing half,
    /// which `reorder_drop_after` works out along the list's axis and reading direction.
    /// Always `false` for `Table`'s columns, which keep their drop logic unchanged. This is
    /// the insertion line's counterpart on the **routing** side.
    fn reorder_insert_after(&self, target: WidgetId, rect: Rect) -> bool {
        match self
            .tree
            .as_ref()
            .and_then(|t| find_widget(t.as_ref(), target))
            .map(reorder_motion)
        {
            Some(ReorderMotion::Slots(axis)) => {
                reorder_drop_after(self.cursor, rect, axis, self.is_rtl())
            }
            _ => false,
        }
    }

    /// The innermost detector that takes a drag under the pointer, with the way it drags.
    fn pan_target(&self) -> Option<(WidgetId, frus_widgets::PanAxis)> {
        let (id, _) = self.ui.as_ref()?.pan_at(self.cursor)?;
        let axis = find_widget(self.tree.as_ref()?.as_ref(), id)?.pan_axis()?;
        Some((id, axis))
    }

    /// `at`, in the coordinates of the detector `id`.
    fn pan_local(&self, id: WidgetId, at: Point) -> Point {
        let origin = self
            .ui
            .as_ref()
            .and_then(|ui| ui.widget_rect(id))
            .map_or(Point::new(0.0, 0.0), |rect| Point::new(rect.x, rect.y));
        Point::new(at.x - origin.x, at.y - origin.y)
    }

    /// Hands one moment of a drag to the detector `id`, and its message to the application.
    fn send_pan(&mut self, id: WidgetId, event: frus_widgets::PanEvent) {
        let rtl = self.is_rtl();
        let value = self.runtime.value(id);
        let (message, moved, released) = match self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
        {
            Some(widget) => {
                // A widget whose own value the drag moves — a switch's thumb (milestone
                // 638): held where the finger puts it, and asked what letting go there
                // means.
                let moved = widget.pan_value(event, value, rtl);
                let released = match event {
                    frus_widgets::PanEvent::End { .. } if self.runtime.value_placed(id) => {
                        Some(widget.on_value_release(value))
                    }
                    _ => None,
                };
                (widget.on_pan(event), moved, released)
            }
            None => (None, None, None),
        };
        if let Some(v) = moved {
            self.runtime.hold_value(id, v);
        }
        if let Some(release) = released {
            self.runtime.release_value(id);
            if let Some(message) = release {
                self.dispatch(message);
            }
        }
        if let Some(message) = message {
            self.dispatch(message);
        }
        self.request_redraw();
    }

    /// Sends a value drag's **start** or **end** to the widget being dragged, at
    /// `fraction` along its travel.
    ///
    /// The fraction is the one [`frus_widgets::DragTrack`] works out for every moment of
    /// the drag, from the same press and the same track: an end that disagreed with the
    /// last `on_drag` about where the value finished would be a slider that settles
    /// somewhere its own final message never mentioned.
    fn dispatch_drag_edge(&mut self, id: WidgetId, edge: Edge, fraction: f32) {
        let message = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| match edge {
                Edge::Start => widget.on_drag_start(fraction),
                Edge::End => widget.on_drag_end(fraction),
            });
        if let Some(message) = message {
            self.dispatch(message);
        }
    }

    /// A moment of a drag on one of a widget's thumbs (milestone 651).
    fn thumb_drag(
        &mut self,
        id: WidgetId,
        thumb: usize,
        moment: frus_widgets::ThumbDrag,
        fraction: f32,
    ) {
        if moment == frus_widgets::ThumbDrag::Start {
            // The widget paints the thumb it took raised and on top.
            self.runtime.input.thumb = Some((id, thumb));
        }
        let message = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.on_thumb_drag(thumb, moment, fraction));
        if let Some(message) = message {
            self.dispatch(message);
        }
    }

    /// One moment of a value drag: `dx` for a handle that accumulates, else the `value`
    /// the drag's track says this moment stands for — `None` when it changes nothing.
    fn apply_widget_drag(&mut self, id: WidgetId, dx: f32, value: Option<f32>) {
        let message = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| {
                widget
                    .on_drag_delta(dx)
                    .or_else(|| value.and_then(|v| widget.on_drag(v)))
            });
        if let Some(message) = message {
            self.dispatch(message);
        }
    }

    /// **A key going down**: everything the shell does with one, from the system's back key
    /// and the inspector to a shortcut, Tab, the arrows, activation and typing. Called with
    /// winit's event in a window, and with one a test made in the driver (milestone 608).
    /// `event_loop` is what Back quits through; with none, Back that would quit does nothing.
    fn key_down(&mut self, event: &KeyDown, event_loop: Option<&ActiveEventLoop>) {
        // A keyboard interaction: the focus ring becomes visible again.
        if !self.runtime.focus_visible {
            self.runtime.focus_visible = true;
            self.request_redraw();
        }

        // The **system** back — Android's button or gesture, the browser's back
        // key: it closes the topmost overlay, else pops a screen, else quits.
        if matches!(
            event.logical_key,
            WinitKey::Named(NamedKey::BrowserBack) | WinitKey::Named(NamedKey::GoBack)
        ) {
            if !event.repeat {
                if let Some(event_loop) = event_loop {
                    self.system_back(event_loop);
                }
            }
            return;
        }

        // F12 toggles the **inspector**: outlines, a card for the hovered
        // widget, and a tree dump on stderr. Debug builds only.
        if matches!(event.logical_key, WinitKey::Named(NamedKey::F12)) {
            if cfg!(debug_assertions) && !event.repeat {
                self.inspector = !self.inspector;
                self.inspector_dump = self.inspector;
                self.request_redraw();
            }
            return;
        }

        // **Shortcuts.** Placed after the system keys the shell owns outright
        // (back, F12) and before everything an application can bind, so that a
        // binding cannot take the inspector or the back gesture away.
        //
        // A stroke with no Ctrl, Alt or Meta goes to a focused field first: a
        // binding on a bare letter would otherwise make every field under it
        // impossible to type in.
        if let Some(stroke) = self.keystroke(event) {
            let typing = !stroke.is_command() && self.runtime.input.focused.is_some();
            if !typing {
                let msgs = self
                    .ui
                    .as_ref()
                    .map(|ui| ui.keystroke(stroke, self.runtime.input.focused))
                    .unwrap_or_default();
                if !msgs.is_empty() {
                    for msg in msgs {
                        self.dispatch(msg);
                    }
                    self.request_redraw();
                    return;
                }
            }
        }

        // Tab and Shift+Tab move between focusables, even with nothing focused.
        if matches!(event.logical_key, WinitKey::Named(NamedKey::Tab)) {
            let forward = !self.shift;
            let next = self
                .ui
                .as_ref()
                .and_then(|ui| ui.focus_next(self.runtime.input.focused, forward));
            if next.is_some() {
                self.runtime.input.focused = next;
                self.runtime.region = None;
                self.reveal_focus();
                self.request_redraw();
            }
            return;
        }

        // Escape walks **leaf to root** from the focused widget — an `OverlayPortal`
        // consumes it to close itself — and failing that closes the topmost
        // overlay, so Escape works with nothing focused.
        if matches!(event.logical_key, WinitKey::Named(NamedKey::Escape)) {
            // Auto-repeat does not trigger another close.
            if !event.repeat {
                self.escape();
            }
            return;
        }

        let Some(focused) = self.runtime.input.focused else {
            // With nothing focused, a selection an area holds still answers to the
            // clipboard's Copy and to Select all.
            self.region_key(event);
            return;
        };

        // Arrows navigate focus **geometrically** — except left and right in a
        // text field, where they move the caret; up and down navigate even out
        // of a single-line field.
        let arrow = match event.logical_key {
            WinitKey::Named(NamedKey::ArrowUp) => Some(FocusDirection::Up),
            WinitKey::Named(NamedKey::ArrowDown) => Some(FocusDirection::Down),
            WinitKey::Named(NamedKey::ArrowLeft) => Some(FocusDirection::Left),
            WinitKey::Named(NamedKey::ArrowRight) => Some(FocusDirection::Right),
            _ => None,
        };
        // PgUp and PgDn jump a **page** inside a multi-line field, bounded to
        // the field so they never leave it. No effect anywhere else.
        if matches!(
            event.logical_key,
            WinitKey::Named(NamedKey::PageUp) | WinitKey::Named(NamedKey::PageDown)
        ) {
            let down = matches!(event.logical_key, WinitKey::Named(NamedKey::PageDown));
            if self.move_caret_vertical(focused, down, true) {
                return;
            }
        }

        if let Some(direction) = arrow {
            // In a **multi-line** field, Up and Down move the caret between
            // lines while it stays in the field; on the first or last line we
            // fall back to focus navigation and leave the field.
            if matches!(direction, FocusDirection::Up | FocusDirection::Down) {
                let down = matches!(direction, FocusDirection::Down);
                if self.move_caret_vertical(focused, down, false) {
                    return;
                }
            }

            // Left and right arrows are offered to the focused widget first —
            // a range slider, say — through `on_key`. If it consumes them, focus
            // does not move.
            if matches!(direction, FocusDirection::Left | FocusDirection::Right) {
                let key = if matches!(direction, FocusDirection::Left) {
                    Key::Left {
                        shift: self.shift,
                        word: self.ctrl,
                    }
                } else {
                    Key::Right {
                        shift: self.shift,
                        word: self.ctrl,
                    }
                };
                let widget = self
                    .tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), focused));
                // A reorderable header moves its column by one; we capture its
                // position to announce it, the keyboard being how screen-reader
                // users reorder.
                let reorder_from = widget.and_then(|w| w.reorder_index());
                let handled = widget.map(|w| w.on_key(&key));
                if let Some(KeyResponse::Handled(message)) = handled {
                    if let Some(message) = message {
                        self.dispatch(message);
                    }
                    if let Some(from) = reorder_from {
                        let to = if matches!(direction, FocusDirection::Left) {
                            from.wrapping_sub(1)
                        } else {
                            from + 1
                        };
                        self.set_announcement(format!("Column moved to position {}", to + 1));
                    }
                    self.request_redraw();
                    return;
                }
            }

            let is_text = self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), focused))
                .is_some_and(is_text_field);
            let navigates =
                !is_text || matches!(direction, FocusDirection::Up | FocusDirection::Down);
            if navigates {
                if let Some(next) = self
                    .ui
                    .as_ref()
                    .and_then(|ui| ui.focus_directional(focused, direction))
                {
                    self.runtime.input.focused = Some(next);
                    self.reveal_focus();
                    self.request_redraw();
                }
                return;
            }
        }

        // Home and End are offered to the focused widget — a range slider maps
        // them to min and max — before the default action. A text field ignores
        // them here (`on_key` returns Ignored) and falls back to ordinary
        // editing further down.
        if matches!(
            event.logical_key,
            WinitKey::Named(NamedKey::Home) | WinitKey::Named(NamedKey::End)
        ) {
            let key = if matches!(event.logical_key, WinitKey::Named(NamedKey::Home)) {
                Key::Home {
                    shift: self.shift,
                    doc: self.ctrl,
                }
            } else {
                Key::End {
                    shift: self.shift,
                    doc: self.ctrl,
                }
            };
            let handled = self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), focused))
                .map(|widget| widget.on_key(&key));
            if let Some(KeyResponse::Handled(message)) = handled {
                if let Some(message) = message {
                    self.dispatch(message);
                }
                self.request_redraw();
                return;
            }
        }

        // Keyboard activation, Enter or Space, of a clickable focusable: a
        // button, a checkbox, a switch. Text fields, which have no `on_click`,
        // fall back to ordinary editing — Enter submits, Space is a space.
        if matches!(
            event.logical_key,
            WinitKey::Named(NamedKey::Enter) | WinitKey::Named(NamedKey::Space)
        ) {
            let widget = self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), focused))
                .filter(|widget| widget.focusable());
            let message = widget.and_then(|widget| widget.on_click());
            if let Some(message) = message {
                // Auto-repeat does not machine-gun the activation: holding
                // Space on a button is one single click.
                if !event.repeat {
                    // The spoken announcement of the effect — a sort, a
                    // selection — captured before `dispatch` rebuilds the tree.
                    let announce = widget.and_then(|widget| widget.announce());
                    self.dispatch(message);
                    if let Some(announce) = announce {
                        self.set_announcement(announce);
                    }
                    self.request_redraw();
                }
                return;
            }
        }

        // The clipboard: Ctrl+C/X/V, and a keyboard's own Copy, Cut and Paste.
        if let Some(command) = clipboard_command(&event.logical_key, event.physical_key, self.ctrl)
        {
            match command {
                ClipCommand::Copy => {
                    self.copy_selection(focused);
                }
                ClipCommand::Cut => self.cut_selection(focused),
                ClipCommand::Paste => {
                    // Answered now, or — on the Web — on a later frame.
                    if let Some(pasted) = self.clipboard.paste(focused, self.window.as_ref()) {
                        self.land_paste(pasted);
                    }
                }
            }
            return;
        }

        // The context-menu key, or Shift+F10: the selection bar for someone with no
        // pointer to hold or right-click with (milestone 568). Only a text field has
        // one, and it is opened on the field that has the focus.
        if opens_selection_bar(&event.logical_key, self.shift)
            && self
                .tree
                .as_ref()
                .and_then(|tree| find_widget(tree.as_ref(), focused))
                .is_some_and(|widget| widget.text_value().is_some())
        {
            self.show_selection_toolbar(focused);
            return;
        }

        // The other editing shortcuts, Ctrl+A/Z/Y.
        if self.ctrl {
            match &event.logical_key {
                WinitKey::Character(c) if c.eq_ignore_ascii_case("a") => {
                    self.select_all(focused);
                    return;
                }
                // Undo, and redo under both its spellings — Ctrl+Y on Windows,
                // Ctrl+Shift+Z everywhere else, and people bring the one their
                // hands already know.
                WinitKey::Character(c) if c.eq_ignore_ascii_case("z") && !self.shift => {
                    self.step_history(focused, false);
                    self.request_redraw();
                    return;
                }
                WinitKey::Character(c)
                    if c.eq_ignore_ascii_case("y")
                        || (c.eq_ignore_ascii_case("z") && self.shift) =>
                {
                    self.step_history(focused, true);
                    self.request_redraw();
                    return;
                }
                _ => {}
            }
        }

        // With the input bridge active, editing goes EXCLUSIVELY through the
        // InputConnection, that is, the IME queue — the bridge view receives the
        // hardware keys too. Without this guard every keystroke would arrive
        // twice, once from winit's native queue and once from the bridge.
        #[cfg(android)]
        if crate::android_ime::installed() {
            return;
        }

        let shift = self.shift;
        let key = match &event.logical_key {
            WinitKey::Named(NamedKey::Backspace) => Some(Key::Backspace),
            WinitKey::Named(NamedKey::Delete) => Some(Key::Delete),
            // Repeating Enter does not submit again; text and deletion do
            // repeat normally.
            WinitKey::Named(NamedKey::Enter) if !event.repeat => Some(Key::Enter),
            WinitKey::Named(NamedKey::Enter) => None,
            // With Ctrl, Left/Right jump a word and Home/End bound the field.
            WinitKey::Named(NamedKey::ArrowLeft) => Some(Key::Left {
                shift,
                word: self.ctrl,
            }),
            WinitKey::Named(NamedKey::ArrowRight) => Some(Key::Right {
                shift,
                word: self.ctrl,
            }),
            WinitKey::Named(NamedKey::Home) => Some(Key::Home {
                shift,
                doc: self.ctrl,
            }),
            WinitKey::Named(NamedKey::End) => Some(Key::End {
                shift,
                doc: self.ctrl,
            }),
            WinitKey::Named(NamedKey::Space) => Some(Key::Text(" ".to_string())),
            // Android delivers Enter as `Character("\n")`, through the
            // KeyCharacterMap, rather than `Named(Enter)`: the same submission,
            // without inserting a line break into the field.
            WinitKey::Character(c) if c == "\n" || c == "\r" => {
                if event.repeat {
                    None
                } else {
                    Some(Key::Enter)
                }
            }
            _ => event.text.as_ref().map(|text| Key::Text(text.to_string())),
        };

        if let Some(key) = key {
            self.apply_key(focused, key);
            self.request_redraw();
        }
    }

    /// The **system** back — Android's `KEYCODE_BACK`, the browser's back key — and
    /// its native chain: ① the topmost overlay closes, be it a sheet, a drawer, a modal
    /// or a menu; ② failing that a screen is popped, by replaying the **back gesture
    /// already committed**, through the same hooks as the swipe, so it settles with an
    /// animation; ③ failing that, at the root, back **quits the application**, as
    /// Android expects.
    fn system_back(&mut self, event_loop: &ActiveEventLoop) {
        if !self.system_back_step() {
            event_loop.exit();
        }
    }

    /// What the system's Back does short of leaving the application, and whether it did
    /// anything: `false` means there was nothing left to go back from.
    fn system_back_step(&mut self) -> bool {
        // An open selection bar goes first, as a platform's own text selection does: Back
        // closes it before it closes anything behind it (milestone 568).
        if self.close_selection_toolbar() {
            return true;
        }
        // Then a selection an area holds with its bar, as for a field's.
        if self
            .runtime
            .region
            .as_ref()
            .is_some_and(|selection| selection.bar)
        {
            self.runtime.region = None;
            self.request_redraw();
            return true;
        }
        if let Some(message) = self.ui.as_ref().and_then(|ui| ui.top_dismiss()) {
            self.dispatch(message);
            self.request_redraw();
            return true;
        }
        if self.app.can_go_back() {
            self.build_dirty = true;
            // A pop, not a swipe: no finger is on the page (milestone 622).
            self.app.go_back();
            self.request_redraw();
            return true;
        }
        false
    }

    /// Routes **Escape**: a leaf-to-root walk from the focused widget, with a
    /// three-state result — `Ignored` keeps walking up, `Handled` consumes, `Skip` stops
    /// with no fallback — then falls back to closing the topmost overlay when nobody
    /// answered, or when nothing is focused.
    fn escape(&mut self) {
        // The selection bar first, as for the system's Back (milestone 568).
        if self.close_selection_toolbar() {
            return;
        }
        // Then a selection an area holds.
        if self.runtime.region.take().is_some() {
            self.request_redraw();
            return;
        }
        // 1) Walk up the focus path. `Some(None)` means consumed with no message; an
        // outer `None` means the whole path ignored it, so we fall back.
        let outcome: Option<Option<A::Message>> = self.runtime.input.focused.and_then(|focused| {
            let tree = self.tree.as_ref()?;
            let path = find_path(tree.as_ref(), focused);
            for widget in path.iter().rev() {
                match widget.on_key(&Key::Escape) {
                    KeyResponse::Handled(message) => return Some(message),
                    KeyResponse::Skip => return Some(None),
                    KeyResponse::Ignored => {}
                }
            }
            None
        });

        match outcome {
            Some(message) => {
                if let Some(message) = message {
                    self.dispatch(message);
                    self.request_redraw();
                }
            }
            // 2) Nobody on the path, or nothing focused: the topmost overlay.
            None => {
                if let Some(message) = self.ui.as_ref().and_then(|ui| ui.top_dismiss()) {
                    self.dispatch(message);
                    self.request_redraw();
                }
            }
        }
    }

    /// Moves the caret vertically in the focused multi-line field — Up/Down when
    /// `page` is false, PgUp/PgDn otherwise — preserving the **remembered goal column**.
    /// Applies the selection under Shift and reveals the caret. Returns `true` when the
    /// caret moved within the field, `false` otherwise, in which case the shell
    /// navigates focus instead.
    fn move_caret_vertical(&mut self, id: WidgetId, down: bool, page: bool) -> bool {
        let width = self
            .ui
            .as_ref()
            .and_then(|ui| ui.widget_rect(id))
            .map(|r| r.width)
            .unwrap_or(0.0);
        let cursor = self.runtime.edits.get(&id).map(|e| e.cursor).unwrap_or(0);
        let moved = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.caret_vertical(width, cursor, down, page, self.goal_x));
        let Some((new_cursor, goal)) = moved else {
            return false;
        };
        let shift = self.shift;
        let edit = self.runtime.edits.entry(id).or_default();
        if shift {
            if edit.anchor.is_none() {
                edit.anchor = Some(edit.cursor);
            }
        } else {
            edit.anchor = None;
        }
        edit.cursor = new_cursor;
        // Remember the goal column for the next vertical jump.
        self.goal_x = Some(goal);
        self.reveal_caret(id, new_cursor);
        self.request_redraw();
        true
    }

    /// A hold in field `id` selects the word under the finger — the press has already
    /// put the caret there — and gives the selection its handles (milestone 511).
    fn select_held_word(&mut self, id: WidgetId) {
        let cursor = self.runtime.edits.get(&id).map(|e| e.cursor).unwrap_or(0);
        let word = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.word_at(cursor))
            .filter(|(start, end)| start < end);
        let Some((start, end)) = word else {
            // Nothing to select — an empty field, a hold past the end of the text. The
            // bar still opens, at the caret, with Paste and whatever else applies.
            self.show_selection_toolbar(id);
            return;
        };
        self.runtime.edits.insert(
            id,
            Edit {
                cursor: end,
                anchor: Some(start),
                composing: None,
            },
        );
        self.runtime.selection_handles = Some(id);
        self.runtime.close_edit_run(id);
        self.show_selection_toolbar(id);
        #[cfg(android)]
        self.push_ime_context(id);
    }

    /// The selection handle under the pointer, taken: a drag that moves its end of the
    /// focused field's selection. `None` when no handle is showing there.
    fn grab_selection_handle(&self) -> Option<Drag> {
        let id = self.runtime.selection_handles?;
        if self.runtime.input.focused != Some(id) {
            return None;
        }
        let rect = self.ui.as_ref()?.widget_rect(id)?;
        let edit = self.runtime.edits.get(&id).copied()?;
        let scroll_y = self.runtime.scroll.get(&id).map(|s| s.1).unwrap_or(0.0);
        let handles = find_widget(self.tree.as_ref()?.as_ref(), id)?
            .selection_handles(rect.width, &edit, scroll_y)?;
        let local = Point::new(self.cursor.x - rect.x, self.cursor.y - rect.y);
        let handle = crate::selection::grab(&handles, local)?;
        let at = handles[handle.index()].line_center;
        Some(Drag::SelectionHandle {
            id,
            rect,
            handle,
            grab: Point::new(at.x - local.x, at.y - local.y),
        })
    }

    /// Routes a key to the focused field: updates the editing state and applies
    /// whatever message comes out, a value change or a submission.
    fn apply_key(&mut self, id: WidgetId, key: Key) {
        // Any horizontal move, or any keystroke, forgets the vertical goal column.
        self.goal_x = None;
        // Typing puts a touch selection's handles away, as a press does (milestone 511) —
        // and the bar over it (milestone 568).
        self.runtime.selection_handles = None;
        self.runtime.selection_toolbar = None;
        let was = self.runtime.edits.get(&id).copied().unwrap_or_default();
        let mut edit = was;
        let widget = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id));
        // What the field held before the key: half of an undo step, and the half the
        // application owns.
        let before = widget
            .and_then(|widget| widget.text_value())
            .map(str::to_owned);
        // A field's own announcement (#18) — read here for the same reason the click
        // and keyboard-activation paths read theirs off the widget **before**
        // `dispatch_edit` rebuilds the tree: a plain keystroke leaves it unused, since
        // `on_edit` answers `None` for one and the announcement below is never spoken.
        let announce = widget.and_then(|widget| widget.announce());
        let message = widget.and_then(|widget| widget.on_edit(&mut edit, &key));
        self.runtime.edits.insert(id, edit);
        // In a multi-line field, make the retained scroll follow the caret and reveal it.
        self.reveal_caret(id, edit.cursor);
        if let Some(message) = message {
            self.dispatch_edit(message);
            if let Some(announce) = announce {
                self.set_announcement(announce);
            }
        }
        // The history, recorded on the **evidence** of a changed value rather than on the
        // intent of a key that usually changes one: a filter may have refused the
        // character, a length limit may have swallowed it, a read-only field ignores it,
        // and an Enter submits instead of typing. The value is read again from the tree
        // the dispatch has just rebuilt, so what is recorded is what happened.
        let after = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.text_value())
            .map(str::to_owned);
        match (before, after) {
            (Some(before), Some(after)) if before != after => {
                let kind = EditKind::of(&key, was.selection_range().is_some(), self.composing());
                let since = self.since_last_edit();
                self.runtime
                    .record_edit(id, EditSnapshot::new(before, was), kind, since);
            }
            // A key that moved only the caret ends the run: what is typed next is a step
            // of its own, or one undo would take back two visits to the field at once.
            (Some(_), _) => self.runtime.close_edit_run(id),
            _ => {}
        }
    }

    /// Dispatches a message that changed a field's value, and refreshes the tree at once.
    ///
    /// Keys can arrive in **bursts**, faster than a frame — a software keyboard, `adb
    /// input text`, auto-repeat — and the next one must see the CURRENT value, not the
    /// retained tree's, or it would overwrite the previous keystroke. So the tree is
    /// refreshed right away; `build_dirty` stays raised and the next frame redoes the full
    /// pass: mounts, leaving fades and all.
    fn dispatch_edit(&mut self, message: A::Message) {
        self.dispatch(message);
        if let Some((width, height)) = self.last_size {
            let theme = self.themes.displayed(&self.app);
            // A surface of its own, because this build happens between frames rather than
            // inside one — and the same `build_view` as the frame path, because the next
            // key in the burst reads this tree straight away.
            let tree = self
                .media_query(width, height)
                .scope(|| build_view(&self.app, &theme, &self.runtime));
            self.tree = Some(tree);
        }
    }

    /// Seconds since the last recorded edit, and stamps this one. The first edit is
    /// infinitely far from the one before it, which is to say it starts a run.
    fn since_last_edit(&mut self) -> f32 {
        let now = Instant::now();
        let since = self
            .last_edit_at
            .map(|then| now.duration_since(then).as_secs_f32())
            .unwrap_or(f32::INFINITY);
        self.last_edit_at = Some(now);
        since
    }

    /// Whether an input method is in the middle of composing a word.
    fn composing(&self) -> bool {
        self.runtime
            .input
            .focused
            .and_then(|id| self.runtime.edits.get(&id))
            .is_some_and(|edit| edit.composing.is_some())
    }

    /// Steps a text field's value back one change, or forward again. `true` when something
    /// moved — Ctrl+Z on anything that is not a field, or with nothing left to undo, moves
    /// nothing and says so.
    fn step_history(&mut self, id: WidgetId, forward: bool) -> bool {
        let value = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.text_value())
            .map(str::to_owned);
        let Some(value) = value else {
            return false;
        };
        let edit = self.runtime.edits.get(&id).copied().unwrap_or_default();
        let current = EditSnapshot::new(value, edit);
        let target = if forward {
            self.runtime.redo_edit(id, current)
        } else {
            self.runtime.undo_edit(id, current)
        };
        let Some(target) = target else {
            return false;
        };
        let message = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.replace_value(target.value.clone()));
        // The caret goes back with the text — an undo that restores the value and leaves
        // the caret at the end has done half the job.
        self.runtime.edits.insert(id, target.edit);
        self.reveal_caret(id, target.edit.cursor);
        if let Some(message) = message {
            self.dispatch_edit(message);
        }
        // An undo is not a keystroke: what is typed after it starts a run of its own,
        // however quickly it follows.
        self.last_edit_at = None;
        true
    }

    /// Brings the focused widget **into view**, gliding every scroll region around it.
    ///
    /// Called wherever the keyboard moves the focus, and nowhere else. A click already
    /// landed on something the eye could see, and a focus restored because an overlay
    /// closed should put the page back where the reader left it, not chase whatever the
    /// restoration happened to pick.
    ///
    /// The glide is a **target**, not a jump: the same easing a scrollbar drag or a page
    /// request uses, so Tab through a form reads as one movement rather than a series of
    /// cuts. Anything already moving the offset is let go of — the keyboard has just
    /// overruled it.
    fn reveal_focus(&mut self) {
        let Some(id) = self.runtime.input.focused else {
            return;
        };
        let Some(moves) = self.ui.as_ref().map(|ui| ui.reveal(id, &self.runtime)) else {
            return;
        };
        for (area, offset) in moves {
            self.runtime.scroll_ballistic.remove(&area);
            self.runtime.scroll_velocity.remove(&area);
            self.runtime.scroll_target.insert(area, offset);
        }
    }

    /// Makes a multi-line field's retained scroll **follow the caret**: adjusts
    /// `runtime.scroll[id]` just enough to keep the caret visible, the way an editor
    /// re-centres as you type. A no-op for a field that does not scroll.
    fn reveal_caret(&mut self, id: WidgetId, cursor: usize) {
        let Some(vp) = self.ui.as_ref().and_then(|ui| ui.scrollable_viewport(id)) else {
            return;
        };
        let metrics = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.text_metrics(vp.width, cursor));
        let Some((content_h, visible_h, caret_top, caret_h)) = metrics else {
            return;
        };
        let max_y = (content_h - visible_h).max(0.0);
        let cur = self.runtime.scroll.get(&id).map(|s| s.1).unwrap_or(0.0);
        // The scroll window in which the caret stays visible, from "the caret's bottom
        // is visible" to "the caret's top is visible". We bring the current scroll into it.
        let lo = (caret_top + caret_h - visible_h).max(0.0);
        let hi = caret_top;
        let target = cur.clamp(lo.min(hi), lo.max(hi)).clamp(0.0, max_y);
        self.runtime.scroll.insert(id, (0.0, target));
        self.runtime.scroll_target.insert(id, (0.0, target));
        self.runtime.scroll_velocity.remove(&id);
    }

    /// Copies field `id`'s selected text to the clipboard. `false` when there was nothing
    /// to copy — no selection, or a field that gives its text to nobody (a masked one).
    fn copy_selection(&mut self, id: WidgetId) -> bool {
        let edit = self.runtime.edits.get(&id).copied().unwrap_or_default();
        let text = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| widget.selected_text(&edit));
        match text {
            Some(text) => {
                self.clipboard.set_text(text);
                true
            }
            None => false,
        }
    }

    /// The texts of `area` in the frame on screen, in reading order, each with its length in
    /// characters — what a selection over them is worked out from.
    fn region_stops(&self, area: WidgetId) -> Vec<(WidgetId, usize)> {
        let (Some(ui), Some(tree)) = (self.ui.as_ref(), self.tree.as_ref()) else {
            return Vec::new();
        };
        ui.text_stops_in(area)
            .filter_map(|stop| {
                let text = find_widget(tree.as_ref(), stop.id)?.selection_text()?;
                Some((stop.id, text.chars().count()))
            })
            .collect()
    }

    /// The selection from `anchor` to `extent` in `area`, in the frame on screen.
    fn region_selection(
        &self,
        area: WidgetId,
        anchor: RegionPoint,
        extent: RegionPoint,
    ) -> RegionSelection {
        RegionSelection::new(area, anchor, extent, &self.region_stops(area))
    }

    /// The character boundary of `stop`'s text nearest `at`, by the layout it was drawn with.
    fn region_index(&self, stop: &TextStop, at: Point) -> Option<usize> {
        find_widget(self.tree.as_ref()?.as_ref(), stop.id)?.selection_hit(
            at.x - stop.rect.x,
            at.y - stop.rect.y,
            stop.rect.width,
        )
    }

    /// A press at the pointer over words in a selection area, if nothing else has a claim on
    /// it: the selection begins there, empty, and follows the pointer until it lifts. A double
    /// click selects the word.
    fn begin_region_selection(&mut self) {
        let Some(stop) = self.region_press_target() else {
            return;
        };
        let Some(index) = self.region_index(&stop, self.cursor) else {
            return;
        };
        let now = Instant::now();
        let here = self.cursor;
        let double = self.last_region_click.is_some_and(|(then, there)| {
            (now - then).as_secs_f32() < 0.4
                && (here.x - there.x).hypot(here.y - there.y) <= REGION_DOUBLE_CLICK_SLOP
        });
        self.last_region_click = Some((now, here));
        let word = double
            .then(|| {
                let tree = self.tree.as_ref()?;
                let text = find_widget(tree.as_ref(), stop.id)?.selection_text()?;
                Some(frus_widgets::word_bounds(text, index))
            })
            .flatten();
        let (anchor, extent) = match word {
            Some((start, end)) => (
                RegionPoint {
                    text: stop.id,
                    index: start,
                },
                RegionPoint {
                    text: stop.id,
                    index: end,
                },
            ),
            None => {
                let point = RegionPoint {
                    text: stop.id,
                    index,
                };
                (point, point)
            }
        };
        self.runtime.region = Some(self.region_selection(stop.area, anchor, extent));
        // A word is a whole selection: there is nothing to drag out of it.
        self.drag = word
            .is_none()
            .then_some(Drag::RegionSelect { area: stop.area });
        self.request_redraw();
    }

    /// The text of a selection area under the pointer, if a press there is the area's to take:
    /// something that answers a press — a button, a tappable row, a link — keeps it.
    fn region_press_target(&self) -> Option<TextStop> {
        let ui = self.ui.as_ref()?;
        let claimed = self
            .runtime
            .input
            .pressed
            .is_some_and(|pressed| ui.msg_for(pressed).is_some());
        if claimed {
            return None;
        }
        ui.text_stop_at(self.cursor)
    }

    /// A finger held on words in a selection area: the word under it is selected and the bar
    /// opens over it. Whether there was a word.
    fn select_region_word_held(&mut self) -> bool {
        let Some(stop) = self.ui.as_ref().and_then(|ui| ui.text_stop_at(self.cursor)) else {
            return false;
        };
        let Some(index) = self.region_index(&stop, self.cursor) else {
            return false;
        };
        let word = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), stop.id))
            .and_then(|widget| widget.selection_text())
            .map(|text| frus_widgets::word_bounds(text, index))
            .filter(|(start, end)| start < end);
        let Some((start, end)) = word else {
            return false;
        };
        let anchor = RegionPoint {
            text: stop.id,
            index: start,
        };
        let extent = RegionPoint {
            text: stop.id,
            index: end,
        };
        self.runtime.region = Some(
            self.region_selection(stop.area, anchor, extent)
                .with_bar(true),
        );
        self.request_redraw();
        true
    }

    /// The two handles of a selection area's touch selection, where they are on the surface.
    fn region_handles(&self) -> Option<(WidgetId, [frus_widgets::SelectionHandle; 2])> {
        let selection = self.runtime.region.as_ref().filter(|s| s.handles)?;
        let (ui, tree) = (self.ui.as_ref()?, self.tree.as_ref()?);
        let at = |point: RegionPoint, start: bool| {
            let stop = ui
                .text_stops_in(selection.area)
                .find(|s| s.id == point.text)?;
            let handle = find_widget(tree.as_ref(), point.text)?.selection_grip(
                stop.rect.width,
                point.index,
                start,
            )?;
            let (dx, dy) = (stop.rect.x, stop.rect.y);
            Some(frus_widgets::SelectionHandle {
                rect: handle.rect.translate(dx, dy),
                line_center: Point::new(handle.line_center.x + dx, handle.line_center.y + dy),
            })
        };
        Some((
            selection.area,
            [at(selection.start?, true)?, at(selection.end?, false)?],
        ))
    }

    /// The handle of a selection area's touch selection under the pointer, taken.
    fn grab_region_handle(&self) -> Option<Drag> {
        let (area, handles) = self.region_handles()?;
        let handle = crate::selection::grab(&handles, self.cursor)?;
        let at = handles[handle.index()].line_center;
        Some(Drag::RegionHandle {
            area,
            handle,
            grab: Point::new(at.x - self.cursor.x, at.y - self.cursor.y),
        })
    }

    /// A handle of a selection area moved with the finger: its end goes to the text position
    /// under it — carried by `grab`, so the handle's line and not the fingertip picks it — and
    /// the other end stays. The two never meet nor cross, as a field's do not.
    fn drag_region_handle(
        &mut self,
        area: WidgetId,
        handle: crate::selection::Handle,
        grab: Point,
    ) {
        let Some(selection) = self.runtime.region.as_ref() else {
            return;
        };
        let (Some(start), Some(end)) = (selection.start, selection.end) else {
            return;
        };
        let target = Point::new(self.cursor.x + grab.x, self.cursor.y + grab.y);
        let Some(stop) = self
            .ui
            .as_ref()
            .and_then(|ui| ui.nearest_text_stop(area, target))
        else {
            return;
        };
        let Some(index) = self.region_index(&stop, target) else {
            return;
        };
        let moved = RegionPoint {
            text: stop.id,
            index,
        };
        let stops = self.region_stops(area);
        let order = |point: RegionPoint| {
            stops
                .iter()
                .position(|(id, _)| *id == point.text)
                .map(|at| (at, point.index))
        };
        let (Some(to), Some(other)) = (
            order(moved),
            order(match handle {
                crate::selection::Handle::Start => end,
                crate::selection::Handle::End => start,
            }),
        ) else {
            return;
        };
        let (fixed, crosses) = match handle {
            crate::selection::Handle::Start => (end, to >= other),
            crate::selection::Handle::End => (start, to <= other),
        };
        if crosses {
            return;
        }
        let next = RegionSelection::new(area, fixed, moved, &stops).with_bar(true);
        // The bar stays put away until the handle is let go.
        let next = RegionSelection { bar: false, ..next };
        if self.runtime.region.as_ref() != Some(&next) {
            self.runtime.region = Some(next);
            self.request_redraw();
        }
    }

    /// The pointer has moved during a drag in `area`: the far end of the selection goes to the
    /// text nearest it.
    fn extend_region_selection(&mut self, area: WidgetId) {
        let Some(anchor) = self.runtime.region.as_ref().map(|region| region.anchor) else {
            return;
        };
        let Some(stop) = self
            .ui
            .as_ref()
            .and_then(|ui| ui.nearest_text_stop(area, self.cursor))
        else {
            return;
        };
        let Some(index) = self.region_index(&stop, self.cursor) else {
            return;
        };
        let extent = RegionPoint {
            text: stop.id,
            index,
        };
        let selection = self.region_selection(area, anchor, extent);
        if self.runtime.region.as_ref() != Some(&selection) {
            self.runtime.region = Some(selection);
            self.request_redraw();
        }
    }

    /// The words a selection area has selected, as they are copied: one line per text. `None`
    /// when nothing is selected.
    fn region_text(&self) -> Option<String> {
        let region = self.runtime.region.as_ref()?;
        let (ui, tree) = (self.ui.as_ref()?, self.tree.as_ref()?);
        let texts: Vec<(WidgetId, &str)> = ui
            .text_stops_in(region.area)
            .filter_map(|stop| {
                let text = find_widget(tree.as_ref(), stop.id)?.selection_text()?;
                Some((stop.id, text))
            })
            .collect();
        let copied = frus_widgets::region_copy(&texts, &region.ranges);
        (!copied.is_empty()).then_some(copied)
    }

    /// Puts the words a selection area has selected on the clipboard. Whether there were any.
    fn copy_region(&mut self) -> bool {
        match self.region_text() {
            Some(copied) => {
                self.clipboard.set_text(copied);
                true
            }
            None => false,
        }
    }

    /// Selects every text of the area that holds a selection.
    fn select_all_region(&mut self) {
        let Some(area) = self.runtime.region.as_ref().map(|region| region.area) else {
            return;
        };
        let stops = self.region_stops(area);
        let (Some(first), Some(last)) = (stops.first(), stops.last()) else {
            return;
        };
        let anchor = RegionPoint {
            text: first.0,
            index: 0,
        };
        let extent = RegionPoint {
            text: last.0,
            index: last.1,
        };
        let bar = self
            .runtime
            .region
            .as_ref()
            .is_some_and(|selection| selection.bar);
        self.runtime.region = Some(self.region_selection(area, anchor, extent).with_bar(bar));
        self.request_redraw();
    }

    /// A key while nothing has the focus: Copy, and Select all, act on a selection an area
    /// holds. Whether the key was one of them.
    fn region_key(&mut self, event: &KeyDown) -> bool {
        if self.runtime.region.is_none() {
            return false;
        }
        if let Some(ClipCommand::Copy) =
            clipboard_command(&event.logical_key, event.physical_key, self.ctrl)
        {
            self.copy_region();
            return true;
        }
        let select_all = self.ctrl
            && matches!(&event.logical_key, WinitKey::Character(c) if c.eq_ignore_ascii_case("a"));
        if select_all {
            self.select_all_region();
            return true;
        }
        false
    }

    /// Cuts field `id`'s selection: copies it, then deletes it — **only if it was copied**.
    /// A masked field refuses the copy, and a cut that deleted anyway would destroy the
    /// text while putting it nowhere.
    fn cut_selection(&mut self, id: WidgetId) {
        if self.copy_selection(id) {
            self.apply_key(id, Key::Backspace);
            self.request_redraw();
        }
    }

    /// Selects all of field `id`'s text.
    fn select_all(&mut self, id: WidgetId) {
        self.runtime.edits.insert(
            id,
            Edit {
                cursor: usize::MAX,
                anchor: Some(0),
                composing: None,
            },
        );
        // A selection is a caret move: what is typed over it is a step of its own, not more
        // of whatever was being typed before.
        self.runtime.close_edit_run(id);
        self.request_redraw();
    }

    /// Opens field `id`'s **selection bar** — Cut, Copy, Paste, Select all — over its
    /// selection (milestone 568). Whether the clipboard holds text is asked once, here, and
    /// kept for as long as the bar is open: it is what decides whether Paste is offered.
    fn show_selection_toolbar(&mut self, id: WidgetId) {
        self.show_selection_toolbar_at(id, None);
    }

    /// The same, opened by a right-click at `at`: the bar goes there instead of to the
    /// selection (milestone 618).
    fn show_selection_toolbar_at(&mut self, id: WidgetId, at: Option<Point>) {
        let can_paste = self.clipboard.has_text();
        self.runtime.selection_toolbar = Some(ToolbarMark { id, can_paste, at });
        self.request_redraw();
    }

    /// What Back and Escape do to an open selection bar: put it away, with the handles that
    /// went with it, and say so — `true` — so that the key goes no further.
    fn close_selection_toolbar(&mut self) -> bool {
        if self.runtime.selection_toolbar.is_none() {
            return false;
        }
        self.runtime.selection_handles = None;
        self.hide_selection_toolbar();
        true
    }

    /// Puts the bar away, if one is open.
    fn hide_selection_toolbar(&mut self) {
        if self.runtime.selection_toolbar.take().is_some() {
            self.request_redraw();
        }
    }

    /// What pressing a built-in button of the selection bar does, to the field the bar is
    /// open on. Copy, Cut and Paste close it and the handles with it; Select all leaves
    /// both open on a phone, on the selection it has just made larger, and closes both on a
    /// desktop (milestone 625).
    fn perform_edit_action(&mut self, action: frus_widgets::EditAction) {
        use frus_widgets::EditAction;
        // The bar of a selection area's selection, which acts on the area and not on a field.
        if self
            .runtime
            .region
            .as_ref()
            .is_some_and(|selection| selection.bar)
        {
            match action {
                EditAction::Copy => {
                    // As a platform's own selection does after a copy: it is put away.
                    self.copy_region();
                    self.runtime.region = None;
                }
                EditAction::SelectAll => self.select_all_region(),
                EditAction::Cut | EditAction::Paste => {}
            }
            self.request_redraw();
            return;
        }
        let Some(id) = self.runtime.selection_toolbar.map(|mark| mark.id) else {
            return;
        };
        match action {
            EditAction::Copy => {
                if self.copy_selection(id) {
                    // As the platforms' own text fields do after a copy: the selection
                    // collapses to its end, and what marked it is put away.
                    if let Some(edit) = self.runtime.edits.get_mut(&id) {
                        *edit = collapsed_to_end(*edit);
                    }
                    self.runtime.close_edit_run(id);
                }
                self.runtime.selection_handles = None;
                self.hide_selection_toolbar();
            }
            EditAction::Cut => {
                // `apply_key` puts the handles and the bar away, as any key does.
                self.cut_selection(id);
                self.hide_selection_toolbar();
            }
            EditAction::Paste => {
                self.runtime.selection_handles = None;
                self.hide_selection_toolbar();
                // Answered now, or — on the Web — on a later frame.
                if let Some(pasted) = self.clipboard.paste(id, self.window.as_ref()) {
                    self.land_paste(pasted);
                }
            }
            EditAction::SelectAll => {
                self.select_all(id);
                // Made with a finger or a right-click, the selection keeps whatever
                // marked it.
                if self.runtime.selection_handles.is_some() {
                    self.runtime.selection_handles = Some(id);
                }
                if select_all_hides_bar(frus_widgets::default_target_platform()) {
                    // On a desktop the menu has done its work, and goes with the handles,
                    // as the reference's `hideToolbar()` takes both (milestone 625).
                    self.runtime.selection_handles = None;
                    self.hide_selection_toolbar();
                } else {
                    // On a phone the bar stays, with the list its new state calls for,
                    // where it was: a menu a right-click opened stays at the pointer.
                    let at = self.runtime.selection_toolbar.and_then(|mark| mark.at);
                    self.show_selection_toolbar_at(id, at);
                }
            }
        }
        #[cfg(android)]
        self.push_ime_context(id);
    }

    /// A right-click on a text field (a desktop's context menu, milestone 568): focuses it,
    /// puts the caret where the click landed unless it landed inside the selection there
    /// already is, and opens the bar. On anything else it puts an open bar away.
    fn context_click(&mut self) {
        // Something that answers a secondary tap takes it (milestone 581).
        let secondary = self
            .ui
            .as_ref()
            .and_then(|ui| ui.hit(self.cursor))
            .and_then(|id| {
                self.tree
                    .as_ref()
                    .and_then(|tree| find_widget(tree.as_ref(), id))
            })
            .and_then(|widget| widget.on_secondary_tap());
        if let Some(message) = secondary {
            self.hide_selection_toolbar();
            self.dispatch(message);
            self.request_redraw();
            return;
        }
        let hit = self.ui.as_ref().and_then(|ui| ui.focus_hit(self.cursor));
        let Some((id, rect)) = hit else {
            self.hide_selection_toolbar();
            return;
        };
        let was_focused = self.runtime.input.focused == Some(id);
        let scroll_y = self.runtime.scroll.get(&id).map(|s| s.1).unwrap_or(0.0);
        let scroll_cursor = if was_focused {
            self.runtime.edits.get(&id).map(|e| e.cursor).unwrap_or(0)
        } else {
            0
        };
        let cursor = self
            .tree
            .as_ref()
            .and_then(|tree| find_widget(tree.as_ref(), id))
            .and_then(|widget| {
                widget.cursor_at(
                    self.cursor.x - rect.x,
                    self.cursor.y - rect.y + scroll_y,
                    rect.width,
                    scroll_cursor,
                )
            });
        // Only a text field has a bar; a button under the pointer is not one.
        let Some(cursor) = cursor else {
            self.hide_selection_toolbar();
            return;
        };
        let inside = was_focused
            && self
                .runtime
                .edits
                .get(&id)
                .and_then(|edit| edit.selection_range())
                .is_some_and(|(start, end)| cursor >= start && cursor <= end);
        self.runtime.input.focused = Some(id);
        self.runtime.selection_handles = None;
        if !inside {
            self.goal_x = None;
            self.runtime.edits.insert(
                id,
                Edit {
                    cursor,
                    anchor: None,
                    composing: None,
                },
            );
            self.runtime.close_edit_run(id);
        }
        self.show_selection_toolbar_at(id, Some(self.cursor));
    }

    /// Types what the clipboard answered into the field that asked for it, if the paste
    /// still lands there — see `clip::Pasted::lands`.
    fn land_paste(&mut self, pasted: clip::Pasted) {
        if pasted.lands(self.runtime.input.focused) {
            self.apply_key(pasted.into, Key::Text(pasted.text));
            self.request_redraw();
        }
    }
}

/// The edit a **copy** leaves behind: the selection collapsed to its end, the caret where
/// the selection stopped. What the platforms' own text fields do after Copy from their bar,
/// and what tells the reader it happened — the highlight goes.
fn collapsed_to_end(edit: Edit) -> Edit {
    let cursor = edit.selection_range().map_or(edit.cursor, |(_, end)| end);
    Edit {
        cursor,
        anchor: None,
        composing: None,
    }
}

/// Which end of a value drag is being announced.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Edge {
    Start,
    End,
}

/// Was the gesture that just ended **still a tap**?
///
/// Every drag here engages only past a threshold, so a press that never crossed it is
/// not a drag at all: it is a tap, and the release owes the widget underneath its
/// click. A drag that *did* move has already been answered — a fling, a drop, a
/// dismissal — and must not also click.
///
/// One list, because forgetting a variant is silent: the widget stays hittable, the
/// press still records it, and only the release quietly does nothing. That is how a
/// dismissible row came to swallow every tap on it (milestone 327).
/// The window's cursor for one the interface asks for. A hidden cursor is the default
/// shape, made invisible by the caller.
fn cursor_icon(cursor: UiCursor) -> CursorIcon {
    match cursor {
        UiCursor::Default | UiCursor::None => CursorIcon::Default,
        UiCursor::Pointer => CursorIcon::Pointer,
        UiCursor::Text => CursorIcon::Text,
        UiCursor::Forbidden => CursorIcon::NotAllowed,
        UiCursor::Wait => CursorIcon::Wait,
        UiCursor::Progress => CursorIcon::Progress,
        UiCursor::Help => CursorIcon::Help,
        UiCursor::Precise => CursorIcon::Crosshair,
        UiCursor::Move => CursorIcon::Move,
        UiCursor::Grab => CursorIcon::Grab,
        UiCursor::Grabbing => CursorIcon::Grabbing,
        UiCursor::ResizeColumn => CursorIcon::ColResize,
        UiCursor::ResizeRow => CursorIcon::RowResize,
        UiCursor::ZoomIn => CursorIcon::ZoomIn,
        UiCursor::ZoomOut => CursorIcon::ZoomOut,
        UiCursor::ContextMenu => CursorIcon::ContextMenu,
    }
}

/// A movement, or a velocity, kept to the way a detector drags.
fn mask_pan(axis: frus_widgets::PanAxis, value: Point) -> Point {
    match axis {
        frus_widgets::PanAxis::Free => value,
        frus_widgets::PanAxis::Horizontal => Point::new(value.x, 0.0),
        frus_widgets::PanAxis::Vertical => Point::new(0.0, value.y),
    }
}

fn gesture_was_a_tap(ended: Option<&Drag>) -> bool {
    matches!(
        ended,
        Some(
            Drag::Scroll { moved: false, .. }
                | Drag::Pan { moved: false, .. }
                | Drag::Gesture { moved: false, .. }
                | Drag::Reorder { moved: false, .. }
                | Drag::Item { moved: false, .. }
                | Drag::Dismiss { moved: false, .. }
                | Drag::Sheet { moved: false, .. }
        )
    )
}

/// A press lands at `at`: what is under it is pressed, and a surface that takes ink
/// splashes from where it landed. The box comes from the frame that was on screen when the
/// pointer came down, which is the one the user aimed at. Returns whether a splash started.
fn press_at<Msg: Clone>(runtime: &mut Runtime, ui: Option<&Ui<Msg>>, at: Point) -> bool {
    runtime.input.pressed = ui.and_then(|ui| ui.hit(at));
    let Some(pressed) = runtime.input.pressed else {
        return false;
    };
    let Some(rect) = ui.and_then(|ui| ui.ink_box(pressed)) else {
        return false;
    };
    runtime.ink_press(
        pressed,
        Point::new(at.x - rect.x, at.y - rect.y),
        Size::new(rect.width, rect.height),
    );
    true
}

/// What becomes of the press once a pointer event has been routed, `could_tap` being
/// whether the gesture under way could still have ended as a tap **before** the event, and
/// `drag` the gesture after it. Returns whether anything changed, which wants a frame.
///
/// A press on something inside a scrollable is shared with the scroll until the pointer
/// crosses the slop. From then on the gesture has it — a scroll, a swipe, a sheet, a
/// carried row — and, as in the reference, where the recogniser that loses the arena is
/// told so, the press is **let go of there and then**: its ink is swept, its press fades.
/// And a pointer that has lifted holds nothing, whatever its release did.
///
/// Before this, a release that ended a gesture which had moved returned before the press
/// was cleared, so the press outlived the finger; the ink, which waits for as long as its
/// widget is pressed, was held for good — the grey left on a segment a phone had swiped
/// a strip of filters by (milestone 534).
///
/// A finger hovers only so that its press can show (milestone 505), so a finger whose press
/// was taken stops hovering too. A mouse is still over whatever it is over.
fn settle_press(
    input: &mut frus_widgets::InputState,
    kind: PointerKind,
    could_tap: bool,
    drag: Option<&Drag>,
    touch: bool,
) -> bool {
    let taken = match kind {
        PointerKind::Down => false,
        PointerKind::Move => could_tap && !gesture_was_a_tap(drag),
        PointerKind::Up | PointerKind::Cancel => true,
    };
    if !taken {
        return false;
    }
    let mut changed = input.pressed.take().is_some();
    if touch {
        changed |= input.hovered.take().is_some();
    }
    changed
}

/// How fast an area scrolls under a carried item, in pixels per second **per pixel** the
/// item hangs over the edge: the further out it is, the faster the list comes to meet it.
/// The reference's number, and the reference's law.
const AUTOSCROLL_VELOCITY: f32 = 50.0;

/// The overhang that speed is worked out from is capped here, so that carrying a row far
/// past the edge — or off the window entirely — settles at a fast but usable speed instead
/// of one nobody can aim with.
const AUTOSCROLL_MAX_OVERHANG: f32 = 20.0;

/// Places the scroll requests it can against `regions`, and hands back the ones whose
/// region that registry does not name, along with whether anything moved.
///
/// A request names its region by **key**, the way a focus request does: the application
/// wrapped it in `keyed(k, …)` and the tree is what turns that back into an identity.
/// The framework's own identities are hashes of a position in a tree — an application
/// cannot know one, and should not have to.
///
/// Nothing is *stored* here. The request is spent the moment its region is found, and
/// what it leaves behind is an offset in the runtime, indistinguishable from an offset a
/// finger left there. That is what makes it survive a rebuild: there is nothing to
/// survive.
fn apply_scroll_requests<Msg>(
    runtime: &mut Runtime,
    tree: &dyn Widget<Msg>,
    requests: Vec<(u64, ScrollTo)>,
    regions: &[Scrollable],
) -> (Vec<(u64, ScrollTo)>, bool) {
    let mut unplaced = Vec::new();
    let mut moved = false;
    for (key, to) in requests {
        let area = find_by_key(tree, key).and_then(|id| regions.iter().find(|a| a.id == id));
        match area {
            Some(area) => moved |= runtime.scroll_to(area, to),
            None => unplaced.push((key, to)),
        }
    }
    (unplaced, moved)
}

/// Places the sheet requests it can against `sheets`, and hands back the ones whose sheet
/// that registry does not name, along with whether anything moved — the terms of
/// `apply_scroll_requests`, above.
///
/// A request names the key the application wrapped the sheet in; the state belongs to the
/// sheet's panel under that key, which is what the tree is asked for.
fn apply_sheet_requests<Msg>(
    runtime: &mut Runtime,
    tree: &dyn Widget<Msg>,
    requests: Vec<(u64, SheetTo)>,
    sheets: &[frus_widgets::SheetArea],
) -> (Vec<(u64, SheetTo)>, bool) {
    let mut unplaced = Vec::new();
    let mut moved = false;
    for (key, to) in requests {
        let sheet = frus_widgets::find_sheet_by_key(tree, key)
            .and_then(|id| sheets.iter().find(|sheet| sheet.id == id));
        match sheet {
            Some(sheet) => moved |= runtime.sheet_to(sheet.id, &sheet.spec, &to),
            None => unplaced.push((key, to)),
        }
    }
    (unplaced, moved)
}

/// Moves a carried item's press by `shift` — how far its content moved on screen — so that
/// the ghost, drawn at the content's box plus the finger's travel since the press, stays
/// under the finger. A lifted item's box, recorded at the press, goes with it.
///
/// Anything else being dragged is not carried content, and is left alone.
fn follow_content(drag: &mut Drag, shift: (f32, f32)) {
    match drag {
        Drag::Reorder { start, carried, .. } => {
            start.x += shift.0;
            start.y += shift.1;
            if let Some((_, rect)) = carried {
                *rect = rect.translate(shift.0, shift.1);
            }
        }
        Drag::Item { source, start, .. } => {
            start.x += shift.0;
            start.y += shift.1;
            source.rect = source.rect.translate(shift.0, shift.1);
        }
        _ => {}
    }
}

/// One axis of the auto-scroll: how far the **content** has to move this frame so that an
/// item held past a viewport's edge brings the rest of the list into view.
///
/// Everything is in screen coordinates and along one axis: `item` and `view` are
/// `(start, end)` pairs, `room` is what is left to scroll that way (nought at the end of
/// the content). The answer is a movement of the content, which the area then turns into
/// an offset of its own — signs and reversed axes belong to `Scrollable::offset_delta`,
/// not here.
///
/// `None` means *not now*: the item is inside, or the edge it hangs over is the end of the
/// content, where there is nothing left to reveal and the list should stay still rather
/// than fight.
fn edge_autoscroll(item: (f32, f32), view: (f32, f32), room: (f32, f32), dt: f32) -> Option<f32> {
    let before = view.0 - item.0; // above the top edge
    let after = item.1 - view.1; // below the bottom edge
                                 // The leading edge is asked first, and both are never obeyed at once: an item taller
                                 // than the viewport hangs over both, and an item pulled two ways scrolls nowhere.
    let overhang = if before > 0.0 && room.0 > 0.0 {
        before.min(AUTOSCROLL_MAX_OVERHANG)
    } else if after > 0.0 && room.1 > 0.0 {
        -after.min(AUTOSCROLL_MAX_OVERHANG)
    } else {
        return None;
    };
    let travel = overhang * AUTOSCROLL_VELOCITY * dt;
    (travel != 0.0).then_some(travel)
}

/// Moves `current` toward `target` by one **exponential** spring step, with time
/// constant `tau` in seconds, over an interval `dt`: frame-rate independent and free
/// of overshoot. Used to smooth the abscissa during a reorder.
fn spring_toward(current: f32, target: f32, dt: f32, tau: f32) -> f32 {
    let k = 1.0 - (-dt / tau.max(1e-4)).exp();
    current + (target - current) * k
}

/// The focus history's maximum depth, for nested overlays' triggers.
const FOCUS_HISTORY_MAX: usize = 8;

/// Resolves focus after a (re)build, from the focusables **present** this frame. When
/// `current` has **vanished**, an overlay having closed, focus returns to the most
/// recent present **trigger** in `history`, which is popped until one is found. The
/// transition is recorded: the old focus (`prev`), if still present and different from
/// the new one, is pushed as a candidate trigger, bounded by [`FOCUS_HISTORY_MAX`].
/// Returns the resolved focus. A **pure** function apart from the mutated `history` and
/// `prev` — testable without a window.
fn resolve_focus(
    current: Option<WidgetId>,
    present: &std::collections::HashSet<WidgetId>,
    history: &mut Vec<WidgetId>,
    prev: &mut Option<WidgetId>,
) -> Option<WidgetId> {
    let mut cur = current;
    if let Some(c) = cur {
        if !present.contains(&c) {
            cur = None;
            while let Some(cand) = history.pop() {
                if present.contains(&cand) {
                    cur = Some(cand);
                    break;
                }
            }
        }
    }
    if *prev != cur {
        if let Some(old) = *prev {
            if present.contains(&old) && Some(old) != cur {
                history.push(old);
                if history.len() > FOCUS_HISTORY_MAX {
                    history.remove(0);
                }
            }
        }
        *prev = cur;
    }
    cur
}

/// Paints the dragged header's **lifted card**, the ghost, into `scene` — unclipped —
/// at `card`: a drop shadow, a **faithful face** from the header's already-translated
/// primitives, or a solid one as a fallback when `ghost` is empty, then a `primary`
/// border. A pure function, testable without a GPU. The neighbours' sliding happens
/// upstream, in `reflow_reorder_columns`.
fn draw_ghost_card(scene: &mut Scene, theme: &Theme, card: Rect, ghost: &[Primitive]) {
    use drag_preview::{BORDER_ALPHA, BORDER_WIDTH, SHADOW_ALPHA, SHADOW_BLUR, SHADOW_OFFSET_Y};
    scene.set_clip(Rect::UNBOUNDED);
    // The shadow colour comes from **the theme** and can be overridden — the same role
    // as `Button`'s shadow; only the geometry, offset, blur and opacity, is a local
    // constant.
    let shadow = theme.scheme.shadow.with_alpha(SHADOW_ALPHA);
    scene.shadow(
        card.translate(0.0, SHADOW_OFFSET_Y),
        shadow,
        theme.radius,
        SHADOW_BLUR,
    );
    let border = theme.primary.fade(BORDER_ALPHA);
    if ghost.is_empty() {
        scene.draw_rect(card, theme.surface, theme.radius, BORDER_WIDTH, border);
    } else {
        scene.draw_rect(card, theme.surface, theme.radius, 0.0, Color::TRANSPARENT);
        for primitive in ghost {
            scene.push_primitive(primitive.clone());
        }
        scene.draw_rect(card, Color::TRANSPARENT, theme.radius, BORDER_WIDTH, border);
    }
}

/// How a reorderable moves while it is carried: the two gestures the shell knows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReorderMotion {
    /// A table's column: a continuous slide along x following the pointer, dropped into
    /// the place of the column under it.
    Columns,
    /// A list's row or a board's card: inserted before or after a slot along the axis,
    /// with an insertion line, a gap opening there, and the nearest slot past either end.
    Slots(ReorderAxis),
}

impl ReorderMotion {
    /// Which of the two a reorderable is, from its two answers: every vertical one inserts,
    /// and a horizontal one only when it says so — a list's row does, a table's column does
    /// not.
    fn of(axis: ReorderAxis, inserts: bool) -> Self {
        match axis {
            ReorderAxis::Vertical => Self::Slots(ReorderAxis::Vertical),
            ReorderAxis::Horizontal if inserts => Self::Slots(ReorderAxis::Horizontal),
            ReorderAxis::Horizontal => Self::Columns,
        }
    }
}

/// How `widget` moves while it is carried — [`ReorderMotion::of`] its two answers.
fn reorder_motion<Msg>(widget: &dyn Widget<Msg>) -> ReorderMotion {
    ReorderMotion::of(widget.reorder_axis(), widget.reorder_inserts())
}

/// Where the ghost is drawn relative to the box it was lifted from, given the finger's
/// `travel` since the press.
///
/// - A **column** follows the pointer along x, with a slight lift.
/// - A **card** follows it in both directions: a board carries it across columns.
/// - A **horizontal list's row** follows it along x only. The reference keeps a list's
///   proxy in its lane on either axis; a vertical list here shares the board's freedom
///   because the two are one path, and a horizontal list has no board to share it with.
fn ghost_offset(motion: ReorderMotion, travel: (f32, f32)) -> (f32, f32) {
    match motion {
        ReorderMotion::Columns => (travel.0, drag_preview::LIFT_Y),
        ReorderMotion::Slots(ReorderAxis::Vertical) => travel,
        ReorderMotion::Slots(ReorderAxis::Horizontal) => (travel.0, 0.0),
    }
}

/// The geometry of a reorder preview's **insertion line**: a thin band of thickness
/// `thickness`, centred on the target edge **where the insertion will happen**.
///
/// Along a **vertical** list: the **top** edge (inserting before, the upper half hovered)
/// or the **bottom** one (inserting after, `after = true`, the lower half hovered),
/// spanning the full width. Along a **horizontal** list the band stands on its end,
/// spanning the full height at the left or right edge — and *after* is the right edge
/// only when the list reads left to right: under `rtl` what follows a row is on its left.
/// A pure function, testable without a GPU.
fn drop_insertion_line(
    target: Rect,
    thickness: f32,
    after: bool,
    axis: ReorderAxis,
    rtl: bool,
) -> Rect {
    match axis {
        ReorderAxis::Vertical => {
            let edge = if after {
                target.y + target.height
            } else {
                target.y
            };
            Rect::new(target.x, edge - thickness * 0.5, target.width, thickness)
        }
        ReorderAxis::Horizontal => {
            let edge = if after != rtl {
                target.x + target.width
            } else {
                target.x
            };
            Rect::new(edge - thickness * 0.5, target.y, thickness, target.height)
        }
    }
}

/// Which axis a scroll gesture is **claimed by**, decided once when the finger passes the
/// threshold: `true` for vertical.
///
/// An area that can only go one way claims that one, whatever the finger did — a diagonal
/// flick down a list is a scroll down, not a refusal. An area that can go both ways takes
/// the direction the finger actually went in, ties going to vertical, which is the way a
/// page reads. The loser gets nothing for the rest of the gesture: this is the reference's
/// arena, where a vertical and a horizontal recogniser compete and only one wins.
fn claim_axis(dx: f32, dy: f32, can_x: bool, can_y: bool) -> bool {
    match (can_x, can_y) {
        (true, false) => false,
        (false, true) => true,
        _ => dy.abs() >= dx.abs(),
    }
}

/// Which of the scrollables under the finger a gesture is **for**: the innermost one that
/// can go the way the finger went (`down` = along the vertical), given `chain` innermost
/// first and `under` the area the press landed on.
///
/// A strip that only slides across, sitting in a page that only scrolls down, is not what a
/// drag downwards is about — the page behind it is, and the reference's arena gives it to
/// the page for exactly that reason. Where nothing in the stack can go that way, the area
/// under the finger keeps the gesture and goes its own way: a lone recogniser in an arena
/// still wins.
fn claim_area(
    chain: &[frus_widgets::Scrollable],
    under: WidgetId,
    down: bool,
) -> Option<frus_widgets::Scrollable> {
    chain
        .iter()
        // A refresh area listening above takes a pull downwards even with nothing to
        // scroll, which is the reference's one exception to the same rule; the physics
        // may say never, or always (milestone 649).
        .find(|a| a.takes_user_scroll(down))
        .or_else(|| {
            chain
                .iter()
                .find(|a| a.id == under && a.physics.user() != frus_widgets::UserScroll::Never)
        })
        .copied()
}

/// Gets the bytes at `url` and hands them to `deliver`, once.
///
/// Registered as the process's [`frus_widgets::ImageFetcher`] when the shell is built with
/// `net`. It spawns and forgets: nothing here waits for the answer, and the store the
/// callback writes into is what a later frame reads.
///
/// The two spawns are the two the rest of this file uses for every other effect — the
/// shared executor natively, the browser on the Web.
///
/// It carries a **deadline**, and that is not politeness. An image still in flight keeps
/// the interface redrawing — that is how the frame showing it ever happens — so a
/// request that never answers would leave the application repainting at full rate for
/// ever, on somebody's battery. A request without an answer has to become one with a
/// failure.
#[cfg(feature = "net")]
fn fetch_image_bytes(
    url: &str,
    deliver: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send + 'static>,
) {
    /// Long enough for a photograph on a slow connection, short enough that a dead
    /// server does not pin a screen redrawing until the user closes the application.
    const DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);

    let url = url.to_string();
    let run = async move {
        let result = crate::net::Request::get(url)
            .timeout(DEADLINE)
            .send_bytes()
            .await;
        deliver(result.map_err(|e| e.to_string()));
    };
    #[cfg(not(web))]
    crate::runtime::spawn(run).detach();
    #[cfg(web)]
    wasm_bindgen_futures::spawn_local(run);
}

#[cfg(test)]
mod debug_keys_tests {
    use super::*;

    #[test]
    fn the_graphs_keep_the_latest_frames_and_mark_the_late_ones() {
        let mut history = FrameHistory::default();
        for i in 0..100 {
            history.push(&crate::frame_stats::FrameCosts {
                build: Some(1.0),
                layout_paint: i as f32,
                render: 5.0,
                ..Default::default()
            });
        }
        assert_eq!(history.ui.len(), HISTORY, "the oldest frames go");
        assert_eq!(
            history.ui.back().copied(),
            Some(100.0),
            "the newest is last"
        );
        let bars = FrameHistory::bars(&history.render, 36.0);
        assert!(bars.iter().all(|(_, over)| !over), "5 ms is within budget");
        let ui = FrameHistory::bars(&history.ui, 36.0);
        assert_eq!(
            ui.last().copied(),
            Some((36.0, true)),
            "over the top fills the graph"
        );
        let half = FrameHistory::bars(&[BUDGET_MS].into_iter().collect(), 36.0);
        assert!((half[0].0 - 18.0).abs() < 0.01 && !half[0].1, "{half:?}");
    }

    #[test]
    fn the_platform_goes_round_as_the_reference_does() {
        use frus_widgets::TargetPlatform as P;
        let mut seen = vec![P::Android];
        for _ in 0..6 {
            seen.push(next_platform(*seen.last().unwrap()));
        }
        assert_eq!(
            seen,
            [
                P::Android,
                P::Ios,
                P::Windows,
                P::MacOs,
                P::Linux,
                P::Fuchsia,
                P::Android
            ]
        );
    }

    #[test]
    fn the_dumps_say_what_there_is() {
        let id = WidgetId::from_u64(0x1234_5678);
        let other = WidgetId::from_u64(0x9);
        let nodes = [frus_widgets::InspectorNode {
            id,
            rect: Rect::new(10.0, 20.0, 100.0, 40.0),
            name: "Button",
            depth: 3,
        }];
        let focus = dump_focus(&nodes, &[id, other], Some(id));
        assert_eq!(focus, "▶ Button  10,20  100×40  #12345678\n  #00000009\n");
        assert_eq!(dump_focus(&nodes, &[], None), "  (nothing focusable)\n");

        let semantics = [(
            id,
            Rect::new(0.0, 0.0, 50.0, 20.0),
            frus_widgets::SemanticsProperties::new(frus_widgets::Role::Button).label("Save"),
        )];
        let dump = dump_semantics(&semantics);
        assert!(dump.starts_with("  Button \"Save\""), "{dump}");
        assert!(dump.ends_with("0,0  50×20\n"), "{dump}");
    }
}

#[cfg(test)]
mod tests {
    use super::{
        build_view, claim_area, claim_axis, draw_ghost_card, drop_insertion_line, fling_velocity,
        gesture_was_a_tap, ghost_offset, install_ambient, reorder_motion, resolve_focus,
        spring_toward, Drag, Point, Rect, ReorderAxis, ReorderMotion, Scene, Theme,
        VelocityEstimate, PRECISE_SLOP, TOUCH_SLOP,
    };
    use super::{clipboard_command, ClipCommand, KeyCode, PhysicalKey, WinitKey};
    use super::{collect_ids, find_widget, MediaQuery};
    use frus_widgets::Locale;

    /// **Which systems put the bar away after its Select all** (milestone 625): the three
    /// desktops, as the reference's field does; on a phone the bar stays.
    #[test]
    fn select_all_hides_the_bar_on_the_desktops() {
        use frus_widgets::TargetPlatform as P;
        for p in [P::MacOs, P::Linux, P::Windows] {
            assert!(super::select_all_hides_bar(p), "{p:?}");
        }
        for p in [P::Android, P::Ios, P::Fuchsia] {
            assert!(!super::select_all_hides_bar(p), "{p:?}");
        }
    }

    /// **The keys that open the selection bar** (milestone 568): the context-menu key, and
    /// F10 with Shift — F10 alone is the menu bar's key in other toolkits and asks for nothing
    /// here, and no ordinary key does.
    #[test]
    fn the_context_menu_key_and_shift_f10_open_the_bar() {
        use super::opens_selection_bar;
        assert!(opens_selection_bar(
            &WinitKey::Named(winit::keyboard::NamedKey::ContextMenu),
            false
        ));
        assert!(opens_selection_bar(
            &WinitKey::Named(winit::keyboard::NamedKey::F10),
            true
        ));
        assert!(!opens_selection_bar(
            &WinitKey::Named(winit::keyboard::NamedKey::F10),
            false
        ));
        assert!(!opens_selection_bar(
            &WinitKey::Named(winit::keyboard::NamedKey::Enter),
            true
        ));
        assert!(!opens_selection_bar(&character("m"), true));
    }

    /// **What a Copy from the selection bar leaves behind** (milestone 568): the selection
    /// collapsed to its end, whichever way it was made — dragged backwards puts the caret at
    /// the far end, and Copy puts it at the *end* of the text, not where the caret was.
    #[test]
    fn a_copy_collapses_the_selection_to_its_end() {
        use frus_widgets::Edit;
        let forwards = Edit {
            cursor: 11,
            anchor: Some(6),
            composing: None,
        };
        let backwards = Edit {
            cursor: 6,
            anchor: Some(11),
            composing: None,
        };
        let expect = Edit {
            cursor: 11,
            anchor: None,
            composing: None,
        };
        assert_eq!(super::collapsed_to_end(forwards), expect);
        assert_eq!(super::collapsed_to_end(backwards), expect);
        // Nothing selected: the caret stays where it is.
        let caret = Edit {
            cursor: 3,
            anchor: None,
            composing: None,
        };
        assert_eq!(super::collapsed_to_end(caret), caret);
        // An anchor on the caret is no selection either.
        let empty = Edit {
            cursor: 3,
            anchor: Some(3),
            composing: Some((1, 2)),
        };
        assert_eq!(super::collapsed_to_end(empty).anchor, None);
        assert_eq!(super::collapsed_to_end(empty).cursor, 3);
    }

    /// **A field with a clear button kept the keyboard only until the first letter**
    /// (milestone 510). Whether the focused widget takes typing was asked of a caret
    /// hit test at the corner of a field one pixel wide; a field whose clickable suffix
    /// covers that pixel — the × it shows once it holds text — answered no, and the
    /// keyboard was closed mid-word. Asked of the widget, the answer is the field's.
    #[test]
    fn a_field_with_a_clear_button_still_wants_the_keyboard() {
        use frus_widgets::{Container, Icons, TextField};
        let clearable = TextField::<()>::new("F")
            .suffix_icon(Icons::CLOSE)
            .on_suffix(());
        assert!(
            super::wants_keyboard(&clearable),
            "the field with its clear button"
        );
        assert!(
            !super::wants_keyboard(&TextField::<()>::new("F").enabled(false)),
            "a disabled field takes no typing"
        );
        assert!(
            !super::wants_keyboard(&Container::<()>::new()),
            "and what is not a field wants no keyboard"
        );
    }

    /// **Left and right moved the focus, not the caret, in a field with text in it**
    /// (milestone 570). Whether the focused widget is a text field was asked of a caret probe
    /// at a corner of the field one pixel wide, and a field that holds text shows a clear
    /// button over that corner: the probe said no caret goes there, so the arrows navigated to
    /// the next control. In an empty field, which has no button, they worked — which is how it
    /// went unseen. The probe still answers no for such a field; the question is the widget's.
    #[test]
    fn a_field_with_a_clear_button_is_a_text_field_and_keeps_its_arrows() {
        use frus_widgets::{Container, Icons, TextField};
        let clearable = TextField::<()>::new("hello")
            .suffix_icon(Icons::CLOSE)
            .on_suffix(());
        assert!(
            frus_widgets::Widget::<()>::cursor_at(&clearable, 0.0, 0.0, 1.0, 0).is_none(),
            "the trap: the probe finds no caret at the corner a clear button covers"
        );
        assert!(
            super::is_text_field(&clearable),
            "and it is a text field all the same"
        );
        assert!(
            super::is_text_field(&TextField::<()>::new("")),
            "empty, too"
        );
        assert!(
            !super::is_text_field(&Container::<()>::new()),
            "what is not a field leaves its arrows to focus navigation"
        );
    }

    /// **A text that can only be read does not raise the keyboard.** A read-only field and a
    /// selectable paragraph are both text fields — they have a caret, and the arrows are
    /// theirs — but the software keyboard is for typing, and sliding it up over the words a
    /// reader has come to select hides the words. Before milestone 573 a read-only field
    /// raised it all the same.
    #[test]
    fn a_text_that_can_only_be_read_wants_no_keyboard() {
        use frus_widgets::{Text, TextField};
        let read_only = TextField::<()>::new("REF-4417").read_only();
        assert!(super::is_text_field(&read_only), "it has a caret");
        assert!(
            !super::wants_keyboard(&read_only),
            "and no use for a keyboard"
        );

        let selectable = Text::new("ORDER-4417").selectable();
        assert!(
            super::is_text_field::<()>(&selectable),
            "the arrows move its caret"
        );
        assert!(!super::wants_keyboard::<()>(&selectable));

        assert!(
            super::wants_keyboard(&TextField::<()>::new("typed")),
            "and a field that can be typed into still does"
        );
        assert!(
            !super::is_text_field::<()>(&Text::new("ORDER-4417")),
            "an ordinary text leaves its arrows to focus navigation"
        );
    }

    fn character(c: &str) -> WinitKey {
        WinitKey::Character(c.into())
    }

    /// Ctrl+C/X/V are the clipboard, in either case — Caps Lock or Shift is still a
    /// copy — and the same letters without Ctrl are only letters.
    #[test]
    fn ctrl_c_x_v_are_the_clipboard_and_the_letters_alone_are_not() {
        let any = PhysicalKey::Code(KeyCode::KeyQ);
        for (letter, command) in [
            ("c", ClipCommand::Copy),
            ("X", ClipCommand::Cut),
            ("v", ClipCommand::Paste),
        ] {
            assert_eq!(
                clipboard_command(&character(letter), any, true),
                Some(command)
            );
            assert_eq!(
                clipboard_command(&character(letter), any, false),
                None,
                "{letter}"
            );
        }
        assert_eq!(clipboard_command(&character("a"), any, true), None);
    }

    /// **Android's Copy, Cut and Paste keys arrive by physical code alone** — winit gives
    /// them no logical key — and they are the clipboard with no modifier held. A check
    /// of the logical key alone ignored them (milestone 509).
    #[test]
    fn a_keyboards_own_clipboard_keys_work_by_their_physical_code() {
        let unidentified = WinitKey::Unidentified(winit::keyboard::NativeKey::Unidentified);
        for (code, command) in [
            (KeyCode::Copy, ClipCommand::Copy),
            (KeyCode::Cut, ClipCommand::Cut),
            (KeyCode::Paste, ClipCommand::Paste),
        ] {
            assert_eq!(
                clipboard_command(&unidentified, PhysicalKey::Code(code), false),
                Some(command),
                "{code:?}"
            );
        }
        // And the named keys a desktop keyboard reports for the same thing.
        let named = WinitKey::Named(super::NamedKey::Paste);
        let any = PhysicalKey::Code(KeyCode::KeyQ);
        assert_eq!(
            clipboard_command(&named, any, false),
            Some(ClipCommand::Paste)
        );
    }

    /// **A paste lands only in the field that asked, while that field still has the
    /// focus** — on the Web the clipboard answers after the key press, and by then the
    /// reader may have moved to another field or to none. And a clipboard holding no
    /// text pastes nothing, rather than typing an empty string over the selection
    /// (milestone 526).
    #[test]
    fn a_paste_lands_in_the_field_that_asked_only_while_it_has_the_focus() {
        use super::clip::Pasted;
        let field = WidgetId::from_u64(1);
        let other = WidgetId::from_u64(2);
        let pasted = Pasted {
            into: field,
            text: "copied".into(),
        };
        assert!(pasted.lands(Some(field)));
        assert!(
            !pasted.lands(Some(other)),
            "the focus moved to another field"
        );
        assert!(!pasted.lands(None), "the focus left every field");
        let nothing = Pasted {
            into: field,
            text: String::new(),
        };
        assert!(!nothing.lands(Some(field)), "an empty clipboard");
    }

    /// **A paste answered later is queued for its field, and a frame is asked for.** Two
    /// pastes asked in two fields and answered in the other order come out in the order
    /// the answers came, each still naming the field that asked; each answer wakes the
    /// window once; and nothing is taken twice (milestone 526).
    #[test]
    fn a_paste_answered_later_waits_for_the_frame_that_takes_it() {
        use super::clip::{Answers, Pasted};
        use std::cell::Cell;
        use std::rc::Rc;
        let first = WidgetId::from_u64(1);
        let second = WidgetId::from_u64(2);
        let answers = Answers::default();
        let wakes = Rc::new(Cell::new(0));
        let wake = || {
            let wakes = Rc::clone(&wakes);
            move || wakes.set(wakes.get() + 1)
        };
        let to_first = answers.answer_for(first, wake());
        let to_second = answers.answer_for(second, wake());
        assert_eq!(answers.take(), None, "nothing is answered yet");
        assert_eq!(wakes.get(), 0, "asking is not answering");

        to_second("later".into());
        assert_eq!(wakes.get(), 1);
        to_first("sooner".into());
        assert_eq!(wakes.get(), 2);

        assert_eq!(
            answers.take(),
            Some(Pasted {
                into: second,
                text: "later".into()
            })
        );
        assert_eq!(
            answers.take(),
            Some(Pasted {
                into: first,
                text: "sooner".into()
            })
        );
        assert_eq!(answers.take(), None, "each answer is taken once");
    }

    /// An application whose whole interface lives **inside a deferred subtree** — which is
    /// what any application with an `AppBar` is, since a bar defers its own composition
    /// until the theme is known.
    ///
    /// It exists because nothing else in this repo can stand in for one: the shell's own
    /// types need a window and an event-loop proxy, so the only piece of the frame a test
    /// can hold is the part that turns a `view` into a tree. That part is where two
    /// milestones' worth of bugs were.
    struct Deferred;

    impl crate::Application for Deferred {
        type Message = ();

        fn update(&mut self, _message: ()) -> crate::Command<()> {
            crate::Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn frus_widgets::Widget<()>> {
            Box::new(frus_widgets::ThemeBuilder::new(|_: &Theme| {
                frus_widgets::Flex::column()
                    .width(300.0)
                    .height(80.0)
                    .child(
                        frus_widgets::TextField::new("hi")
                            .width(200.0)
                            .on_input(|_| ()),
                    )
            }))
        }
    }

    /// The surface every frame installs, so a build outside one measures the way a build
    /// inside one does.
    fn surfaced<R>(f: impl FnOnce() -> R) -> R {
        MediaQuery::new(frus_widgets::Size::new(300.0, 80.0)).scope(f)
    }

    /// **A shell installs the reader's language** — the assertion that keeps milestone 454
    /// from being a resolution nobody ever runs.
    ///
    /// `locale::of()` answers `en` with nothing installed, exactly as
    /// `localizations::of()` answers English, and for the same reason: an application that
    /// says nothing must keep working. That default is also what would hide the wiring
    /// being missing, so this drives the shell's own reading of the trait rather than
    /// calling `resolve` directly — milestone 408's bug, and milestone 449's guard against
    /// it.
    #[test]
    fn a_shell_installs_the_reader_s_language() {
        /// An application with three languages, and a switch of its own it may or may not
        /// have been told to use.
        struct Speaks(Option<Locale>);

        impl crate::Application for Speaks {
            type Message = ();

            fn update(&mut self, _message: ()) -> crate::Command<()> {
                crate::Command::none()
            }

            fn view(&self, _theme: &Theme) -> Box<dyn frus_widgets::Widget<()>> {
                Box::new(frus_widgets::Flex::<()>::column())
            }

            fn supported_locales(&self) -> Vec<Locale> {
                vec![
                    Locale::new("en"),
                    Locale::new("fr"),
                    Locale::with_country("fr", "CA"),
                ]
            }

            fn locale(&self) -> Option<Locale> {
                self.0.clone()
            }
        }

        // The device speaks Belgian French; the application has French, so it wins.
        install_ambient(&Speaks(None), &[Locale::with_country("fr", "BE")]);
        assert_eq!(frus_widgets::locale::of(), Locale::new("fr"));

        // A platform that reported nothing is not a failure: the application's own first
        // choice stands.
        install_ambient(&Speaks(None), &[]);
        assert_eq!(frus_widgets::locale::of(), Locale::new("en"));

        // And an application with a language menu of its own outranks the device — still
        // resolved, so asking for one it does not have gives the nearest thing it does.
        install_ambient(
            &Speaks(Some(Locale::with_country("fr", "FR"))),
            &[Locale::new("en")],
        );
        assert_eq!(frus_widgets::locale::of(), Locale::new("fr"));

        // An application that says nothing at all is where it was: English.
        install_ambient(&Deferred, &[Locale::new("fr")]);
        assert_eq!(
            frus_widgets::locale::of(),
            Locale::new("en"),
            "it supports only English, so French resolves to it"
        );
    }

    /// **A shell installs the application's words** — which is the assertion that keeps
    /// milestone 449 from being a table nobody ever reads.
    ///
    /// `localizations::of` answers English with nothing installed, so every widget test
    /// and every golden would pass whether or not the shell ever called `install`. The
    /// default is what makes the feature safe to add; it is also what would hide the
    /// wiring being missing. So this drives the shell's own reading of the trait.
    #[test]
    fn a_shell_installs_the_application_s_words() {
        struct Fr;

        impl frus_widgets::localizations::Localizations for Fr {
            fn back_button_label(&self) -> &str {
                "Retour"
            }

            fn first_day_of_week_index(&self) -> usize {
                1
            }
        }

        struct Speaks;

        impl crate::Application for Speaks {
            type Message = ();

            fn update(&mut self, _message: ()) -> crate::Command<()> {
                crate::Command::none()
            }

            fn view(&self, _theme: &Theme) -> Box<dyn frus_widgets::Widget<()>> {
                Box::new(frus_widgets::Flex::<()>::column())
            }

            fn localizations(&self) -> Option<std::rc::Rc<dyn frus_widgets::Localizations>> {
                Some(std::rc::Rc::new(Fr))
            }
        }

        install_ambient(&Speaks, &[]);
        assert_eq!(
            frus_widgets::localizations::of().back_button_label(),
            "Retour",
            "the shell read the application's table and installed it"
        );
        assert_eq!(
            frus_widgets::localizations::of().first_day_of_week_index(),
            1
        );

        // And an application that says nothing leaves whatever is in force alone rather
        // than forcing English back on top of a table installed elsewhere.
        install_ambient(&Deferred, &[]);
        assert_eq!(
            frus_widgets::localizations::of().back_button_label(),
            "Retour",
            "saying nothing is not the same as saying English"
        );
    }

    /// **The application's scroll behaviour is the one at the root** (milestone 616), and
    /// one that says nothing gets the behaviour that follows the theme.
    #[test]
    fn the_scroll_behaviour_at_the_root_is_the_applications() {
        struct Quiet;

        impl crate::Application for Quiet {
            type Message = ();

            fn update(&mut self, _message: ()) -> crate::Command<()> {
                crate::Command::none()
            }

            fn view(&self, _theme: &Theme) -> Box<dyn frus_widgets::Widget<()>> {
                Box::new(frus_widgets::Flex::<()>::column())
            }

            fn scroll_behavior(&self) -> frus_widgets::ScrollBehavior {
                frus_widgets::ScrollBehavior::material().with_overscroll(false)
            }
        }

        struct Silent;

        impl crate::Application for Silent {
            type Message = ();

            fn update(&mut self, _message: ()) -> crate::Command<()> {
                crate::Command::none()
            }

            fn view(&self, _theme: &Theme) -> Box<dyn frus_widgets::Widget<()>> {
                Box::new(frus_widgets::Flex::<()>::column())
            }
        }

        install_ambient(&Quiet, &[]);
        assert_eq!(
            frus_widgets::ScrollConfiguration::of(),
            frus_widgets::ScrollBehavior::material().with_overscroll(false)
        );
        install_ambient(&Silent, &[]);
        assert_eq!(
            frus_widgets::ScrollConfiguration::of(),
            frus_widgets::ScrollBehavior::material()
        );
    }

    /// A tree the shell hands to a traversal is **ready to be traversed**.
    ///
    /// Milestones 415 and 416 were the same bug found twice, in the two places this shell
    /// turns a `view` into a tree. A deferred subtree has no children until something has
    /// built it, so an unprepared tree reports **one** identity — its root — and every
    /// widget in the application is invisible to `collect_ids`, to `find_widget`, and to
    /// everything downstream of them: the mount and leave fades, the focus, the caret.
    ///
    /// The failure was silence in both places, which is why it went unnoticed twice. This
    /// is the assertion that would have caught it, and it needs no window.
    #[test]
    fn a_view_is_built_ready_to_be_read() {
        let theme = Theme::default();
        let prepared =
            surfaced(|| build_view(&Deferred, &theme, &frus_widgets::Runtime::default()));
        let ids = collect_ids(prepared.as_ref());
        assert!(
            ids.len() > 1,
            "an application inside a deferred subtree has identities to mount: {ids:?}"
        );
        // And every one of them is reachable, which is what the burst path needs.
        for id in &ids {
            assert!(
                find_widget(prepared.as_ref(), *id).is_some(),
                "{id:?} was counted but cannot be found"
            );
        }
    }

    /// The same view, unprepared, is the state both call sites used to read.
    #[test]
    #[should_panic(expected = "before it was built")]
    fn an_unprepared_view_is_the_state_that_broke() {
        let theme = Theme::default();
        let raw = surfaced(|| crate::Application::view(&Deferred, &theme));
        let _ = collect_ids(raw.as_ref());
    }

    /// A press on a **dismissible** row that never moved is a tap, and the widget under
    /// the finger owes it a click (reported on a device: a task row's avatar opened
    /// nothing, while a control a few hundred pixels away in the same card worked).
    ///
    /// The row registers a swipe on the press, in case the finger is about to slide
    /// sideways. When it does not, the swipe has to stand down. Every other gesture
    /// here already did; this one was left out of the list.
    #[test]
    fn a_swipe_that_never_started_is_still_a_tap() {
        let item = frus_widgets::Dismissable {
            id: WidgetId::from_u64(1),
            rect: Rect::new(0.0, 0.0, 300.0, 62.0),
            spec: frus_widgets::DismissSpec::default(),
        };
        let dismiss = |moved| Drag::Dismiss {
            item,
            last: Point::new(0.0, 0.0),
            moved,
        };
        assert!(
            gesture_was_a_tap(Some(&dismiss(false))),
            "a swipe under the threshold leaves the click alone"
        );
        assert!(
            !gesture_was_a_tap(Some(&dismiss(true))),
            "a swipe that ran has already been answered and must not also click"
        );
        // A scroll, the variant that was already right — and the one that masked this
        // bug, since a list long enough to scroll claims the press before the swipe can.
        let scroll = Drag::Scroll {
            id: WidgetId::from_u64(2),
            last: Point::new(0.0, 0.0),
            moved: false,
            carried: (0.0, 0.0),
            dismiss: None,
            axis: None,
            pan: None,
        };
        assert!(gesture_was_a_tap(Some(&scroll)));
        // A press on a sheet's panel likewise: a button in the sheet still clicks, and a
        // sheet that was dragged does not also click what it was dragged by (515).
        let sheet = |moved| Drag::Sheet {
            id: WidgetId::from_u64(4),
            last: Point::new(0.0, 0.0),
            moved,
            available: 800.0,
        };
        assert!(gesture_was_a_tap(Some(&sheet(false))));
        assert!(!gesture_was_a_tap(Some(&sheet(true))));
        // And a gesture that captures on the press, rather than at a threshold, never
        // becomes a tap however still the finger was.
        let select = Drag::TextSelect {
            id: WidgetId::from_u64(3),
            rect: Rect::new(0.0, 0.0, 10.0, 10.0),
        };
        assert!(!gesture_was_a_tap(Some(&select)));
        assert!(!gesture_was_a_tap(None), "no gesture, no verdict to give");
    }

    /// A page that scrolls down must not drift sideways while it does it (reported on a
    /// device, 2026-08-16). No finger travels in a straight line, so an area that can go
    /// both ways has to pick one and keep it.
    #[test]
    fn a_scroll_gesture_is_claimed_by_one_axis() {
        // Both axes available: the direction the finger went in wins, and a little wobble
        // across it changes nothing.
        assert!(claim_axis(6.0, 40.0, true, true), "down the page");
        assert!(!claim_axis(40.0, 6.0, true, true), "across it");
        // A tie reads as vertical, which is the way a page reads.
        assert!(claim_axis(10.0, 10.0, true, true));
        // One axis only: it takes the gesture whatever the finger did, or a diagonal flick
        // down a list would move nothing at all.
        assert!(claim_axis(40.0, 6.0, false, true), "a list only goes down");
        assert!(
            !claim_axis(6.0, 40.0, true, false),
            "a strip only goes across"
        );
    }

    /// An area under the finger, `max_x` by `max_y` of content out of sight.
    fn area(id: u64, max_x: f32, max_y: f32) -> frus_widgets::Scrollable {
        frus_widgets::Scrollable {
            id: WidgetId::from_u64(id),
            viewport: Rect::new(0.0, 0.0, 100.0, 100.0),
            max_x,
            max_y,
            axis: frus_widgets::Axis::Vertical,
            physics: frus_widgets::ScrollPhysics::CLAMPING,
            overscroll: Some(frus_widgets::OverscrollIndicator::Glow),
            fling: frus_widgets::VelocityStrategy::Regression,
            refresh: None,
            page: None,
            reverse_x: false,
            reverse_y: false,
            host: None,
            keep_visible: None,
        }
    }

    /// A strip that only slides sideways, sitting in a page that only scrolls down, must
    /// not swallow a drag downwards: the page behind it is what that drag is about
    /// (reported on a device, 2026-08-16).
    #[test]
    fn the_gesture_goes_to_the_area_that_can_take_it() {
        let strip = area(1, 400.0, 0.0);
        let page = area(2, 0.0, 900.0);
        let chain = [strip, page]; // innermost first, as the finger meets them
        assert_eq!(
            claim_area(&chain, strip.id, true).map(|a| a.id),
            Some(page.id),
            "down the page, over the strip"
        );
        assert_eq!(
            claim_area(&chain, strip.id, false).map(|a| a.id),
            Some(strip.id),
            "across the strip"
        );
        // Nothing behind it: the strip keeps the gesture and goes its own way, which is
        // what a lone recogniser in an arena does.
        assert_eq!(
            claim_area(&[strip], strip.id, true).map(|a| a.id),
            Some(strip.id)
        );
        // The innermost that can take it wins, not the outermost.
        let inner = area(3, 0.0, 200.0);
        assert_eq!(
            claim_area(&[inner, strip, page], inner.id, true).map(|a| a.id),
            Some(inner.id)
        );
    }

    /// **The physics have the last word on a finger** (milestone 649): never scrollable
    /// takes none, even with content to reveal, and the area around it gets the drag;
    /// always scrollable takes one along its axis with nothing to reveal.
    #[test]
    fn the_physics_have_the_last_word_on_a_finger() {
        let mut inner = area(1, 0.0, 300.0);
        inner.physics = frus_widgets::ScrollPhysics::NEVER;
        assert!(!inner.accepts_user_offset((0.0, 0.0)));
        assert!(!inner.takes_user_scroll(true));
        let outer = area(2, 0.0, 600.0);
        let chain = [inner, outer];
        assert_eq!(
            claim_area(&chain, WidgetId::from_u64(1), true).map(|a| a.id),
            Some(WidgetId::from_u64(2)),
            "the page around it scrolls"
        );
        assert_eq!(
            claim_area(&[inner], WidgetId::from_u64(1), true).map(|a| a.id),
            None,
            "and alone it keeps nothing"
        );

        let mut short = area(3, 0.0, 0.0);
        short.physics = frus_widgets::ScrollPhysics::ALWAYS;
        assert!(short.accepts_user_offset((0.0, 0.0)));
        assert!(short.takes_user_scroll(true), "along its axis");
        assert!(!short.takes_user_scroll(false), "and not across it");
        assert_eq!(
            claim_area(&[short, outer], WidgetId::from_u64(3), true).map(|a| a.id),
            Some(WidgetId::from_u64(3)),
            "a short list that always scrolls keeps the drag from the page"
        );
        let mut strip = short;
        strip.axis = frus_widgets::Axis::Horizontal;
        assert_eq!(
            claim_area(&[strip, outer], WidgetId::from_u64(3), true).map(|a| a.id),
            Some(WidgetId::from_u64(2)),
            "a strip that always scrolls across leaves a drag down to the page"
        );
        let mut both = short;
        both.axis = frus_widgets::Axis::Both;
        assert!(both.takes_user_scroll(false) && both.takes_user_scroll(true));
    }

    /// An end-of-content glow on a page with nothing to scroll says something about the
    /// content that is not true (reported on a device, 2026-08-16). The reference takes the
    /// drag recognisers away outright when everything fits.
    #[test]
    fn an_area_whose_content_fits_takes_no_finger() {
        let fits = area(1, 0.0, 0.0);
        assert!(!fits.accepts_user_offset((0.0, 0.0)));
        // Unless it is already displaced — content that shrank under a scrolled offset has
        // to be draggable back into place.
        assert!(fits.accepts_user_offset((0.0, 12.0)));
        // Or a refresh area is listening above it: a list of two items still pulls down.
        let mut pullable = fits;
        pullable.refresh = Some(WidgetId::from_u64(9));
        assert!(pullable.accepts_user_offset((0.0, 0.0)));
        // A single pixel out of sight is content to reveal, and enough.
        assert!(area(1, 0.0, 1.0).accepts_user_offset((0.0, 0.0)));
        assert!(area(1, 1.0, 0.0).accepts_user_offset((0.0, 0.0)));
    }
    use frus_widgets::WidgetId;
    use std::collections::HashSet;

    /// An estimate reading `velocity` px/s after travelling `offset` px.
    fn released(velocity: (f32, f32), offset: (f32, f32)) -> VelocityEstimate {
        VelocityEstimate {
            velocity: frus_widgets::Velocity::new(velocity.0, velocity.1),
            confidence: 1.0,
            duration: 0.05,
            offset,
        }
    }

    #[test]
    fn a_fast_twitch_that_went_nowhere_is_not_a_fling() {
        // 2000 px/s, but the finger covered 3 px: a wobble on lift-off, not a throw.
        let (x, y) = fling_velocity(released((0.0, 2000.0), (0.0, 3.0)), TOUCH_SLOP);
        assert_eq!((x, y), (0.0, 0.0));
        // The same speed over a real distance is.
        let (_, y) = fling_velocity(released((0.0, 2000.0), (0.0, 60.0)), TOUCH_SLOP);
        assert_eq!(y, 2000.0);
    }

    #[test]
    fn the_fling_gate_is_per_axis() {
        // A vertical swipe with the sideways wobble a thumb always adds: the wobble
        // must not fling the content horizontally.
        let (x, y) = fling_velocity(released((300.0, 1500.0), (5.0, 120.0)), TOUCH_SLOP);
        assert_eq!(x, 0.0, "the wobble is not a horizontal fling");
        assert_eq!(y, 1500.0, "the swipe still flings vertically");
    }

    #[test]
    fn a_precise_pointer_needs_almost_no_travel() {
        // The same 3 px that a finger's slop rejects is a deliberate mouse drag.
        let estimate = released((0.0, 900.0), (0.0, 3.0));
        assert_eq!(fling_velocity(estimate, TOUCH_SLOP).1, 0.0);
        assert_eq!(fling_velocity(estimate, PRECISE_SLOP).1, 900.0);
    }

    #[test]
    fn insertion_line_sits_on_the_target_top_edge() {
        // The upper half hovered means inserting **before**: a band of thickness 4
        // centred on the top edge (y=100) of a target 200 wide.
        let line = drop_insertion_line(
            Rect::new(20.0, 100.0, 200.0, 44.0),
            4.0,
            false,
            ReorderAxis::Vertical,
            false,
        );
        assert_eq!(line.x, 20.0, "aligned to the target's left");
        assert_eq!(line.width, 200.0, "the target's full width");
        assert_eq!(line.y, 98.0, "centred on the top edge (100 - 4/2)");
        assert_eq!(line.height, 4.0);
    }

    #[test]
    fn insertion_line_sits_on_the_target_bottom_edge_when_inserting_after() {
        // The lower half hovered means inserting **after**: the band slides to the
        // **bottom** edge (y = 100 + 44 = 144, centred → 142). Same width, same thickness.
        let line = drop_insertion_line(
            Rect::new(20.0, 100.0, 200.0, 44.0),
            4.0,
            true,
            ReorderAxis::Vertical,
            false,
        );
        assert_eq!(line.x, 20.0, "still aligned to the left");
        assert_eq!(line.width, 200.0, "the target's full width");
        assert_eq!(line.y, 142.0, "centred on the bottom edge (144 - 4/2)");
        assert_eq!(line.height, 4.0);
        // A vertical list reads down whichever way its text runs.
        let rtl = drop_insertion_line(
            Rect::new(20.0, 100.0, 200.0, 44.0),
            4.0,
            true,
            ReorderAxis::Vertical,
            true,
        );
        assert_eq!(rtl, line, "right to left changes nothing down a list");
    }

    /// **A horizontal list's line stands on its end**, on the edge the row goes to: the
    /// right one after a row that reads left to right, the left one after a row that reads
    /// right to left — where what follows it is.
    #[test]
    fn a_horizontal_insertion_line_stands_on_the_edge_the_row_goes_to() {
        let chip = Rect::new(100.0, 20.0, 80.0, 48.0);
        let line = |after, rtl| drop_insertion_line(chip, 4.0, after, ReorderAxis::Horizontal, rtl);
        let before = line(false, false);
        assert_eq!(
            (before.x, before.y, before.width, before.height),
            (98.0, 20.0, 4.0, 48.0),
            "before a row: its left edge, the full height, 4 wide"
        );
        assert_eq!(
            line(true, false).x,
            178.0,
            "after it: its right edge (180 - 4/2)"
        );
        // Right to left, the two edges trade places.
        assert_eq!(
            line(true, true).x,
            98.0,
            "after, right to left: the left edge"
        );
        assert_eq!(
            line(false, true).x,
            178.0,
            "before, right to left: the right edge"
        );
    }

    /// **Which gesture a reorderable gets.** A column slides; a row or a card is inserted
    /// between slots — and a horizontal reorderable is a row only when it says so, which is
    /// what keeps a table's columns exactly as they were.
    #[test]
    fn a_horizontal_reorderable_inserts_only_when_it_says_so() {
        assert_eq!(
            ReorderMotion::of(ReorderAxis::Horizontal, false),
            ReorderMotion::Columns,
            "a table's column"
        );
        assert_eq!(
            ReorderMotion::of(ReorderAxis::Horizontal, true),
            ReorderMotion::Slots(ReorderAxis::Horizontal),
            "a horizontal list's row"
        );
        // Every vertical reorderable inserts, whatever it answers.
        for inserts in [false, true] {
            assert_eq!(
                ReorderMotion::of(ReorderAxis::Vertical, inserts),
                ReorderMotion::Slots(ReorderAxis::Vertical)
            );
        }
        // A widget that answers nothing keeps the trait's defaults, which are the table's.
        assert_eq!(
            reorder_motion::<()>(&frus_widgets::Container::new()),
            ReorderMotion::Columns
        );
        // And the real rows say which they are, down and across.
        for (axis, expected) in [
            (
                ReorderAxis::Vertical,
                ReorderMotion::Slots(ReorderAxis::Vertical),
            ),
            (
                ReorderAxis::Horizontal,
                ReorderMotion::Slots(ReorderAxis::Horizontal),
            ),
        ] {
            let list = frus_widgets::ReorderableList::<()>::new(|_, _| ())
                .axis(axis)
                .row(frus_widgets::Container::new().width(60.0));
            let row = frus_widgets::Widget::children(&list)[0].as_ref();
            assert_eq!(reorder_motion(row), expected, "{axis:?}");
        }
    }

    /// **The ghost stays in its lane.** A column rises and follows x; a card follows the
    /// finger anywhere; a horizontal list's row follows x and nothing else — so a finger
    /// that wanders below the strip does not drag the row off it.
    #[test]
    fn a_horizontal_rows_ghost_follows_the_finger_along_x_only() {
        let travel = (120.0, 35.0);
        assert_eq!(
            ghost_offset(ReorderMotion::Columns, travel),
            (120.0, super::drag_preview::LIFT_Y)
        );
        assert_eq!(
            ghost_offset(ReorderMotion::Slots(ReorderAxis::Vertical), travel),
            (120.0, 35.0)
        );
        assert_eq!(
            ghost_offset(ReorderMotion::Slots(ReorderAxis::Horizontal), travel),
            (120.0, 0.0)
        );
    }

    #[test]
    fn focus_returns_to_trigger_when_overlay_closes() {
        let anchor = WidgetId::from_u64(1);
        let item = WidgetId::from_u64(2);
        let (mut history, mut prev) = (Vec::new(), None);

        // Frame 1: focus on the anchor, which is present.
        let f = resolve_focus(
            Some(anchor),
            &HashSet::from([anchor]),
            &mut history,
            &mut prev,
        );
        assert_eq!(f, Some(anchor));
        assert!(history.is_empty());

        // Frame 2: the menu is open and the item focused; the anchor is pushed as trigger.
        let present = HashSet::from([anchor, item]);
        let f = resolve_focus(Some(item), &present, &mut history, &mut prev);
        assert_eq!(f, Some(item));
        assert_eq!(history, vec![anchor]);

        // Frame 3: the menu closed and the item vanished → back to the trigger, history spent.
        let f = resolve_focus(
            Some(item),
            &HashSet::from([anchor]),
            &mut history,
            &mut prev,
        );
        assert_eq!(f, Some(anchor), "focus returns to the trigger");
        assert!(history.is_empty());
    }

    #[test]
    fn focus_falls_to_none_when_no_trigger_remains() {
        let a = WidgetId::from_u64(1);
        let (mut history, mut prev) = (Vec::new(), Some(a));
        // `a` vanishes and the history is empty → no focus at all.
        let f = resolve_focus(Some(a), &HashSet::new(), &mut history, &mut prev);
        assert_eq!(f, None);
        assert_eq!(prev, None);
    }

    #[test]
    fn spring_approaches_target_monotonically_and_settles() {
        // From 0 toward 100: a monotonic approach with no overshoot, all but reached
        // after several 16 ms steps.
        let mut x = 0.0;
        let mut prev = -1.0;
        for _ in 0..30 {
            x = spring_toward(x, 100.0, 0.016, 0.07);
            assert!(x > prev && x <= 100.0, "monotonic and bounded: {x}");
            prev = x;
        }
        assert!(x > 99.0, "all but reached after ~0.5 s: {x}");
    }

    #[test]
    fn ghost_card_shape() {
        let theme = Theme::default();
        let card = Rect::new(140.0, 0.0, 80.0, 34.0);
        // An empty ghost falls back to a shadow plus a solid bordered card: 2 primitives.
        let mut scene = Scene::new();
        draw_ghost_card(&mut scene, &theme, card, &[]);
        assert_eq!(scene.primitives().len(), 2, "shadow plus solid card");
    }
}

/// The half of a scroll request that belongs to the shell: turning the **name** an
/// application wrote into the region a frame actually has.
#[cfg(test)]
mod sheet_request_tests {
    use super::{apply_sheet_requests, Runtime, Widget};
    use crate::command::Command;
    use frus_widgets::{
        build_ui, keyed, Container, DraggableScrollableSheet, SheetTo, Size, Theme,
    };

    /// A page with one named sheet on it — the key on a wrapper the application wrote, the
    /// state on a panel it never sees.
    fn view() -> Box<dyn Widget<()>> {
        Box::new(
            Container::<()>::new()
                .width(400.0)
                .height(800.0)
                .child(keyed(
                    "places",
                    DraggableScrollableSheet::<()>::new(Container::new()),
                )),
        )
    }

    /// **A request reaches the sheet the view named**, and nothing else: another key, or a
    /// frame without the sheet, hands it back unplaced and moves nothing.
    #[test]
    fn a_request_reaches_the_sheet_the_view_named() {
        let tree = view();
        let mut runtime = Runtime::default();
        let sheets = build_ui(
            tree.as_ref(),
            Size::new(400.0, 800.0),
            &runtime,
            &Theme::default(),
        )
        .sheets()
        .to_vec();
        let sheet = sheets.first().expect("the page has its sheet").clone();

        let requests = Command::<()>::sheet("places", SheetTo::size(0.9))
            .into_parts()
            .sheets;
        let (unplaced, moved) =
            apply_sheet_requests(&mut runtime, tree.as_ref(), requests, &sheets);
        assert!(unplaced.is_empty());
        assert!(moved);
        assert_eq!(runtime.sheet_size(sheet.id, &sheet.spec), 0.9);

        let elsewhere = Command::<()>::sheet("elsewhere", SheetTo::size(0.3))
            .into_parts()
            .sheets;
        let (unplaced, moved) =
            apply_sheet_requests(&mut runtime, tree.as_ref(), elsewhere, &sheets);
        assert_eq!(unplaced.len(), 1);
        assert!(!moved);
        let not_yet = Command::<()>::sheet("places", SheetTo::size(0.3))
            .into_parts()
            .sheets;
        let (unplaced, _) = apply_sheet_requests(&mut runtime, tree.as_ref(), not_yet, &[]);
        assert_eq!(unplaced.len(), 1, "kept for the frame that has the sheet");
        assert_eq!(
            runtime.sheet_size(sheet.id, &sheet.spec),
            0.9,
            "nothing moved"
        );
    }
}

#[cfg(test)]
mod scroll_request_tests {
    use super::{apply_scroll_requests, Rect, Runtime, Scrollable, Widget, WidgetId};
    use crate::command::Command;
    use frus_widgets::{keyed, Container, ScrollTo, SingleChildScrollView};

    /// A view with one named scroll region in it, and nothing else of interest.
    fn view() -> Box<dyn Widget<()>> {
        Box::new(Container::<()>::new().child(keyed(
            "log",
            SingleChildScrollView::<()>::new().height(200.0),
        )))
    }

    /// The region as the frame would register it: a 200-tall window over 1 000 of content.
    fn region(id: WidgetId) -> Scrollable {
        Scrollable {
            id,
            viewport: Rect {
                x: 0.0,
                y: 0.0,
                width: 300.0,
                height: 200.0,
            },
            max_x: 0.0,
            max_y: 1000.0,
            axis: frus_widgets::Axis::Vertical,
            physics: frus_widgets::ScrollPhysics::CLAMPING,
            overscroll: Some(frus_widgets::OverscrollIndicator::Glow),
            fling: frus_widgets::VelocityStrategy::Regression,
            refresh: None,
            page: None,
            reverse_x: false,
            reverse_y: false,
            keep_visible: None,
            host: None,
        }
    }

    /// The key a request carries and the key the view declared are the **same hash** —
    /// which is the whole of the identity design, and the one thing that cannot be
    /// checked on either side alone.
    #[test]
    fn a_request_reaches_the_region_the_view_named() {
        let tree = view();
        let requests = Command::<()>::scroll("log", ScrollTo::end().instant())
            .into_parts()
            .scrolls;
        let id = frus_widgets::find_by_key(tree.as_ref(), requests[0].0)
            .expect("the view named it, so the tree knows it");
        let mut runtime = Runtime::default();
        let (unplaced, moved) =
            apply_scroll_requests(&mut runtime, tree.as_ref(), requests, &[region(id)]);
        assert!(unplaced.is_empty());
        assert!(moved);
        assert_eq!(runtime.scroll.get(&id), Some(&(0.0, 1000.0)));
    }

    /// A region that has only just appeared is not in the registry the request is first
    /// tried against — that one was built last frame — so it is handed back rather than
    /// thrown away. Coming back to a screen and being put where you left off depends on
    /// exactly this.
    #[test]
    fn a_region_this_registry_has_not_got_is_handed_back() {
        let tree = view();
        let requests = Command::<()>::scroll("log", ScrollTo::y(120.0))
            .into_parts()
            .scrolls;
        let mut runtime = Runtime::default();
        let (unplaced, moved) = apply_scroll_requests(&mut runtime, tree.as_ref(), requests, &[]);
        assert_eq!(unplaced.len(), 1, "kept for the second attempt");
        assert!(!moved);
        assert!(runtime.scroll_target.is_empty());
    }

    /// A key naming nothing at all leaves no trace: the caller drops what comes back,
    /// so a typo costs one frame's lookup and never accumulates.
    #[test]
    fn a_name_the_view_does_not_use_moves_nothing() {
        let tree = view();
        let requests = Command::<()>::scroll("ledger", ScrollTo::start())
            .into_parts()
            .scrolls;
        let mut runtime = Runtime::default();
        let id = frus_widgets::find_by_key(
            tree.as_ref(),
            Command::<()>::scroll("log", ScrollTo::start())
                .into_parts()
                .scrolls[0]
                .0,
        )
        .expect("the real one is there");
        let (unplaced, moved) =
            apply_scroll_requests(&mut runtime, tree.as_ref(), requests, &[region(id)]);
        assert_eq!(unplaced.len(), 1);
        assert!(!moved);
        assert!(runtime.scroll.is_empty() && runtime.scroll_target.is_empty());
    }

    /// Two requests in one batch, both placed, and the batch is what `Command::batch`
    /// produces — a screen that restores both axes writes two and means two.
    #[test]
    fn a_batch_places_every_request_it_carries() {
        let tree = view();
        let requests = Command::<()>::batch([
            Command::scroll("log", ScrollTo::y(400.0).instant()),
            Command::scroll("log", ScrollTo::y(600.0).instant()),
        ])
        .into_parts()
        .scrolls;
        assert_eq!(requests.len(), 2);
        let id = frus_widgets::find_by_key(tree.as_ref(), requests[0].0).expect("named");
        let mut runtime = Runtime::default();
        let (unplaced, moved) =
            apply_scroll_requests(&mut runtime, tree.as_ref(), requests, &[region(id)]);
        assert!(unplaced.is_empty() && moved);
        assert_eq!(
            runtime.scroll.get(&id),
            Some(&(0.0, 600.0)),
            "the last request is the current statement"
        );
    }
}

#[cfg(test)]
mod autoscroll_tests {
    use super::{
        edge_autoscroll, follow_content, Drag, Point, Rect, WidgetId, AUTOSCROLL_MAX_OVERHANG,
        AUTOSCROLL_VELOCITY,
    };

    /// A viewport from 100 to 500, with room to scroll either way.
    const VIEW: (f32, f32) = (100.0, 500.0);
    const ROOM: (f32, f32) = (1000.0, 1000.0);
    /// A sixtieth of a second, which is the frame this is asked on.
    const DT: f32 = 1.0 / 60.0;

    #[test]
    fn a_row_inside_the_viewport_scrolls_nothing() {
        assert_eq!(edge_autoscroll((200.0, 260.0), VIEW, ROOM, DT), None);
        // Touching the edge exactly is still inside: the row has not asked for anything.
        assert_eq!(edge_autoscroll((440.0, 500.0), VIEW, ROOM, DT), None);
    }

    /// The law: pixels per second per pixel of overhang, so ten pixels out is ten times
    /// the speed of one pixel out — the row is not dragged along by a fixed nudge.
    #[test]
    fn the_speed_follows_how_far_out_the_row_is() {
        let near = edge_autoscroll((460.0, 501.0), VIEW, ROOM, DT).expect("one pixel out");
        let far = edge_autoscroll((460.0, 510.0), VIEW, ROOM, DT).expect("ten pixels out");
        assert!(
            near < 0.0,
            "the content moves up to reveal what is below: {near}"
        );
        assert!(
            (far / near - 10.0).abs() < 0.01,
            "ten times as far, ten times as fast: {near} vs {far}"
        );
        assert!(
            (near + 1.0 * AUTOSCROLL_VELOCITY * DT).abs() < 1e-4,
            "one pixel out, at the stated velocity: {near}"
        );
    }

    /// Carrying a row right off the window is not a request to scroll a thousand times
    /// faster; past the cap the speed stops growing.
    #[test]
    fn the_overhang_is_capped() {
        let far = edge_autoscroll((460.0, 520.0), VIEW, ROOM, DT).expect("twenty out");
        let absurd = edge_autoscroll((460.0, 5000.0), VIEW, ROOM, DT).expect("off the window");
        assert!((far - absurd).abs() < 1e-4, "{far} vs {absurd}");
        assert!((absurd + AUTOSCROLL_MAX_OVERHANG * AUTOSCROLL_VELOCITY * DT).abs() < 1e-4);
    }

    /// Above the top the content moves the other way, and the sign is the whole of the
    /// difference between the two edges.
    #[test]
    fn above_the_top_the_content_comes_down() {
        let up = edge_autoscroll((90.0, 150.0), VIEW, ROOM, DT).expect("ten above");
        assert!(up > 0.0, "{up}");
    }

    /// **What is carried stays under the finger while its list scrolls.**
    ///
    /// Seen on a phone: a row carried to the bottom edge started the list scrolling, and
    /// the ghost rode up with the content — it is drawn at the row's box, and the box had
    /// moved — until it no longer hung over the edge and the scroll stopped by itself,
    /// 95 px in. The press moves with the content instead.
    #[test]
    fn a_carried_item_follows_its_content() {
        // The list scrolled on by 95 px: its content went 95 px up the screen.
        let shift = (0.0, -95.0);
        let pressed = Point::new(900.0, 1330.0);
        let row_then = Rect::new(105.0, 1250.0, 700.0, 160.0);
        let row_now = row_then.translate(0.0, -95.0);
        let finger = Point::new(900.0, 2030.0);

        let mut reorder = Drag::Reorder {
            id: WidgetId::from_u64(1),
            from: 0,
            start: pressed,
            moved: true,
            carried: Some((WidgetId::from_u64(1), row_then)),
        };
        follow_content(&mut reorder, shift);
        let Drag::Reorder { start, carried, .. } = reorder else {
            unreachable!("still a reorder");
        };
        // The box it was carried from went with the content, as the row did — and the frame's
        // own box is not asked again, since the frame clips a row carried to an edge and loses
        // one scrolled out of sight (milestone 527).
        let (_, carried) = carried.expect("the box it was carried from");
        assert_eq!(carried, row_now, "the carried box went with the content");
        // Drawn the way the shell draws it: the carried box, plus the travel.
        let ghost = carried.translate(finger.x - start.x, finger.y - start.y);
        assert_eq!(
            ghost,
            row_then.translate(finger.x - pressed.x, finger.y - pressed.y),
            "the ghost is where it would be had nothing scrolled"
        );

        let mut item = Drag::Item {
            source: frus_widgets::DragSource {
                id: WidgetId::from_u64(1),
                rect: row_then,
                payload: 7,
            },
            start: pressed,
            moved: true,
            over: None,
        };
        follow_content(&mut item, shift);
        let Drag::Item { source, start, .. } = item else {
            unreachable!("still an item");
        };
        assert_eq!(
            source.rect, row_now,
            "the box taken at the press went with the content"
        );
        assert_eq!(start, Point::new(900.0, 1235.0), "and so did the press");
    }

    /// At the end of the content there is nothing left to reveal, so the list stays where
    /// it is instead of straining against its own end.
    #[test]
    fn an_exhausted_edge_stays_still() {
        assert_eq!(
            edge_autoscroll((460.0, 520.0), VIEW, (1000.0, 0.0), DT),
            None
        );
        assert_eq!(
            edge_autoscroll((90.0, 150.0), VIEW, (0.0, 1000.0), DT),
            None
        );
    }

    /// A row taller than the viewport hangs over both edges at once. Pulled two ways it
    /// would scroll nowhere, or jitter between them; the leading edge decides.
    #[test]
    fn a_row_taller_than_the_viewport_follows_its_leading_edge() {
        let both = edge_autoscroll((50.0, 900.0), VIEW, ROOM, DT).expect("over both edges");
        assert!(both > 0.0, "the top edge wins: {both}");
    }
}

/// **A back gesture the page below cannot take** (milestone 531).
///
/// Seen on a phone: a back gesture from the left edge, at the height of a task row of the
/// page below, did not slide the page on top. Half a second in, the row was lifted instead —
/// drawn over the page on top in its green-outlined ghost, and following the finger — and it
/// went away when the finger did. At a height with no row the gesture worked.
///
/// The press that starts the gesture is tested against the frame on screen, and after a push
/// that frame is the push's last: an application's animation that has just settled asks for
/// no rebuild, so the page the push left is still in the frame, parallaxed to the left and
/// under the finger. The press found the row's hold, the long press armed, and its deadline
/// replaced the gesture with a lift.
#[cfg(test)]
mod back_gesture_tests {
    use super::{
        drag_after_hold, frame_needs_build, hold_candidates, Drag, Point, Theme, WidgetId,
    };
    use frus_widgets::{build_ui, column, Container, DragSource, Draggable, Navigator};
    use frus_widgets::{Rect, Runtime, Size, Ui, Widget};

    /// A phone, in logical pixels.
    const W: f32 = 392.0;
    const H: f32 = 850.0;
    /// Where the row sits on the page below, and the finger's press on the edge at its
    /// height.
    const ROW_TOP: f32 = 480.0;
    const ROW_HEIGHT: f32 = 66.0;
    const ON_THE_ROW: Point = Point::new(3.0, 509.0);
    const ABOVE_THE_ROW: Point = Point::new(3.0, 200.0);
    /// The long press the row asks for.
    const HELD: u8 = 1;

    /// A page with one row that lifts on a hold and says something when held, below a
    /// stretch with nothing to take.
    fn home() -> impl Widget<u8> {
        column![
            Container::<u8>::new().width(W).height(ROW_TOP),
            Draggable::new(
                Container::<u8>::new()
                    .width(W)
                    .height(ROW_HEIGHT)
                    .on_long_press(HELD)
            )
            .payload(7)
            .long_press(),
        ]
    }

    /// The frame on screen after a push from `home` has settled: the push's last, with the
    /// page it left still in it.
    fn after_a_push() -> Navigator<u8> {
        Navigator::new("data", Container::<u8>::new().width(W).height(H))
            .size(W, H)
            .from("home", home(), 0.999, true)
    }

    fn frame(root: &dyn Widget<u8>) -> Ui<u8> {
        build_ui(
            root,
            Size::new(W, H),
            &Runtime::default(),
            &Theme::default(),
        )
    }

    fn back(at: Point) -> Drag {
        Drag::Back { start_x: at.x }
    }

    fn still_scroll() -> Drag {
        Drag::Scroll {
            id: WidgetId::from_u64(9),
            last: ON_THE_ROW,
            moved: false,
            carried: (0.0, 0.0),
            dismiss: None,
            axis: None,
            pan: None,
        }
    }

    fn row_source() -> DragSource {
        DragSource {
            id: WidgetId::from_u64(3),
            rect: Rect::new(-117.0, ROW_TOP, W, ROW_HEIGHT),
            payload: 7,
        }
    }

    /// **Why the row was under the finger at all**: the frame a transition ends on is built
    /// again. The tick that ends a push takes the page it left out of the state and reports
    /// nothing moving, so a loop that builds only while something moves hit-tests the
    /// push's last frame from then on — the page left behind still in it, where a tap or a
    /// hold can reach what is no longer on screen. The demo's
    /// `the_last_frame_of_a_push_still_holds_the_page_it_left` shows that frame on its own
    /// page, at the phone's coordinates.
    #[test]
    fn the_frame_an_animation_settles_in_is_built_again() {
        assert!(
            frame_needs_build(false, false, true, false),
            "the frame the application's animation stops in builds the view again"
        );
        assert!(
            frame_needs_build(false, true, true, false),
            "as does every frame while it moves"
        );
        assert!(
            !frame_needs_build(false, false, false, false),
            "and a still frame after a still one repaints the tree it has"
        );
        assert!(frame_needs_build(true, false, false, false), "unless asked");
        assert!(
            frame_needs_build(false, false, false, true),
            "or the frame has its own reason"
        );
    }

    /// The reproduction: the frame really has a row to take under the finger, and a back
    /// gesture's press takes nothing from it.
    #[test]
    fn a_back_gesture_claims_nothing_under_its_finger() {
        let root = after_a_push();
        let ui = frame(&root);
        let (held, lift) = hold_candidates(None, Some(&ui), Some(&root), ON_THE_ROW);
        assert!(
            lift.is_some() && held == Some(HELD),
            "the frame the phone had: a press there, with no gesture, finds the row's hold"
        );

        let gesture = back(ON_THE_ROW);
        let (held, lift) = hold_candidates(Some(&gesture), Some(&ui), Some(&root), ON_THE_ROW);
        assert!(
            lift.is_none(),
            "a back gesture's press arms no lift of the row under it"
        );
        assert_eq!(held, None, "nor its long press");
    }

    /// Whatever a press found, the deadline never takes the pointer from a back gesture:
    /// the gesture goes on, and keeps its start.
    #[test]
    fn a_hold_never_takes_the_pointer_from_a_back_gesture() {
        let reorder = Some((WidgetId::from_u64(4), 2, ON_THE_ROW));
        for (lift, reorder) in [
            (Some(row_source()), None),
            (None, reorder),
            (Some(row_source()), reorder),
            (None, None),
        ] {
            let after = drag_after_hold(Some(back(ON_THE_ROW)), lift, reorder, ON_THE_ROW);
            assert!(
                matches!(after, Some(Drag::Back { start_x }) if start_x == ON_THE_ROW.x),
                "the back gesture is still the drag (lift {}, reorder {})",
                lift.is_some(),
                reorder.is_some()
            );
        }
    }

    /// At a height with nothing to take — where the gesture always worked — it still does.
    #[test]
    fn a_back_gesture_where_nothing_is_under_it_still_owns_the_pointer() {
        let root = after_a_push();
        let ui = frame(&root);
        let gesture = back(ABOVE_THE_ROW);
        let (held, lift) = hold_candidates(Some(&gesture), Some(&ui), Some(&root), ABOVE_THE_ROW);
        assert!(held.is_none() && lift.is_none());
        assert!(matches!(
            drag_after_hold(Some(gesture), None, None, ABOVE_THE_ROW),
            Some(Drag::Back { .. })
        ));
    }

    /// No regression: a hold on the row with no back gesture — the list's scroll still
    /// waiting to see whether the finger moves — lifts it, or its reorder, and says what
    /// the row asks when held.
    #[test]
    fn a_hold_on_a_row_without_a_back_gesture_still_lifts_it() {
        let root = home();
        let ui = frame(&root);
        let at = Point::new(40.0, ROW_TOP + 10.0);
        let scroll = still_scroll();
        let (held, lift) = hold_candidates(Some(&scroll), Some(&ui), Some(&root), at);
        assert_eq!(
            held,
            Some(HELD),
            "the long press is armed under a still scroll"
        );
        assert!(lift.is_some(), "and so is the lift");
        let (held, lift) = hold_candidates(None, Some(&ui), Some(&root), at);
        assert!(held.is_some() && lift.is_some(), "and with no drag at all");

        let cursor = Point::new(41.0, ROW_TOP + 11.0);
        let lifted = drag_after_hold(Some(still_scroll()), Some(row_source()), None, cursor);
        assert!(
            matches!(lifted, Some(Drag::Item { moved: true, start, .. }) if start == cursor),
            "the hold lifts the item where the finger is"
        );
        let reorder = Some((WidgetId::from_u64(4), 2, at));
        let reordering = drag_after_hold(Some(still_scroll()), None, reorder, cursor);
        assert!(
            matches!(reordering, Some(Drag::Reorder { moved: true, from: 2, start, .. }) if start == at),
            "or picks the row up for a reorder, from where it was pressed"
        );
        assert!(
            drag_after_hold(Some(still_scroll()), None, None, cursor).is_none(),
            "a hold with nothing to lift ends the still scroll: the long press had it"
        );
    }
}

/// How many layers `primitives` hold, nested ones included (milestone 609).
fn count_layers(primitives: &[frus_widgets::Primitive]) -> u32 {
    primitives
        .iter()
        .map(|p| match p {
            frus_widgets::Primitive::Layer { primitives, .. } => 1 + count_layers(primitives),
            _ => 0,
        })
        .sum()
}

/// **What the shell reads of a key going down** (milestone 608). Winit's own event cannot be
/// made outside winit, so the shell's handling takes this, made from it in a window and by
/// hand in a test.
pub(crate) struct KeyDown {
    /// The key the layout makes of it: a character, or a named key.
    logical_key: WinitKey,
    /// Where it is on the keyboard, whatever the layout.
    physical_key: PhysicalKey,
    /// The text it types, if any.
    text: Option<winit::keyboard::SmolStr>,
    /// Whether it is the key repeating, held down.
    repeat: bool,
}

impl From<&winit::event::KeyEvent> for KeyDown {
    fn from(event: &winit::event::KeyEvent) -> Self {
        Self {
            logical_key: event.logical_key.clone(),
            physical_key: event.physical_key,
            text: event.text.clone(),
            repeat: event.repeat,
        }
    }
}

/// `scene` over the window's background, for a see-through renderer, whose frames start
/// transparent (milestone 643): everywhere but the `line` pixels at the top the system paints,
/// which are left clear for its title bar to show through. In physical pixels, as the scene
/// is; the scene's own primitives follow, in their order.
fn backdrop_under(mut scene: Scene, width: f32, height: f32, line: f32) -> Scene {
    let mut framed = Scene::new();
    framed.fill_rect(
        frus_widgets::Rect::new(0.0, line, width, (height - line).max(0.0)),
        frus_gpu::backdrop(),
    );
    for primitive in scene.split_off(0) {
        framed.push_primitive(primitive);
    }
    framed
}

#[cfg(test)]
mod backdrop_tests {
    use super::*;

    /// **A see-through frame is the window's background under everything but the line the
    /// system paints**, and the scene over it, unchanged.
    #[test]
    fn the_background_leaves_the_system_s_line_clear() {
        let mut scene = Scene::new();
        scene.fill_rect(
            frus_widgets::Rect::new(10.0, 5.0, 20.0, 20.0),
            frus_widgets::Color::WHITE,
        );
        let framed = backdrop_under(scene.clone(), 800.0, 600.0, 48.0);
        let prims = framed.primitives();
        assert_eq!(prims.len(), 2);
        match &prims[0] {
            frus_widgets::Primitive::Rect { rect, color, .. } => {
                assert_eq!(*rect, frus_widgets::Rect::new(0.0, 48.0, 800.0, 552.0));
                assert_eq!(*color, frus_gpu::backdrop());
                assert_eq!(
                    color.a, 1.0,
                    "opaque: nothing behind the window shows there"
                );
            }
            other => panic!("the background first: {other:?}"),
        }
        assert_eq!(prims[1], scene.primitives()[0], "then the scene");

        let whole = backdrop_under(Scene::new(), 800.0, 600.0, 0.0);
        assert!(
            matches!(&whole.primitives()[0],
            frus_widgets::Primitive::Rect { rect, .. } if *rect == frus_widgets::Rect::new(0.0, 0.0, 800.0, 600.0)),
            "no line: the whole window"
        );
    }
}

/// A driver with no window and no event loop: input and frames fed by hand, through the
/// shell's own paths.
#[cfg(any(test, feature = "testing"))]
#[doc(hidden)]
pub mod testing {
    use super::*;
    use crate::gesture::{PointerEvent, PointerKind, LONG_PRESS_DELAY};

    /// What the last frame left behind: the interface it laid out, and the tree it laid out from.
    pub type FrameParts<'a, Msg> = (&'a Ui<Msg>, &'a dyn Widget<Msg>);

    /// The shell around an application, on a surface of a stated logical size.
    pub struct Driver<A: Application> {
        shell: App<A>,
        size: Size,
        /// Where the last frame drew a reorder's ghost, when it drew one.
        ghost: Option<Rect>,
    }

    impl<A: Application> Driver<A> {
        /// A driver for `app` on a `width` by `height` logical surface.
        pub fn new(app: A, width: f32, height: f32) -> Self {
            let mut shell = App::detached(app);
            // Gestures are timed by the frames run, as everything else here is.
            shell.gesture_clock = Some((0.0, 0.0));
            Self {
                shell,
                size: Size::new(width, height),
                ghost: None,
            }
        }

        /// The system's **Back** — Android's back button, the browser's Back — as the shell
        /// handles it, short of leaving: whether it went back from anything.
        pub fn system_back(&mut self) -> bool {
            self.shell.system_back_step()
        }

        /// How the gesture under way will read its fling: its scroll area's behaviour's, on
        /// a drag that landed on one, else the application's (milestone 616).
        pub fn fling_strategy(&self) -> frus_widgets::VelocityStrategy {
            self.shell.gesture_velocity.strategy()
        }

        /// Where what is carried is drawn this frame — a reorder's ghost or a lifted item —
        /// or `None` when nothing is.
        pub fn carried(&self) -> Option<Rect> {
            self.shell.carried_rect()
        }

        /// Where the last frame drew a reorder's ghost — the outline around it — or `None`
        /// when it drew none.
        pub fn ghost(&self) -> Option<Rect> {
            self.ghost
        }

        /// Every scroll region of the last frame, as its viewport and its offset.
        pub fn offsets(&self) -> Vec<(Rect, (f32, f32))> {
            let s = &self.shell;
            s.ui.as_ref()
                .map(|ui| {
                    ui.scroll_regions()
                        .iter()
                        .map(|a| {
                            (
                                a.viewport,
                                s.runtime.scroll.get(&a.id).copied().unwrap_or((0.0, 0.0)),
                            )
                        })
                        .collect()
                })
                .unwrap_or_default()
        }

        /// The interface the last frame laid out — what a tap is asked about, what the registries
        /// hold — and the tree it was laid out from.
        pub fn frame_parts(&self) -> Option<FrameParts<'_, A::Message>> {
            let s = &self.shell;
            Some((s.ui.as_ref()?, s.tree.as_deref()?))
        }

        /// The words the last frame drew and the box each was drawn in, in paint order.
        pub fn texts(&self) -> Vec<(String, Rect)> {
            self.shell
                .ui
                .as_ref()
                .map(|ui| {
                    ui.scene()
                        .primitives()
                        .iter()
                        .filter_map(|p| match p {
                            frus_widgets::Primitive::Text { text, .. } => {
                                Some((text.clone(), p.bounds()))
                            }
                            _ => None,
                        })
                        .collect()
                })
                .unwrap_or_default()
        }

        /// A tap on the first word of the last frame that reads `label`, and a frame after it:
        /// how a test presses a button by what it says. Whether there was such a word.
        pub fn tap_text(&mut self, label: &str) -> bool {
            let Some((_, rect)) = self.texts().into_iter().find(|(text, _)| text == label) else {
                return false;
            };
            let at = Point::new(rect.x + rect.width / 2.0, rect.y + rect.height / 2.0);
            self.press(at);
            self.release(at);
            self.frame(1.0 / 60.0);
            true
        }

        /// The application, as the shell holds it.
        pub fn app(&self) -> &A {
            &self.shell.app
        }

        /// The widget with the keyboard focus, if one has it.
        pub fn focused(&self) -> Option<WidgetId> {
            self.shell.runtime.input.focused
        }

        /// The modifiers the shell holds as down: Ctrl, Shift, Alt and Meta.
        pub fn shell_modifiers(&self) -> (bool, bool, bool, bool) {
            (
                self.shell.ctrl,
                self.shell.shift,
                self.shell.alt,
                self.shell.meta,
            )
        }

        /// The widget the last frame would hand a press at `at`, if any.
        pub fn hit(&self, at: Point) -> Option<WidgetId> {
            self.shell.ui.as_ref().and_then(|ui| ui.hit(at))
        }

        /// Hands the application a message, as the shell does.
        pub fn update(&mut self, message: A::Message) {
            self.shell.dispatch(message);
        }

        /// Frames at sixty a second for `seconds`.
        pub fn run(&mut self, seconds: f32) {
            let n = (seconds * 60.0).round() as usize;
            for _ in 0..n.max(1) {
                self.frame(1.0 / 60.0);
            }
        }

        /// A finger down at `at`.
        pub fn press(&mut self, at: Point) {
            self.pointer(PointerKind::Down, at);
        }

        /// The finger moved to `at`.
        pub fn move_to(&mut self, at: Point) {
            self.pointer(PointerKind::Move, at);
        }

        /// The finger lifted at `at`.
        pub fn release(&mut self, at: Point) {
            self.pointer(PointerKind::Up, at);
        }

        /// The long-press deadline, delivered as the loop's wake delivers it. Whether it
        /// fired: a press that moved past the slop, or was never waiting, has none.
        pub fn hold_deadline(&mut self) -> bool {
            let fired = self.shell.press.poll(Instant::now() + LONG_PRESS_DELAY);
            if fired {
                self.shell.hold_deadline_reached();
            }
            fired
        }

        /// The double tap's wait, over: a first tap still waiting is sent as a tap. Whether one
        /// was waiting.
        pub fn tap_deadline(&mut self) -> bool {
            self.shell
                .poll_pending_tap(Instant::now() + DOUBLE_TAP_TIMEOUT)
        }

        /// The cursor the window would show where the pointer is now.
        pub fn cursor_shown(&self) -> frus_widgets::Cursor {
            let s = &self.shell;
            let requested = s.runtime.input.hovered.and_then(|id| {
                let rect = s.ui.as_ref()?.widget_rect(id)?;
                let widget = find_widget(s.tree.as_ref()?.as_ref(), id)?;
                widget.cursor_icon(
                    s.cursor.x - rect.x,
                    s.cursor.y - rect.y,
                    rect.width,
                    rect.height,
                )
            });
            s.region_cursor(requested)
        }

        /// When the loop would wake next if it went idle now, if it would.
        pub fn next_wake(&self) -> Option<Instant> {
            match self.shell.idle_control_flow() {
                ControlFlow::WaitUntil(at) => Some(at),
                _ => None,
            }
        }

        /// A click of the secondary mouse button at `at`.
        pub fn secondary_click(&mut self, at: Point) {
            self.pointer_of(PointerKind::Move, at, false);
            self.shell.context_click();
        }

        /// A mouse button down at `at` — a pointer that hovers, which is not a finger: nothing is
        /// left to scroll, and a press on words in a selection area begins a selection.
        pub fn press_mouse(&mut self, at: Point) {
            self.pointer_of(PointerKind::Down, at, false);
        }

        /// The mouse moved to `at`, its button down.
        pub fn move_mouse(&mut self, at: Point) {
            self.pointer_of(PointerKind::Move, at, false);
        }

        /// The mouse button lifted at `at`.
        pub fn release_mouse(&mut self, at: Point) {
            self.pointer_of(PointerKind::Up, at, false);
        }

        /// The words a selection area has selected, as Copy would put them on the clipboard.
        pub fn area_selection(&self) -> Option<String> {
            self.shell.region_text()
        }

        /// Select all, as the keyboard asks it of a selection area that holds a selection.
        pub fn area_select_all(&mut self) {
            self.shell.select_all_region();
        }

        /// Escape, as the keyboard delivers it.
        pub fn escape(&mut self) {
            self.shell.escape();
        }

        /// **A key pressed**, with the modifiers the stroke names held down for it, through
        /// the shell's own handling of a key (milestone 608): the arrows move the focus or a
        /// caret or answer the widget with the focus, Enter and Space activate, Escape
        /// closes, Tab moves on, a bound shortcut fires, a character is typed.
        ///
        /// The system's back key is not one of them: what it does last is quit, and a
        /// driver has no loop to quit.
        pub fn key(&mut self, stroke: frus_widgets::KeyStroke) {
            use frus_widgets::ShortcutKey as K;
            let named = |key| (WinitKey::Named(key), None);
            let (logical_key, text) = match stroke.key {
                K::Char(c) => {
                    let typed: winit::keyboard::SmolStr = c.to_string().into();
                    (WinitKey::Character(typed.clone()), Some(typed))
                }
                K::Enter => named(NamedKey::Enter),
                K::Escape => named(NamedKey::Escape),
                K::Tab => named(NamedKey::Tab),
                K::Space => (WinitKey::Named(NamedKey::Space), Some(" ".into())),
                K::Backspace => named(NamedKey::Backspace),
                K::Delete => named(NamedKey::Delete),
                K::Up => named(NamedKey::ArrowUp),
                K::Down => named(NamedKey::ArrowDown),
                K::Left => named(NamedKey::ArrowLeft),
                K::Right => named(NamedKey::ArrowRight),
                K::Home => named(NamedKey::Home),
                K::End => named(NamedKey::End),
                K::PageUp => named(NamedKey::PageUp),
                K::PageDown => named(NamedKey::PageDown),
                K::F(n) => named(match n {
                    1 => NamedKey::F1,
                    2 => NamedKey::F2,
                    3 => NamedKey::F3,
                    4 => NamedKey::F4,
                    5 => NamedKey::F5,
                    6 => NamedKey::F6,
                    7 => NamedKey::F7,
                    8 => NamedKey::F8,
                    9 => NamedKey::F9,
                    10 => NamedKey::F10,
                    11 => NamedKey::F11,
                    _ => NamedKey::F12,
                }),
            };
            // Where a letter is on a QWERTY keyboard: the clipboard's shortcuts are read off
            // the key's place, so that they work on any layout.
            const LETTERS: [KeyCode; 26] = [
                KeyCode::KeyA,
                KeyCode::KeyB,
                KeyCode::KeyC,
                KeyCode::KeyD,
                KeyCode::KeyE,
                KeyCode::KeyF,
                KeyCode::KeyG,
                KeyCode::KeyH,
                KeyCode::KeyI,
                KeyCode::KeyJ,
                KeyCode::KeyK,
                KeyCode::KeyL,
                KeyCode::KeyM,
                KeyCode::KeyN,
                KeyCode::KeyO,
                KeyCode::KeyP,
                KeyCode::KeyQ,
                KeyCode::KeyR,
                KeyCode::KeyS,
                KeyCode::KeyT,
                KeyCode::KeyU,
                KeyCode::KeyV,
                KeyCode::KeyW,
                KeyCode::KeyX,
                KeyCode::KeyY,
                KeyCode::KeyZ,
            ];
            let physical_key = match stroke.key {
                K::Char(c) if c.is_ascii_alphabetic() => {
                    PhysicalKey::Code(LETTERS[(c.to_ascii_lowercase() as u8 - b'a') as usize])
                }
                _ => PhysicalKey::Unidentified(winit::keyboard::NativeKeyCode::Unidentified),
            };
            let held = (
                self.shell.ctrl,
                self.shell.shift,
                self.shell.alt,
                self.shell.meta,
            );
            (
                self.shell.ctrl,
                self.shell.shift,
                self.shell.alt,
                self.shell.meta,
            ) = (stroke.ctrl, stroke.shift, stroke.alt, stroke.meta);
            self.shell.key_down(
                &KeyDown {
                    logical_key,
                    physical_key,
                    text,
                    repeat: false,
                },
                None,
            );
            (
                self.shell.ctrl,
                self.shell.shift,
                self.shell.alt,
                self.shell.meta,
            ) = held;
        }

        /// The two handles of a selection area's touch selection, on the surface, if it has them.
        pub fn area_handles(&self) -> Option<[frus_widgets::SelectionHandle; 2]> {
            self.shell.region_handles().map(|(_, handles)| handles)
        }

        fn pointer(&mut self, kind: PointerKind, at: Point) {
            self.pointer_of(kind, at, true);
        }

        fn pointer_of(&mut self, kind: PointerKind, at: Point, touch: bool) {
            self.shell.pointer_event(PointerEvent {
                kind,
                position: at,
                touch,
            });
        }

        /// One frame, the real frame's steps in the real frame's order, less the GPU.
        pub fn frame(&mut self, dt: f32) {
            let (width, height) = (self.size.width, self.size.height);
            let s = &mut self.shell;
            if let Some((now, _)) = s.gesture_clock.as_mut() {
                *now += dt;
            }
            if s.last_size != Some((width, height)) {
                s.last_size = Some((width, height));
                s.build_dirty = true;
                s.app.on_resize(width, height);
            }
            let mut app_animating = s.app.tick(dt);
            let settings = s
                .platform
                .accessibility
                .with_overrides(s.app.accessibility());
            let theme_moved = s.themes.advance(
                &s.app,
                s.platform.brightness,
                settings.high_contrast,
                settings.disable_animations,
                dt,
            );
            app_animating |= theme_moved | s.themes.animating();
            let theme = s.themes.displayed(&s.app);
            install_ambient(&s.app, &s.platform.locales);
            let _surface = s.media_query(width, height).install();
            s.runtime.still = settings.disable_animations;
            let was = std::mem::replace(&mut s.app_was_animating, app_animating);
            let asked = s.app.effects();
            s.run_command(asked);
            let arrived = s.take_task_arrivals();
            if frus_widgets::take_rebuild_request() || arrived {
                s.build_dirty = true;
            }
            s.report_focus();
            if frame_needs_build(
                s.build_dirty,
                app_animating,
                was,
                s.tree.is_none() || s.runtime.switching(),
            ) {
                s.tree = Some(build_view(&s.app, &theme, &s.runtime));
            }
            s.build_dirty = false;
            s.autoscroll_carried(dt);
            s.advance_reorder_springs(dt);
            let regions =
                s.ui.as_ref()
                    .map(|ui| ui.scroll_regions().to_vec())
                    .unwrap_or_default();
            s.runtime.sync_pages(&regions);
            s.runtime.sync_visible(&regions);
            s.runtime.advance(dt);
            s.runtime.advance_scroll(&regions, dt);
            let tree = s.tree.as_deref().expect("the view was built");
            // The widgets' own values, as the window's frame steps them: without it a value
            // a drag held would be held for ever here (milestone 638).
            s.runtime.advance_values(tree, dt);
            let ui = build_ui(tree, Size::new(width, height), &s.runtime, &theme);
            s.runtime.states.end_frame();
            let mut scene = ui.scene().clone();
            let ghost = if matches!(s.drag, Some(Drag::Reorder { moved: true, .. })) {
                s.paint_reorder_preview(&ui, &theme, &mut scene);
                // The ghost's outline is the last thing the preview draws, on the ghost's box.
                scene.primitives().last().map(|p| p.bounds())
            } else {
                None
            };
            let paged = ui.scroll_regions().to_vec();
            let scrolled: Vec<A::Message> = {
                let grain = |id| find_widget(tree, id).map_or(0.0, |w| w.scroll_grain());
                s.runtime
                    .scroll_changes(&paged, grain)
                    .into_iter()
                    .filter_map(|(id, position)| {
                        find_widget(tree, id).and_then(|w| w.on_scroll(position))
                    })
                    .collect()
            };
            s.ui = Some(ui);
            s.sync_regions(false);
            // As the shell does after every frame: focus that vanished goes back, and a
            // widget that takes the focus on appearing takes it (milestone 605).
            s.reconcile_focus();
            for message in scrolled {
                s.dispatch(message);
            }
            self.ghost = ghost;
        }
    }
}

/// **What is carried stays carried, however far its list scrolls** (milestone 527, seen on
/// a phone).
///
/// A label held on the Kanban screen's strip and carried towards the strip's right edge was
/// not drawn lifted, the strip scrolled away under it, and the release put it somewhere the
/// finger had never been. The carried row's box came from the frame, and the frame keeps a
/// reorderable's box only while it is on screen, clipped to what shows: once auto-scroll had
/// pushed the row against the edge the box stopped moving with the content while the press
/// kept moving, the ghost ran ahead of the finger, the scroll fed on it, and a row scrolled
/// out of sight had no box at all.
///
/// These drive the shell's own input path and its frame, on the screen's shape: a bar, a strip
/// of ten 96-px labels that lift on a hold, and a board of cards, each in a horizontal scroll.
#[cfg(test)]
mod carried_row_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{
        column, text, Axis, Button, CellFn, Container, Flex, Kanban, Point, Rect, ReorderAxis,
        ReorderGrab, ReorderableList, SingleChildScrollView, Theme, Widget,
    };

    /// A phone, in logical pixels.
    const W: f32 = 392.7;
    const H: f32 = 850.9;
    /// The height of the labels' middle, under the 56-px bar and the strip's 12 px of padding.
    const STRIP_Y: f32 = 88.0;
    /// How wide the strip's content is: ten labels, nine gaps, and 24 px at either end.
    const STRIP_CONTENT: f32 = 24.0 + 10.0 * 96.0 + 9.0 * 8.0 + 24.0;

    #[derive(Clone, Debug, PartialEq)]
    enum Board {
        Label(usize, usize),
        Card(usize, usize, usize, usize),
        Delete(usize, usize),
        Add(usize),
        Row(usize, usize),
    }

    /// The Kanban screen, in the shape that matters.
    struct BoardApp {
        labels: Vec<usize>,
        cards: Vec<Vec<String>>,
        log: Vec<Board>,
    }

    impl Default for BoardApp {
        fn default() -> Self {
            let cols: [&[&str]; 3] = [
                &["Design API", "Write spec", "Triage bugs"],
                &["Build widget"],
                &["Kickoff", "Research"],
            ];
            Self {
                labels: (0..10).collect(),
                cards: cols
                    .iter()
                    .map(|c| c.iter().map(|s| s.to_string()).collect())
                    .collect(),
                log: Vec::new(),
            }
        }
    }

    impl Application for BoardApp {
        type Message = Board;

        fn update(&mut self, message: Board) -> Command<Board> {
            self.log.push(message.clone());
            match message {
                Board::Label(from, to) => {
                    let label = self.labels.remove(from);
                    self.labels.insert(to, label);
                }
                Board::Card(from_col, from_pos, to_col, to_pos) => {
                    let card = self.cards[from_col].remove(from_pos);
                    let to_pos = to_pos.min(self.cards[to_col].len());
                    self.cards[to_col].insert(to_pos, card);
                }
                _ => {}
            }
            Command::none()
        }

        fn view(&self, theme: &Theme) -> Box<dyn Widget<Board>> {
            let mut strip = ReorderableList::new(Board::Label)
                .axis(ReorderAxis::Horizontal)
                .grab(ReorderGrab::LongPress)
                .gap(8.0);
            for &label in &self.labels {
                strip = strip.keyed_row(
                    label as u64,
                    Container::new()
                        .width(96.0)
                        .padding(12.0)
                        .color(theme.surface)
                        .child(text(format!("label {label}")).size(14.0)),
                );
            }
            let strip = SingleChildScrollView::new()
                .axis(Axis::Horizontal)
                .width(W)
                .child(
                    Container::new()
                        .padding_each(12.0, 24.0, 0.0, 24.0)
                        .child(strip),
                );
            let mut board = Kanban::new(Board::Card)
                .on_add(Board::Add)
                .scrollable_columns();
            for (col, title) in ["To do", "Doing", "Done"].iter().enumerate() {
                let cards: Vec<CellFn<Board>> = self.cards[col]
                    .iter()
                    .enumerate()
                    .map(|(pos, label)| {
                        let label = label.clone();
                        Box::new(move || {
                            Box::new(
                                Flex::row()
                                    .child(text(label.clone()).size(14.0))
                                    .child(Flex::row().flex(1.0))
                                    .child(Button::new("x").on_press(Board::Delete(col, pos))),
                            ) as Box<dyn Widget<Board>>
                        }) as CellFn<Board>
                    })
                    .collect();
                board = board.column_widgets(*title, cards);
            }
            let board = SingleChildScrollView::new()
                .axis(Axis::Horizontal)
                .width(W)
                .flex(1.0)
                .child(Container::new().padding(24.0).child(board));
            Box::new(
                Container::new().width(W).height(H).child(
                    column![
                        Container::<Board>::new().width(W).height(56.0),
                        strip,
                        board
                    ]
                    .flex(1.0),
                ),
            )
        }
    }

    /// Twenty 60-px rows that lift on a hold, in a list taller than the window.
    #[derive(Default)]
    struct ListApp {
        log: Vec<Board>,
    }

    impl Application for ListApp {
        type Message = Board;

        fn update(&mut self, message: Board) -> Command<Board> {
            self.log.push(message);
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Board>> {
            let mut list = ReorderableList::new(Board::Row)
                .grab(ReorderGrab::LongPress)
                .width(W);
            for row in 0..20u64 {
                list = list.keyed_row(
                    row,
                    Container::new()
                        .height(60.0)
                        .child(text(format!("row {row}")).size(14.0)),
                );
            }
            Box::new(
                SingleChildScrollView::new()
                    .axis(Axis::Vertical)
                    .width(W)
                    .height(H)
                    .child(list),
            )
        }
    }

    fn driver<A: Application>(app: A) -> Driver<A> {
        let mut driver = Driver::new(app, W, H);
        driver.run(0.2);
        driver
    }

    /// A finger held still at `at` until the long press has lifted what is under it.
    fn hold<A: Application>(driver: &mut Driver<A>, at: Point) {
        driver.press(at);
        driver.run(0.5);
        assert!(
            driver.hold_deadline(),
            "the hold lifts what is under {at:?}"
        );
        driver.run(0.05);
    }

    /// The finger through `points`, a tenth of a second apart, as the phone's were.
    fn carry<A: Application>(driver: &mut Driver<A>, points: impl IntoIterator<Item = Point>) {
        for at in points {
            driver.move_to(at);
            driver.run(0.1);
        }
    }

    /// Frame by frame for `seconds` with the finger still at `finger`: the carried box keeps
    /// the place it had under the finger — `offset` from it and `size` — and the region
    /// `region` keeps scrolling the way it started. Hands back that region's last offset.
    fn held_under_the_finger<A: Application>(
        driver: &mut Driver<A>,
        seconds: f32,
        finger: Point,
        offset: (f32, f32),
        size: (f32, f32),
        region: usize,
    ) -> (f32, f32) {
        let mut last = driver.offsets()[region].1;
        for frame in 0..(seconds * 60.0) as usize {
            driver.run(1.0 / 60.0);
            let now = driver.offsets()[region].1;
            let carried: Rect = driver.carried().unwrap_or_else(|| {
                panic!("frame {frame}: nothing is carried any more, the list at {now:?}")
            });
            assert!(
                (carried.x - finger.x - offset.0).abs() < 0.5
                    && (carried.y - finger.y - offset.1).abs() < 0.5
                    && (carried.width - size.0).abs() < 0.5
                    && (carried.height - size.1).abs() < 0.5,
                "frame {frame}: carried at {carried:?}, the finger at {finger:?}, the list at {now:?}"
            );
            assert!(
                now.0 >= last.0 - 0.01 && now.1 >= last.1 - 0.01,
                "frame {frame}: the list went back, {last:?} then {now:?}"
            );
            // And it is drawn there: the ghost the finger sees is the box being carried.
            let ghost = driver
                .ghost()
                .unwrap_or_else(|| panic!("frame {frame}: no ghost is drawn"));
            assert!(
                (ghost.x - carried.x).abs() < 1.0
                    && (ghost.y - carried.y).abs() < 1.0
                    && (ghost.width - carried.width).abs() < 2.0,
                "frame {frame}: the ghost is drawn at {ghost:?}, what is carried is at {carried:?}"
            );
            last = now;
        }
        last
    }

    /// **The reproduction.** A label held and carried past the strip's right edge stays under
    /// the finger for as long as it is held there, whole, while the strip scrolls on to its
    /// end; and the release drops it where the finger is, past the last label.
    #[test]
    fn a_label_carried_past_the_strips_edge_stays_under_the_finger() {
        let mut driver = driver(BoardApp::default());
        hold(&mut driver, Point::new(155.0, STRIP_Y));
        let lifted = driver.carried().expect("the label is carried");
        assert_eq!(
            lifted,
            Rect::new(128.0, 68.0, 96.0, 41.0),
            "Feature, lifted"
        );
        let finger = Point::new(370.0, STRIP_Y);
        carry(
            &mut driver,
            [200.0, 260.0, 320.0, finger.x].map(|x| Point::new(x, STRIP_Y)),
        );
        let strip = held_under_the_finger(
            &mut driver,
            1.5,
            finger,
            (lifted.x - 155.0, lifted.y - STRIP_Y),
            (96.0, 41.0),
            0,
        );
        assert!(
            (strip.0 - (STRIP_CONTENT - W)).abs() < 1.0,
            "the strip scrolled on to its end: {strip:?}"
        );
        driver.release(finger);
        driver.run(0.2);
        assert_eq!(
            driver.app().log,
            [Board::Label(1, 9)],
            "past the last label, it goes last; no card moves"
        );
    }

    /// **The phone's own gesture**, where the label never reaches an edge: held on Feature,
    /// carried along x as the injected moves went, let go over Design's right half.
    #[test]
    fn a_hold_on_a_label_then_a_carry_along_x_reorders_the_labels_and_moves_no_card() {
        let mut driver = driver(BoardApp::default());
        hold(&mut driver, Point::new(155.0, STRIP_Y));
        carry(
            &mut driver,
            [167.0, 189.0, 218.0, 247.0, 276.0, 306.0].map(|x| Point::new(x, STRIP_Y)),
        );
        driver.run(0.4);
        assert!(driver.carried().is_some(), "still carried");
        driver.release(Point::new(306.0, STRIP_Y));
        driver.run(0.2);
        assert_eq!(driver.app().log, [Board::Label(1, 2)]);
        assert_eq!(driver.app().labels[..4], [0, 2, 1, 3]);
        assert_eq!(
            driver.app().cards,
            BoardApp::default().cards,
            "no card moved"
        );
        assert_eq!(driver.offsets()[0].1, (0.0, 0.0), "nothing scrolled");
        assert_eq!(driver.offsets()[1].1, (0.0, 0.0), "the board neither");
    }

    /// **A card still crosses the board**: Design API, pressed and carried onto the upper
    /// half of Build widget, goes to the top of Doing; no label moves.
    #[test]
    fn a_card_carried_across_the_board_moves_the_card() {
        let mut driver = driver(BoardApp::default());
        driver.press(Point::new(100.0, 190.0));
        carry(
            &mut driver,
            [130.0, 180.0, 240.0, 300.0].map(|x| Point::new(x, 185.0)),
        );
        driver.release(Point::new(300.0, 185.0));
        driver.run(0.2);
        assert_eq!(driver.app().log, [Board::Card(0, 0, 1, 0)]);
        assert_eq!(driver.app().labels, (0..10).collect::<Vec<_>>());
    }

    /// **The board has the same edge.** A card carried to the board's right edge scrolls
    /// the board and stays under the finger, although the column it came from scrolls away.
    #[test]
    fn a_card_carried_to_the_boards_edge_stays_under_the_finger() {
        let mut driver = driver(BoardApp::default());
        let press = Point::new(100.0, 190.0);
        driver.press(press);
        let finger = Point::new(385.0, 190.0);
        carry(
            &mut driver,
            [130.0, 200.0, 280.0, 340.0, finger.x].map(|x| Point::new(x, 190.0)),
        );
        let card = driver.carried().expect("the card is carried");
        let board = held_under_the_finger(
            &mut driver,
            1.0,
            finger,
            (card.x - finger.x, card.y - finger.y),
            (card.width, card.height),
            1,
        );
        assert!(
            board.0 > 250.0,
            "the board scrolled past the column the card came from: {board:?}"
        );
    }

    /// **A list that runs down has the same edge**: row 0 held and carried to the bottom
    /// stays under the finger after its own place has scrolled off the top, and lands low in
    /// the list.
    #[test]
    fn a_row_carried_past_the_bottom_of_a_long_list_stays_under_the_finger() {
        let mut driver = driver(ListApp::default());
        hold(&mut driver, Point::new(100.0, 30.0));
        let lifted = driver.carried().expect("the row is carried");
        let finger = Point::new(100.0, 840.0);
        carry(
            &mut driver,
            [200.0, 400.0, 600.0, 800.0, finger.y].map(|y| Point::new(100.0, y)),
        );
        let list = held_under_the_finger(
            &mut driver,
            1.5,
            finger,
            (lifted.x - 100.0, lifted.y - 30.0),
            (lifted.width, lifted.height),
            0,
        );
        assert!(
            list.1 > 200.0,
            "the list scrolled past the row's own place: {list:?}"
        );
        driver.release(finger);
        driver.run(0.2);
        assert!(
            matches!(driver.app().log[..], [Board::Row(0, to)] if to > 15),
            "row 0 lands near the end: {:?}",
            driver.app().log
        );
    }
}

/// **A press a scroll took is let go of** (milestone 534).
///
/// The shell's own types need a window and an event loop, so these drive a real frame
/// through the pieces `App::pointer` is made of, in the order it calls them: the hover, the
/// press where the pointer lands, the gesture the drag handler turns the press into, and
/// `settle_press` after every event. What is painted is then compared with a runtime
/// nobody pressed.
#[cfg(test)]
mod press_tests {
    use super::{gesture_was_a_tap, press_at, settle_press, Drag, Point, Runtime, Theme};
    use crate::gesture::PointerKind;
    use crate::hover::Hover;
    use frus_widgets::{
        build_ui, Axis, Button, Container, Flex, Primitive, SegmentedButton, SingleChildScrollView,
        Size, Ui, Widget,
    };

    const SCREEN: Size = Size::new(300.0, 400.0);
    const DT: f32 = 1.0 / 60.0;

    /// The phone's screen: a strip of segments too wide for it, in a horizontal scroll.
    fn filters() -> Box<dyn Widget<usize>> {
        let mut segments = SegmentedButton::new(0, |i| i);
        for label in ["All", "Active", "Done", "Archived", "Starred", "Shared"] {
            segments = segments.segment(label);
        }
        Box::new(
            Flex::column().width(300.0).height(400.0).child(
                SingleChildScrollView::new()
                    .axis(Axis::Horizontal)
                    .width(300.0)
                    .height(80.0)
                    .child(segments),
            ),
        )
    }

    /// A plain button at the top of a page that scrolls down.
    fn page() -> Box<dyn Widget<usize>> {
        Box::new(
            Flex::column().width(300.0).height(400.0).child(
                SingleChildScrollView::new()
                    .width(300.0)
                    .height(400.0)
                    .child(
                        Flex::column()
                            .child(Button::new("Go").on_press(7usize))
                            .child(Container::new().width(300.0).height(1200.0)),
                    ),
            ),
        )
    }

    fn frame(view: &dyn Widget<usize>, runtime: &Runtime) -> Ui<usize> {
        build_ui(view, SCREEN, runtime, &Theme::default())
    }

    /// Frames go by with nothing else happening, as a phone left alone for `seconds`.
    fn idle(runtime: &mut Runtime, seconds: f32) {
        for _ in 0..(seconds / DT) as usize {
            runtime.advance(DT);
            runtime.advance_ink(DT);
        }
    }

    /// What the screen shows.
    fn painted(view: &dyn Widget<usize>, runtime: &Runtime) -> Vec<Primitive> {
        frame(view, runtime).scene().primitives().to_vec()
    }

    /// The same screen, scrolled the same, that no pointer has touched.
    fn untouched(view: &dyn Widget<usize>, runtime: &Runtime) -> Vec<Primitive> {
        let mut quiet = Runtime::default();
        quiet.scroll.clone_from(&runtime.scroll);
        quiet.scroll_target.clone_from(&runtime.scroll_target);
        idle(&mut quiet, 0.5);
        painted(view, &quiet)
    }

    /// A pointer on a screen, routed as the shell routes one.
    struct Pointer<'a> {
        view: &'a dyn Widget<usize>,
        runtime: Runtime,
        hover: Hover,
        drag: Option<Drag>,
        touch: bool,
        at: Point,
    }

    impl<'a> Pointer<'a> {
        fn new(view: &'a dyn Widget<usize>, touch: bool) -> Self {
            Self {
                view,
                runtime: Runtime::default(),
                hover: Hover::default(),
                drag: None,
                touch,
                at: Point::new(0.0, 0.0),
            }
        }

        /// One event: `route` stands for what the shell's handler makes of it.
        fn event(&mut self, kind: PointerKind, at: Point, route: impl FnOnce(&mut Self)) {
            self.at = at;
            self.hover.event(kind, at, self.touch);
            let could_tap = gesture_was_a_tap(self.drag.as_ref());
            if kind == PointerKind::Down {
                let ui = frame(self.view, &self.runtime);
                self.runtime.input.hovered = self.hover.target(&ui);
                press_at(&mut self.runtime, Some(&ui), at);
            }
            route(self);
            settle_press(
                &mut self.runtime.input,
                kind,
                could_tap,
                self.drag.as_ref(),
                self.touch,
            );
            if matches!(kind, PointerKind::Up | PointerKind::Cancel) {
                let ui = frame(self.view, &self.runtime);
                self.runtime.input.hovered = self.hover.target(&ui);
            }
        }

        /// A finger lands where a touch scroll takes it, as `pointer_down` prepares one.
        fn land(&mut self, at: Point) {
            self.event(PointerKind::Down, at, |p| {
                if !p.touch {
                    return;
                }
                let ui = frame(p.view, &p.runtime);
                let area = ui
                    .scroll_chain(at)
                    .find(|area| area.accepts_user_offset((0.0, 0.0)))
                    .expect("the region under the finger has somewhere to go");
                p.drag = Some(Drag::Scroll {
                    id: area.id,
                    last: at,
                    moved: false,
                    carried: (0.0, 0.0),
                    dismiss: None,
                    axis: None,
                    pan: None,
                });
            });
        }

        /// The pointer moves by `by`; past the slop a touch scroll moves its content, as the
        /// drag handler moves it.
        fn slide(&mut self, by: (f32, f32)) {
            let to = Point::new(self.at.x + by.0, self.at.y + by.1);
            self.event(PointerKind::Move, to, |p| {
                let Some(Drag::Scroll {
                    id,
                    moved,
                    axis,
                    last,
                    ..
                }) = p.drag.as_mut()
                else {
                    return;
                };
                let (dx, dy) = (to.x - last.x, to.y - last.y);
                if dx.hypot(dy) <= super::TOUCH_SLOP && !*moved {
                    return;
                }
                *moved = true;
                *axis = Some(dy.abs() >= dx.abs());
                *last = to;
                let offset = p.runtime.scroll.get(id).copied().unwrap_or((0.0, 0.0));
                let moved_to = (offset.0 - by.0, offset.1 - by.1);
                p.runtime.scroll.insert(*id, moved_to);
                p.runtime.scroll_target.insert(*id, moved_to);
            });
        }

        /// The pointer lifts; the release takes the gesture, as `pointer_up` does.
        fn lift(&mut self) -> Option<Drag> {
            let mut ended = None;
            self.event(PointerKind::Up, self.at, |p| ended = p.drag.take());
            ended
        }
    }

    /// **Seen on a phone**: a swipe that started on "Done" scrolled the strip, selected
    /// nothing — and left "Done" grey, still there two seconds later. Afterwards the screen
    /// is the one nobody touched.
    #[test]
    fn a_segment_a_swipe_started_on_is_not_left_pressed() {
        let view = filters();
        let mut finger = Pointer::new(view.as_ref(), true);
        let done = Point::new(200.0, 16.0);
        finger.land(done);
        let segment = finger
            .runtime
            .input
            .pressed
            .expect("the segment is pressed");
        assert!(
            finger.runtime.ink.contains_key(&segment),
            "and it splashed: a segment takes ink"
        );
        assert!(
            frame(view.as_ref(), &finger.runtime)
                .scroll_chain(done)
                .any(|area| area.max_x > 0.0),
            "the strip is wider than the screen, as the phone's was"
        );
        for _ in 0..19 {
            finger.slide((-10.0, 0.0));
        }
        let ended = finger.lift();
        assert!(
            !gesture_was_a_tap(ended.as_ref()),
            "a gesture that scrolled clicks nothing"
        );
        idle(&mut finger.runtime, 2.0);
        // What the phone showed first, then why.
        let (shown, quiet) = (
            painted(view.as_ref(), &finger.runtime),
            untouched(view.as_ref(), &finger.runtime),
        );
        assert_eq!(
            shown.len(),
            quiet.len(),
            "two seconds on, the screen paints what nobody touched, and no layer more"
        );
        assert_eq!(shown, quiet, "nothing is highlighted");
        assert!(
            finger.runtime.ink.is_empty(),
            "no ink waits for a finger that has gone"
        );
        assert_eq!(finger.runtime.input.pressed, None, "the press went with it");
        assert_eq!(
            finger.runtime.input.hovered, None,
            "and a lifted finger hovers nothing"
        );
    }

    /// The reference cancels the press **when the scroll wins**, not when the finger lifts:
    /// a strip being scrolled does not carry a pressed segment along with it.
    #[test]
    fn the_press_ends_when_the_scroll_takes_it() {
        let view = filters();
        let mut finger = Pointer::new(view.as_ref(), true);
        finger.land(Point::new(200.0, 16.0));
        finger.slide((-4.0, 0.0));
        assert!(
            finger.runtime.input.pressed.is_some(),
            "under the slop it may still be a tap"
        );
        finger.slide((-40.0, 0.0));
        assert_eq!(
            finger.runtime.input.pressed, None,
            "past it, the scroll has it"
        );
        assert_eq!(
            finger.runtime.input.hovered, None,
            "and the finger's hover with it"
        );
        idle(&mut finger.runtime, 0.5);
        assert_eq!(
            painted(view.as_ref(), &finger.runtime),
            untouched(view.as_ref(), &finger.runtime),
            "the finger is still down, and nothing under it is highlighted"
        );
    }

    /// The same down a page: a plain button a scroll started on.
    #[test]
    fn a_button_a_page_scrolled_from_is_not_left_pressed() {
        let view = page();
        let mut finger = Pointer::new(view.as_ref(), true);
        let go = Point::new(20.0, 15.0);
        finger.land(go);
        let button = finger.runtime.input.pressed.expect("the button is pressed");
        assert_eq!(
            frame(view.as_ref(), &finger.runtime).msg_for(button),
            Some(7),
            "the press is on the button"
        );
        for _ in 0..10 {
            finger.slide((0.0, -30.0));
        }
        assert!(!gesture_was_a_tap(finger.lift().as_ref()));
        idle(&mut finger.runtime, 2.0);
        assert_eq!(finger.runtime.input.pressed, None);
        assert!(finger.runtime.ink.is_empty());
        assert_eq!(
            painted(view.as_ref(), &finger.runtime),
            untouched(view.as_ref(), &finger.runtime),
        );
    }

    /// **A tap is still a tap**: a finger that stays inside the slop keeps its press to the
    /// release, which is what clicks; only then is it let go of.
    #[test]
    fn a_tap_still_presses_and_clicks() {
        let view = filters();
        let mut finger = Pointer::new(view.as_ref(), true);
        let segment = Point::new(200.0, 16.0);
        finger.land(segment);
        finger.slide((3.0, 2.0));
        let pressed = finger.runtime.input.pressed;
        assert!(pressed.is_some(), "a wobble under the slop takes nothing");
        assert_eq!(finger.runtime.input.hovered, pressed, "and the press shows");
        // What `pointer_up` reads, before the release lets it go.
        let ui = frame(view.as_ref(), &finger.runtime);
        assert_eq!(
            ui.hit(segment),
            pressed,
            "released on the widget it pressed"
        );
        assert!(
            pressed.and_then(|id| ui.msg_for(id)).is_some(),
            "and the segment it pressed has a choice to make"
        );
        let ended = finger.lift();
        assert!(
            gesture_was_a_tap(ended.as_ref()),
            "a scroll that never moved"
        );
        assert_eq!(
            finger.runtime.input.pressed, None,
            "let go of once released"
        );
    }

    /// **A mouse is as it was**: it has no touch scroll, keeps its press while it moves, and
    /// still hovers where it is after its button comes up.
    #[test]
    fn a_mouse_keeps_its_press_while_it_moves_and_its_hover_after() {
        let view = filters();
        let mut mouse = Pointer::new(view.as_ref(), false);
        let done = Point::new(200.0, 16.0);
        mouse.land(done);
        assert!(mouse.drag.is_none(), "a mouse does not drag a scroll");
        let pressed = mouse.runtime.input.pressed.expect("pressed");
        mouse.slide((-60.0, 0.0));
        assert_eq!(mouse.runtime.input.pressed, Some(pressed), "still held");
        mouse.lift();
        assert_eq!(mouse.runtime.input.pressed, None);
        assert!(
            mouse.runtime.input.hovered.is_some(),
            "a released mouse is still over the strip"
        );
    }

    /// A gesture a **mouse** moves past its slop takes the press as a finger's does — but
    /// not the hover, since the mouse is still there.
    #[test]
    fn a_gesture_takes_a_mouse_s_press_and_leaves_its_hover() {
        let id = frus_widgets::WidgetId::from_u64(3);
        let sheet = |moved| Drag::Sheet {
            id: frus_widgets::WidgetId::from_u64(9),
            last: Point::new(0.0, 0.0),
            moved,
            available: 800.0,
        };
        for touch in [false, true] {
            let mut input = frus_widgets::InputState {
                pressed: Some(id),
                hovered: Some(id),
                ..Default::default()
            };
            assert!(!settle_press(
                &mut input,
                PointerKind::Move,
                true,
                Some(&sheet(false)),
                touch
            ));
            assert_eq!(input.pressed, Some(id), "not yet past the slop");
            assert!(settle_press(
                &mut input,
                PointerKind::Move,
                true,
                Some(&sheet(true)),
                touch
            ));
            assert_eq!(input.pressed, None, "touch {touch}");
            assert_eq!(input.hovered, (!touch).then_some(id), "touch {touch}");
        }
        // A gesture that was never a tap — a slider, a selection — had no press to share,
        // and moving it lets go of nothing.
        let mut input = frus_widgets::InputState {
            pressed: Some(id),
            ..Default::default()
        };
        let select = Drag::TextSelect {
            id,
            rect: super::Rect::new(0.0, 0.0, 10.0, 10.0),
        };
        assert!(!settle_press(
            &mut input,
            PointerKind::Move,
            false,
            Some(&select),
            true
        ));
        assert_eq!(input.pressed, Some(id));
    }
}

/// The mouse, the words and the selection a [`SelectionArea`](frus_widgets::SelectionArea) holds,
/// driven through the shell as a person drives it.
#[cfg(test)]
mod selection_area_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{Button, Container, Flex, Point, SelectionArea, Text, Theme, Widget};

    const W: f32 = 400.0;
    const H: f32 = 300.0;

    /// A line outside the area, then an area of three lines with a button between two of them.
    #[derive(Default)]
    struct Doc {
        /// What the application says about the area's bar.
        bar: Bar,
        /// How many times the bar's own item was pressed.
        shared: std::rc::Rc<std::cell::Cell<u32>>,
        /// The theme's platform: Android unless a test says otherwise, because these are a
        /// finger's tests and Android's bar is the pill (milestone 618).
        platform: Option<frus_widgets::TargetPlatform>,
    }

    /// The application's say over the area's bar (milestone 578).
    #[derive(Default, Clone, Copy)]
    enum Bar {
        /// Nothing: Copy and Select all.
        #[default]
        Default,
        /// Its own item, Share, after Copy, and no Select all.
        Share,
        /// No bar at all.
        Empty,
    }

    impl Application for Doc {
        type Message = ();

        fn update(&mut self, _message: ()) -> Command<()> {
            self.shared.set(self.shared.get() + 1);
            Command::none()
        }

        fn theme(&self) -> Theme {
            Theme::default().with_platform(
                self.platform
                    .unwrap_or(frus_widgets::TargetPlatform::Android),
            )
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<()>> {
            let area = SelectionArea::around(
                Flex::column()
                    .child(Text::new("first line of words").no_wrap())
                    .child(Text::new("second line").no_wrap())
                    .child(Button::new("Press").on_press(()))
                    .child(Text::new("third line ends here").no_wrap()),
            );
            let area = match self.bar {
                Bar::Default => area,
                Bar::Share => area.selection_toolbar(|_, items| {
                    let mut items: Vec<_> = items
                        .into_iter()
                        .filter(|item| item.label() == "Copy")
                        .collect();
                    items.push(frus_widgets::ToolbarItem::custom("Share", ()));
                    items
                }),
                Bar::Empty => area.selection_toolbar(|_, _| Vec::new()),
            };
            Box::new(
                Container::new().width(W).height(H).child(
                    Flex::column()
                        .child(Text::new("Outside the area").no_wrap())
                        .child(area),
                ),
            )
        }
    }

    /// A row that answers a tap, with words in it, beside words that answer nothing.
    struct Tappable;

    impl Application for Tappable {
        type Message = ();

        fn update(&mut self, _message: ()) -> Command<()> {
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<()>> {
            Box::new(
                Container::new()
                    .width(W)
                    .height(H)
                    .child(SelectionArea::around(
                        Flex::column()
                            .child(
                                Container::new()
                                    .on_click(())
                                    .child(Text::new("tap this row").no_wrap()),
                            )
                            .child(Text::new("plain words here").no_wrap()),
                    )),
            )
        }
    }

    /// **What answers a tap keeps it, even when it is not a focus stop**: words inside a row that
    /// takes a tap begin no selection, and words beside it do. (A button is a focus stop and is
    /// kept by that; a row that is only clickable is kept by nothing but this.)
    #[test]
    fn a_row_that_takes_a_tap_keeps_its_press() {
        let mut d = Driver::new(Tappable, W, H);
        d.run(0.2);
        let find = |d: &Driver<Tappable>, label: &str| {
            let (_, rect) = d
                .texts()
                .into_iter()
                .find(|(text, _)| text == label)
                .expect("on screen");
            Point::new(rect.x + 20.0, rect.y + 8.0)
        };
        let (tap, plain) = (find(&d, "tap this row"), find(&d, "plain words here"));
        let end = Point::new(plain.x + 60.0, plain.y);
        d.press_mouse(tap);
        d.run(0.05);
        d.move_mouse(end);
        d.run(0.05);
        d.release_mouse(end);
        d.run(0.05);
        assert_eq!(d.area_selection(), None, "the row's press stayed the row's");

        d.press_mouse(plain);
        d.run(0.05);
        d.move_mouse(end);
        d.run(0.05);
        d.release_mouse(end);
        d.run(0.05);
        assert!(d.area_selection().is_some(), "plain words still select");
    }

    fn driver() -> Driver<Doc> {
        driver_with(Bar::Default)
    }

    fn driver_with(bar: Bar) -> Driver<Doc> {
        driver_on(bar, None)
    }

    fn driver_on(bar: Bar, platform: Option<frus_widgets::TargetPlatform>) -> Driver<Doc> {
        let doc = Doc {
            bar,
            platform,
            ..Doc::default()
        };
        let mut driver = Driver::new(doc, W, H);
        driver.run(0.2);
        driver
    }

    /// Where the word `label` starts, and a point on its line a fraction `across` of the way
    /// along it.
    fn on(driver: &Driver<Doc>, label: &str, across: f32) -> Point {
        let (_, rect) = driver
            .texts()
            .into_iter()
            .find(|(text, _)| text == label)
            .unwrap_or_else(|| panic!("{label:?} is on screen"));
        // A text primitive is a point at its top-left; the line is about 19 px tall and the
        // words a few px per character.
        Point::new(rect.x + across, rect.y + 8.0)
    }

    fn drag(driver: &mut Driver<Doc>, from: Point, to: Point) {
        driver.press_mouse(from);
        driver.run(0.05);
        driver.move_mouse(to);
        driver.run(0.05);
        driver.release_mouse(to);
        driver.run(0.05);
    }

    /// **A drag across texts selects across them**: the tail of the first, the whole of the one
    /// between, the head of the last — and what the button between them says is not among the
    /// words, because it is not a text of the area's.
    #[test]
    fn a_drag_selects_across_the_texts_of_an_area() {
        let mut d = driver();
        let (from, to) = (
            on(&d, "first line of words", 60.0),
            on(&d, "third line ends here", 40.0),
        );
        drag(&mut d, from, to);
        let copied = d.area_selection().expect("something is selected");
        let lines: Vec<&str> = copied.lines().collect();
        assert_eq!(lines.len(), 3, "one line per text: {copied:?}");
        assert!(
            !lines[0].is_empty() && "first line of words".ends_with(lines[0]),
            "the tail of the first: {:?}",
            lines[0]
        );
        assert!(lines[0].len() < "first line of words".len());
        assert_eq!(lines[1], "second line", "the whole of the middle one");
        assert!(
            !lines[2].is_empty() && "third line ends here".starts_with(lines[2]),
            "the head of the last: {:?}",
            lines[2]
        );
        assert!(lines[2].len() < "third line ends here".len());
        assert!(!copied.contains("Press"), "a button's label is not text");
    }

    /// **Dragged upward it is the same words.**
    #[test]
    fn dragging_upward_selects_the_same_words() {
        let (down, up) = {
            let mut d = driver();
            let (a, b) = (
                on(&d, "first line of words", 60.0),
                on(&d, "third line ends here", 40.0),
            );
            drag(&mut d, a, b);
            let down = d.area_selection();
            drag(&mut d, b, a);
            (down, d.area_selection())
        };
        assert!(down.is_some());
        assert_eq!(down, up);
    }

    /// **A drag that leaves the words still has an end**: past the right edge of the last line,
    /// the selection ends with it, and below everything it ends at the last text.
    #[test]
    fn a_drag_past_the_words_ends_at_the_last_of_them() {
        let mut d = driver();
        let from = on(&d, "second line", 5.0);
        drag(&mut d, from, Point::new(W - 2.0, H - 2.0));
        let copied = d.area_selection().expect("a selection");
        assert!(copied.ends_with("third line ends here"), "{copied:?}");
    }

    /// **Words outside the area are not part of it**: a drag over them selects nothing, and
    /// one that starts inside never picks them up.
    #[test]
    fn words_outside_the_area_are_left_alone() {
        let mut d = driver();
        let outside = on(&d, "Outside the area", 30.0);
        let end = on(&d, "third line ends here", 40.0);
        drag(&mut d, outside, end);
        assert_eq!(d.area_selection(), None, "the press began outside");

        let inside = on(&d, "first line of words", 30.0);
        drag(&mut d, inside, Point::new(20.0, 2.0));
        let copied = d.area_selection().expect("a selection");
        assert!(!copied.contains("Outside"), "{copied:?}");
    }

    /// **A press on a button is the button's**: no selection begins under it.
    #[test]
    fn a_button_keeps_its_press() {
        let mut d = driver();
        let button = on(&d, "Press", 10.0);
        let end = on(&d, "third line ends here", 40.0);
        drag(&mut d, button, end);
        assert_eq!(d.area_selection(), None);
    }

    /// **A press without a drag puts the selection away**, in the area or out of it.
    #[test]
    fn a_click_puts_the_selection_away() {
        let mut d = driver();
        let (from, to) = (
            on(&d, "first line of words", 60.0),
            on(&d, "third line ends here", 40.0),
        );
        drag(&mut d, from, to);
        assert!(d.area_selection().is_some());
        let elsewhere = on(&d, "second line", 30.0);
        drag(&mut d, elsewhere, elsewhere);
        assert_eq!(d.area_selection(), None, "a click in the area");

        drag(&mut d, from, to);
        assert!(d.area_selection().is_some());
        let outside = on(&d, "Outside the area", 30.0);
        drag(&mut d, outside, outside);
        assert_eq!(d.area_selection(), None, "a click outside it");
    }

    /// **A double click selects the word.**
    #[test]
    fn a_double_click_selects_the_word() {
        let mut d = driver();
        // "second" is the first word of the line: a few px in.
        let at = on(&d, "second line", 12.0);
        d.press_mouse(at);
        d.release_mouse(at);
        d.run(0.05);
        d.press_mouse(at);
        d.release_mouse(at);
        d.run(0.05);
        assert_eq!(d.area_selection().as_deref(), Some("second"));
    }

    /// **Select all takes every text of the area** — and none of what is outside it.
    #[test]
    fn select_all_takes_the_whole_area() {
        let mut d = driver();
        let at = on(&d, "second line", 12.0);
        let end = on(&d, "second line", 40.0);
        drag(&mut d, at, end);
        assert!(d.area_selection().is_some());
        d.area_select_all();
        assert_eq!(
            d.area_selection().as_deref(),
            Some("first line of words\nsecond line\nthird line ends here")
        );
    }

    /// **A finger scrolls, and does not select**: a touch drag over the words leaves them be.
    #[test]
    fn a_finger_does_not_select() {
        let mut d = driver();
        let (from, to) = (
            on(&d, "first line of words", 60.0),
            on(&d, "third line ends here", 40.0),
        );
        d.press(from);
        d.run(0.05);
        d.move_to(to);
        d.run(0.05);
        d.release(to);
        d.run(0.05);
        assert_eq!(d.area_selection(), None);
    }

    /// A finger held still on `at` until the long press fires, then lifted.
    fn hold(d: &mut Driver<Doc>, at: Point) -> bool {
        d.press(at);
        d.run(0.1);
        let fired = d.hold_deadline();
        d.run(0.05);
        d.release(at);
        d.run(0.05);
        fired
    }

    /// Where the bar's button reading `label` is, if the bar shows one.
    fn bar_button(d: &Driver<Doc>, label: &str) -> Option<Point> {
        let (ui, _) = d.frame_parts()?;
        d.texts()
            .into_iter()
            .filter(|(text, _)| text == label)
            .map(|(_, rect)| Point::new(rect.x + 4.0, rect.y + 6.0))
            .find(|at| ui.toolbar_contains(*at))
    }

    /// **A finger held on words selects the word under it and opens the bar** — Copy and
    /// Select all — over it (milestone 576). A phone has no mouse to drag with.
    #[test]
    fn a_hold_selects_the_word_and_opens_the_bar() {
        let mut d = driver();
        let at = on(&d, "second line", 12.0);
        assert!(hold(&mut d, at), "the hold fired");
        assert_eq!(d.area_selection().as_deref(), Some("second"));
        assert!(bar_button(&d, "Copy").is_some(), "Copy is on the bar");
        assert!(bar_button(&d, "Select all").is_some(), "and Select all");
    }

    /// **On a desktop theme the bar is the menu, and its rows act on the area as the pill's
    /// buttons do** (milestone 618).
    #[test]
    fn the_desktop_menus_rows_act_on_the_area() {
        let mut d = driver_on(Bar::Default, Some(frus_widgets::TargetPlatform::Linux));
        let at = on(&d, "second line", 12.0);
        hold(&mut d, at);
        let select_all = bar_button(&d, "Select all").expect("Select all");
        // The menu hangs from the selection's top, over the handles under it: the press is
        // the menu's, not a handle's.
        d.press(select_all);
        d.release(select_all);
        d.run(0.05);
        assert_eq!(
            d.area_selection().as_deref(),
            Some("first line of words\nsecond line\nthird line ends here")
        );
    }

    /// **The bar's Select all takes the whole area and keeps the bar**, which no longer offers
    /// Select all; its Copy puts the selection away, as a platform's own does.
    #[test]
    fn the_bars_buttons_act_on_the_area() {
        let mut d = driver();
        let at = on(&d, "second line", 12.0);
        hold(&mut d, at);
        let select_all = bar_button(&d, "Select all").expect("Select all");
        d.press(select_all);
        d.release(select_all);
        d.run(0.05);
        assert_eq!(
            d.area_selection().as_deref(),
            Some("first line of words\nsecond line\nthird line ends here")
        );
        assert!(
            bar_button(&d, "Select all").is_none(),
            "nothing left to select"
        );
        let copy = bar_button(&d, "Copy").expect("Copy stays");
        d.press(copy);
        d.release(copy);
        d.run(0.05);
        assert_eq!(d.area_selection(), None, "copied, and put away");
        assert!(bar_button(&d, "Copy").is_none(), "the bar with it");
    }

    /// **A hold on a button is the button's**, and a finger that moves is a scroll, not a hold.
    #[test]
    fn a_hold_on_a_button_selects_nothing() {
        let mut d = driver();
        let button = on(&d, "Press", 10.0);
        hold(&mut d, button);
        assert_eq!(d.area_selection(), None);
    }

    /// **Escape, and a tap elsewhere, put the selection and its bar away.**
    #[test]
    fn escape_and_a_tap_put_the_bar_away() {
        let mut d = driver();
        let at = on(&d, "second line", 12.0);
        hold(&mut d, at);
        assert!(d.area_selection().is_some());
        d.escape();
        d.run(0.05);
        assert_eq!(d.area_selection(), None);
        assert!(bar_button(&d, "Copy").is_none());

        hold(&mut d, at);
        assert!(d.area_selection().is_some());
        let elsewhere = on(&d, "Outside the area", 20.0);
        d.press(elsewhere);
        d.release(elsewhere);
        d.run(0.05);
        assert_eq!(d.area_selection(), None);
        assert!(bar_button(&d, "Copy").is_none());
    }

    /// **A selection made with a mouse has no bar**: the bar is for a finger, which has no
    /// Ctrl+C.
    #[test]
    fn a_mouse_selection_has_no_bar() {
        let mut d = driver();
        let (from, to) = (
            on(&d, "first line of words", 60.0),
            on(&d, "third line ends here", 40.0),
        );
        drag(&mut d, from, to);
        assert!(d.area_selection().is_some());
        assert!(bar_button(&d, "Copy").is_none());
    }

    /// **The application says what the bar holds** (milestone 578): its own item beside Copy,
    /// and no Select all — and pressing its item sends the application's message.
    #[test]
    fn the_application_says_what_the_bar_holds() {
        let mut d = driver_with(Bar::Share);
        let at = on(&d, "second line", 12.0);
        assert!(hold(&mut d, at));
        assert_eq!(d.area_selection().as_deref(), Some("second"));
        assert!(bar_button(&d, "Copy").is_some(), "Copy was kept");
        assert!(
            bar_button(&d, "Select all").is_none(),
            "Select all was taken off"
        );
        let share = bar_button(&d, "Share").expect("the application's own item");
        let shared = d.app().shared.clone();
        d.press(share);
        d.release(share);
        d.run(0.05);
        assert_eq!(shared.get(), 1, "its message was sent");
    }

    /// **An empty list shows no bar**, and the selection is still made.
    #[test]
    fn an_empty_list_shows_no_bar() {
        let mut d = driver_with(Bar::Empty);
        let at = on(&d, "second line", 12.0);
        assert!(hold(&mut d, at));
        assert_eq!(d.area_selection().as_deref(), Some("second"));
        assert!(bar_button(&d, "Copy").is_none());
        assert!(d
            .frame_parts()
            .is_some_and(|(ui, _)| !ui.toolbar_contains(at)));
    }

    /// A handle's middle — where a finger takes it.
    fn middle(rect: frus_widgets::Rect) -> Point {
        Point::new(rect.x + rect.width / 2.0, rect.y + rect.height / 2.0)
    }

    /// A finger taking a handle at `from` and carrying it to `to`, a few steps at a time.
    fn carry_handle(d: &mut Driver<Doc>, from: Point, to: Point) {
        d.press(from);
        d.run(0.05);
        for step in 1..=4 {
            let f = step as f32 / 4.0;
            d.move_to(Point::new(
                from.x + (to.x - from.x) * f,
                from.y + (to.y - from.y) * f,
            ));
            d.run(0.05);
        }
        d.release(to);
        d.run(0.05);
    }

    /// **A touch selection has two handles**, hanging below the ends of the word, the start one
    /// to the left of the end one — and a mouse selection has none.
    #[test]
    fn a_touch_selection_has_handles_and_a_mouse_one_does_not() {
        let mut d = driver();
        let paths = |d: &Driver<Doc>| {
            let (ui, _) = d.frame_parts().expect("a frame");
            ui.scene()
                .primitives()
                .iter()
                .filter(|p| matches!(p, frus_widgets::Primitive::Path { .. }))
                .count()
        };
        let before = paths(&d);
        let at = on(&d, "second line", 12.0);
        hold(&mut d, at);
        assert_eq!(paths(&d), before + 2, "the two handles are painted");
        let [start, end] = d.area_handles().expect("two handles");
        assert!(start.line_center.x < end.line_center.x, "{start:?} {end:?}");
        assert!(start.rect.y > at.y - 8.0, "they hang below the line");

        let (from, to) = (
            on(&d, "first line of words", 60.0),
            on(&d, "third line ends here", 40.0),
        );
        drag(&mut d, from, to);
        assert!(d.area_selection().is_some());
        assert!(
            d.area_handles().is_none(),
            "a mouse selection has no handles"
        );
        d.area_select_all();
        assert!(
            d.area_handles().is_none(),
            "nor does it grow any when the keyboard selects all"
        );
    }

    /// **The end handle carries the end of the selection to the next text**: dragged down to the
    /// third line, the selection runs from the word to it. The bar is put away while the handle
    /// moves, and back when it is let go.
    #[test]
    fn the_end_handle_widens_the_selection_across_texts() {
        let mut d = driver();
        let at = on(&d, "second line", 12.0);
        hold(&mut d, at);
        let [_, end] = d.area_handles().expect("handles");
        let third = on(&d, "third line ends here", 60.0);
        let from = middle(end.rect);
        // The handle hangs below its line: carried to where its line would meet the third.
        let to = Point::new(third.x, from.y + (third.y - at.y));
        d.press(from);
        d.run(0.05);
        d.move_to(Point::new(from.x, (from.y + to.y) / 2.0));
        d.run(0.05);
        d.move_to(to);
        d.run(0.05);
        assert!(
            bar_button(&d, "Copy").is_none(),
            "no bar while a handle moves"
        );
        d.release(to);
        d.run(0.05);
        let copied = d.area_selection().expect("a selection");
        let lines: Vec<&str> = copied.lines().collect();
        assert_eq!(lines.len(), 2, "{copied:?}");
        assert_eq!(lines[0], "second line", "the rest of the word's line");
        assert!("third line ends here".starts_with(lines[1]), "{copied:?}");
        assert!(!lines[1].is_empty());
        assert!(bar_button(&d, "Copy").is_some(), "the bar is back");
    }

    /// **The start handle carries the start of it back up**: dragged to the first line, the
    /// selection begins there.
    #[test]
    fn the_start_handle_widens_it_upward() {
        let mut d = driver();
        let at = on(&d, "second line", 80.0);
        hold(&mut d, at);
        assert_eq!(d.area_selection().as_deref(), Some("line"));
        let [start, _] = d.area_handles().expect("handles");
        let first = on(&d, "first line of words", 30.0);
        let from = middle(start.rect);
        let to = Point::new(first.x, from.y + (first.y - at.y));
        carry_handle(&mut d, from, to);
        let copied = d.area_selection().expect("a selection");
        let lines: Vec<&str> = copied.lines().collect();
        assert_eq!(lines.len(), 2, "{copied:?}");
        assert!("first line of words".ends_with(lines[0]), "{copied:?}");
        assert_eq!(lines[1], "second line");
    }

    /// **A handle cannot cross the other**: the end handle dragged back past the start leaves the
    /// selection as it was, rather than turning it inside out.
    #[test]
    fn a_handle_does_not_cross_the_other() {
        let mut d = driver();
        let at = on(&d, "second line", 80.0);
        hold(&mut d, at);
        let before = d.area_selection();
        assert!(before.is_some());
        let [_, end] = d.area_handles().expect("handles");
        let first = on(&d, "first line of words", 5.0);
        let from = middle(end.rect);
        // In one move, straight to a place before the start: refused, not turned inside out.
        let to = Point::new(first.x, from.y + (first.y - at.y));
        d.press(from);
        d.run(0.05);
        d.move_to(to);
        d.run(0.05);
        d.release(to);
        d.run(0.05);
        assert_eq!(d.area_selection(), before);
    }

    /// **The selection is painted**: a highlight over each text it covers, in the theme's
    /// colour, and none over the one it does not.
    #[test]
    fn the_selection_is_highlighted_in_each_text() {
        let mut d = driver();
        let (from, to) = (
            on(&d, "first line of words", 60.0),
            on(&d, "third line ends here", 40.0),
        );
        let bare = rects(&d);
        drag(&mut d, from, to);
        // What the selection added to the frame: a box over each text it covers.
        let boxes: Vec<frus_widgets::Rect> = rects(&d)
            .into_iter()
            .filter(|rect| !bare.contains(rect))
            .collect();
        assert_eq!(boxes.len(), 3, "one per text covered: {boxes:?}");
        let outside = on(&d, "Outside the area", 0.0);
        assert!(
            boxes.iter().all(|b| b.y > outside.y + 10.0),
            "none over the line outside the area: {boxes:?}"
        );
    }

    fn rects(d: &Driver<Doc>) -> Vec<frus_widgets::Rect> {
        let (ui, _) = d.frame_parts().expect("a frame");
        ui.scene()
            .primitives()
            .iter()
            .filter_map(|p| match p {
                frus_widgets::Primitive::Rect { rect, .. } => Some(*rect),
                _ => None,
            })
            .collect()
    }
}

/// Taps, double taps, long presses and secondary clicks on a
/// [`GestureDetector`](frus_widgets::GestureDetector), driven through the shell (milestone 581).
#[cfg(test)]
mod gesture_detector_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{Container, Flex, GestureDetector, Point, Text, Theme, Widget};
    use std::cell::RefCell;
    use std::rc::Rc;

    const W: f32 = 400.0;
    const H: f32 = 400.0;

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Tap,
        Double,
        Hold,
        Menu,
        Plain,
        OnlyDouble,
    }

    /// Three detectors down a page: one that takes everything, one that takes only a tap, and
    /// one that takes only a double tap.
    #[derive(Default)]
    struct Page {
        heard: Rc<RefCell<Vec<Msg>>>,
    }

    impl Application for Page {
        type Message = Msg;

        fn update(&mut self, message: Msg) -> Command<Msg> {
            self.heard.borrow_mut().push(message);
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Msg>> {
            let block = |label: &str| {
                Container::new()
                    .width(300.0)
                    .height(60.0)
                    .child(Text::new(label).no_wrap())
            };
            Box::new(
                Container::new().width(W).height(H).child(
                    Flex::column()
                        .gap(40.0)
                        .child(
                            GestureDetector::new(block("everything"))
                                .on_tap(Msg::Tap)
                                .on_double_tap(Msg::Double)
                                .on_long_press(Msg::Hold)
                                .on_secondary_tap(Msg::Menu),
                        )
                        .child(GestureDetector::new(block("tap only")).on_tap(Msg::Plain))
                        .child(
                            GestureDetector::new(block("double only"))
                                .on_double_tap(Msg::OnlyDouble),
                        ),
                ),
            )
        }
    }

    fn driver() -> (Driver<Page>, Rc<RefCell<Vec<Msg>>>) {
        let page = Page::default();
        let heard = page.heard.clone();
        let mut driver = Driver::new(page, W, H);
        driver.run(0.2);
        (driver, heard)
    }

    /// A point inside the block labelled `label`.
    fn on(d: &Driver<Page>, label: &str) -> Point {
        let (_, rect) = d
            .texts()
            .into_iter()
            .find(|(text, _)| text == label)
            .unwrap_or_else(|| panic!("{label:?} is on screen"));
        Point::new(rect.x + 20.0, rect.y + 8.0)
    }

    fn tap(d: &mut Driver<Page>, at: Point) {
        d.press(at);
        d.run(0.02);
        d.release(at);
        d.run(0.02);
    }

    /// **With a double tap possible, a tap waits**: nothing is sent at the release, and the
    /// tap is sent once the wait is over.
    #[test]
    fn a_tap_waits_while_a_double_tap_is_possible() {
        let (mut d, heard) = driver();
        let at = on(&d, "everything");
        tap(&mut d, at);
        assert!(heard.borrow().is_empty(), "not yet: {:?}", heard.borrow());
        assert!(d.tap_deadline(), "a tap was waiting");
        assert_eq!(*heard.borrow(), vec![Msg::Tap]);
    }

    /// **The loop wakes when the wait is over**, so a waiting tap is sent without anything
    /// else happening; and nothing is scheduled once it is gone.
    #[test]
    fn the_loop_wakes_for_a_waiting_tap() {
        let (mut d, _) = driver();
        let before = std::time::Instant::now();
        let at = on(&d, "everything");
        tap(&mut d, at);
        let wake = d.next_wake().expect("a wake for the tap");
        let wait = wake.duration_since(before);
        assert!(
            wait <= std::time::Duration::from_millis(400),
            "about 300 ms: {wait:?}"
        );
        d.tap_deadline();
        assert_eq!(d.next_wake(), None);
    }

    /// **Two taps in quick succession are a double tap**, and not also a tap.
    #[test]
    fn two_quick_taps_are_a_double_tap() {
        let (mut d, heard) = driver();
        let at = on(&d, "everything");
        tap(&mut d, at);
        tap(&mut d, Point::new(at.x + 6.0, at.y + 2.0));
        assert_eq!(*heard.borrow(), vec![Msg::Double]);
        assert!(!d.tap_deadline(), "nothing is left waiting");
        assert_eq!(*heard.borrow(), vec![Msg::Double]);
    }

    /// **Without a double tap, a tap answers at once.**
    #[test]
    fn a_tap_alone_answers_at_once() {
        let (mut d, heard) = driver();
        let at = on(&d, "tap only");
        tap(&mut d, at);
        assert_eq!(*heard.borrow(), vec![Msg::Plain]);
        tap(&mut d, at);
        assert_eq!(
            *heard.borrow(),
            vec![Msg::Plain, Msg::Plain],
            "two taps are two taps"
        );
    }

    /// **A press somewhere else ends the wait**: the first tap is a tap after all, sent before
    /// what the second press does.
    #[test]
    fn a_press_elsewhere_sends_the_waiting_tap() {
        let (mut d, heard) = driver();
        let (first, other) = (on(&d, "everything"), on(&d, "tap only"));
        tap(&mut d, first);
        tap(&mut d, other);
        assert_eq!(*heard.borrow(), vec![Msg::Tap, Msg::Plain]);
    }

    /// **The secondary button** sends its own message, and no tap.
    #[test]
    fn a_secondary_click_sends_its_message() {
        let (mut d, heard) = driver();
        let at = on(&d, "everything");
        d.secondary_click(at);
        d.run(0.02);
        assert_eq!(*heard.borrow(), vec![Msg::Menu]);
        let plain = on(&d, "tap only");
        d.secondary_click(plain);
        assert_eq!(
            *heard.borrow(),
            vec![Msg::Menu],
            "a detector without one hears nothing"
        );
    }

    /// **A long press** sends its message, and the release after it is not a tap.
    #[test]
    fn a_long_press_is_not_also_a_tap() {
        let (mut d, heard) = driver();
        let at = on(&d, "everything");
        d.press(at);
        d.run(0.1);
        assert!(d.hold_deadline(), "the hold fired");
        d.release(at);
        d.run(0.02);
        d.tap_deadline();
        assert_eq!(*heard.borrow(), vec![Msg::Hold]);
    }

    /// **A detector with only a double tap** takes the press all the same: one tap sends
    /// nothing, two send the double tap.
    #[test]
    fn a_double_tap_alone_is_heard() {
        let (mut d, heard) = driver();
        let at = on(&d, "double only");
        tap(&mut d, at);
        d.tap_deadline();
        assert!(heard.borrow().is_empty(), "{:?}", heard.borrow());
        tap(&mut d, at);
        tap(&mut d, at);
        assert_eq!(*heard.borrow(), vec![Msg::OnlyDouble]);
    }
}

/// Drags on a [`GestureDetector`](frus_widgets::GestureDetector), alone and inside a scroll,
/// driven through the shell (milestone 582).
#[cfg(test)]
mod gesture_pan_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{
        Container, Flex, GestureDetector, PanAxis, Point, SingleChildScrollView, Text, Theme,
        Widget,
    };
    use std::cell::RefCell;
    use std::rc::Rc;

    const W: f32 = 400.0;
    const H: f32 = 400.0;

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Start(Point),
        Update(Point, Point),
        End(Point),
        Tap,
        Hold,
    }

    /// A detector, either alone on the page or at the top of a tall vertical scroll.
    struct Page {
        axis: PanAxis,
        scrolled: bool,
        heard: Rc<RefCell<Vec<Msg>>>,
    }

    impl Application for Page {
        type Message = Msg;

        fn update(&mut self, message: Msg) -> Command<Msg> {
            self.heard.borrow_mut().push(message);
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Msg>> {
            let detector = GestureDetector::new(
                Container::new()
                    .width(300.0)
                    .height(150.0)
                    .child(Text::new("drag me").no_wrap()),
            )
            .on_tap(Msg::Tap)
            .on_long_press(Msg::Hold)
            .on_pan_start(Msg::Start)
            .on_pan_update(Msg::Update)
            .on_pan_end(Msg::End)
            .pan_axis(self.axis);
            let content = Flex::column()
                .child(Container::new().width(300.0).height(30.0))
                .child(detector)
                .child(Container::new().width(300.0).height(1200.0));
            if self.scrolled {
                Box::new(
                    SingleChildScrollView::new()
                        .width(W)
                        .height(H)
                        .child(content),
                )
            } else {
                Box::new(Container::new().width(W).height(H).child(content))
            }
        }
    }

    fn driver(axis: PanAxis, scrolled: bool) -> (Driver<Page>, Rc<RefCell<Vec<Msg>>>) {
        let heard = Rc::new(RefCell::new(Vec::new()));
        let page = Page {
            axis,
            scrolled,
            heard: heard.clone(),
        };
        let mut driver = Driver::new(page, W, H);
        driver.run(0.2);
        (driver, heard)
    }

    /// Where the detector's words start.
    fn origin(d: &Driver<Page>) -> Point {
        let (_, rect) = d
            .texts()
            .into_iter()
            .find(|(text, _)| text == "drag me")
            .expect("on screen");
        Point::new(rect.x, rect.y)
    }

    /// A finger from `from` by `(dx, dy)`, in eight steps.
    fn swipe(d: &mut Driver<Page>, from: Point, dx: f32, dy: f32) {
        d.press(from);
        d.run(0.02);
        for step in 1..=8 {
            let f = step as f32 / 8.0;
            d.move_to(Point::new(from.x + dx * f, from.y + dy * f));
            d.run(0.02);
        }
        d.release(Point::new(from.x + dx, from.y + dy));
        d.run(0.02);
    }

    fn deltas(heard: &[Msg]) -> Point {
        heard.iter().fold(Point::new(0.0, 0.0), |sum, m| match m {
            Msg::Update(_, delta) => Point::new(sum.x + delta.x, sum.y + delta.y),
            _ => sum,
        })
    }

    fn scroll_y(d: &Driver<Page>) -> f32 {
        d.offsets().first().map_or(0.0, |(_, offset)| offset.1)
    }

    /// **A drag is a start, movements and an end**: the start where the finger went down in
    /// the detector's own coordinates, and movements that add up to the way it went once past
    /// the slop.
    #[test]
    fn a_drag_is_a_start_updates_and_an_end() {
        let (mut d, heard) = driver(PanAxis::Free, false);
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 40.0);
        swipe(&mut d, at, 120.0, 60.0);
        let heard = heard.borrow();
        assert!(matches!(heard.first(), Some(Msg::Start(_))), "{heard:?}");
        if let Some(Msg::Start(local)) = heard.first() {
            // The words sit at the detector's corner, 30 px down the page.
            let corner = origin(&d);
            assert!(corner.y >= 30.0, "{corner:?}");
            assert_eq!(*local, Point::new(at.x - corner.x, at.y - corner.y));
        }
        assert!(matches!(heard.last(), Some(Msg::End(_))), "{heard:?}");
        if let Some(Msg::End(velocity)) = heard.last() {
            assert!(velocity.x.hypot(velocity.y) <= 8000.0 + 0.5, "{velocity:?}");
        }
        let moved = deltas(&heard);
        assert!(moved.x > 60.0 && moved.y > 20.0, "{moved:?}");
        assert!(!heard.contains(&Msg::Tap), "a drag is not a tap");
        // The last movement is where the finger lifted: nothing was left behind on the way.
        let last = heard.iter().rev().find_map(|m| match m {
            Msg::Update(local, _) => Some(*local),
            _ => None,
        });
        let corner = origin(&d);
        assert_eq!(
            last,
            Some(Point::new(at.x + 120.0 - corner.x, at.y + 60.0 - corner.y))
        );
    }

    /// **A press that barely moves is a tap**, and no drag.
    #[test]
    fn a_press_that_does_not_move_is_a_tap() {
        let (mut d, heard) = driver(PanAxis::Free, false);
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 40.0);
        swipe(&mut d, at, 3.0, 2.0);
        assert_eq!(*heard.borrow(), vec![Msg::Tap]);
    }

    /// **A hold on a detector that also drags is a long press**: the drag waiting for the
    /// finger to move does not keep the hold from being one (seen on the phone).
    #[test]
    fn a_hold_on_a_dragging_detector_is_a_long_press() {
        let (mut d, heard) = driver(PanAxis::Free, false);
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 40.0);
        d.press(at);
        d.run(0.1);
        assert!(d.hold_deadline(), "the hold fired");
        d.release(at);
        d.run(0.02);
        assert_eq!(*heard.borrow(), vec![Msg::Hold]);
    }

    /// **The mouse drags too**, with its own, finer slop.
    #[test]
    fn a_mouse_drags_it() {
        let (mut d, heard) = driver(PanAxis::Free, false);
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 40.0);
        d.press_mouse(at);
        d.run(0.02);
        d.move_mouse(Point::new(at.x + 30.0, at.y));
        d.run(0.02);
        d.release_mouse(Point::new(at.x + 30.0, at.y));
        d.run(0.02);
        let heard = heard.borrow();
        assert!(matches!(heard.first(), Some(Msg::Start(_))), "{heard:?}");
        assert!(matches!(heard.last(), Some(Msg::End(_))), "{heard:?}");
    }

    /// **A horizontal drag in a vertical scroll**: across, the drag has it and the page stays;
    /// down, the page scrolls and the drag hears nothing. Its movements are only across.
    #[test]
    fn a_horizontal_drag_shares_a_vertical_scroll() {
        let (mut d, heard) = driver(PanAxis::Horizontal, true);
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 40.0);
        swipe(&mut d, at, 120.0, 10.0);
        assert!(
            matches!(heard.borrow().first(), Some(Msg::Start(_))),
            "{:?}",
            heard.borrow()
        );
        assert_eq!(deltas(&heard.borrow()).y, 0.0, "only across");
        assert_eq!(scroll_y(&d), 0.0, "the page did not move");

        heard.borrow_mut().clear();
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 120.0);
        swipe(&mut d, at, 5.0, -120.0);
        assert!(heard.borrow().is_empty(), "{:?}", heard.borrow());
        assert!(scroll_y(&d) > 30.0, "the page scrolled: {}", scroll_y(&d));
    }

    /// **A free drag in a vertical scroll** takes a movement across and leaves a movement
    /// down to the scroll, as the reference's pan does.
    #[test]
    fn a_free_drag_leaves_the_scroll_its_own_direction() {
        let (mut d, heard) = driver(PanAxis::Free, true);
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 40.0);
        swipe(&mut d, at, 150.0, 8.0);
        assert!(
            matches!(heard.borrow().first(), Some(Msg::Start(_))),
            "{:?}",
            heard.borrow()
        );
        assert_eq!(scroll_y(&d), 0.0);

        heard.borrow_mut().clear();
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 120.0);
        swipe(&mut d, at, 4.0, -120.0);
        assert!(heard.borrow().is_empty(), "{:?}", heard.borrow());
        assert!(scroll_y(&d) > 30.0, "the page scrolled: {}", scroll_y(&d));
    }

    /// **A machine that stalls in the middle of a drag does not change it** (milestone 584,
    /// seen in CI). The shell's gestures are timed by the driver's frames and not by the wall:
    /// with the wall's clock, twenty milliseconds lost between two movements a microsecond
    /// apart read as a fling in either direction, and a page scrolled down was thrown back to
    /// the top.
    #[test]
    fn a_stall_mid_drag_does_not_change_the_scroll() {
        let (mut d, heard) = driver(PanAxis::Free, true);
        let from = Point::new(origin(&d).x + 40.0, origin(&d).y + 120.0);
        d.press(from);
        d.run(0.02);
        for step in 1..=8 {
            let f = step as f32 / 8.0;
            d.move_to(Point::new(from.x + 4.0 * f, from.y - 120.0 * f));
            if step == 5 {
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
            d.run(0.02);
        }
        d.release(Point::new(from.x + 4.0, from.y - 120.0));
        d.run(0.02);
        assert!(heard.borrow().is_empty(), "{:?}", heard.borrow());
        assert!(scroll_y(&d) > 30.0, "the page scrolled: {}", scroll_y(&d));
    }

    /// **A vertical drag in a vertical scroll** is the detector's: it asked for that
    /// direction, and it is under the finger.
    #[test]
    fn a_vertical_drag_takes_it_from_the_scroll() {
        let (mut d, heard) = driver(PanAxis::Vertical, true);
        let at = Point::new(origin(&d).x + 40.0, origin(&d).y + 120.0);
        swipe(&mut d, at, 6.0, -100.0);
        let heard = heard.borrow();
        assert!(matches!(heard.first(), Some(Msg::Start(_))), "{heard:?}");
        let moved = deltas(&heard);
        assert_eq!(moved.x, 0.0, "only down");
        assert!(moved.y < -40.0, "{moved:?}");
        assert_eq!(scroll_y(&d), 0.0, "the page did not move");
    }
}

/// The pointer entering, moving over and leaving a
/// [`MouseRegion`](frus_widgets::MouseRegion), driven through the shell (milestone 583).
#[cfg(test)]
mod mouse_region_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{
        Container, Cursor, Flex, MouseRegion, Point, Positioned, Stack, TextField, Theme, Widget,
    };
    use std::cell::RefCell;
    use std::rc::Rc;

    const W: f32 = 400.0;
    const H: f32 = 600.0;

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Enter(&'static str, Point),
        Move(&'static str),
        Exit(&'static str),
        Show,
    }

    /// An outer region holding an inner one at its top; below them, a big region with a
    /// smaller one overlapping it — not inside it — in a stack; and a region that appears
    /// when told to.
    struct Page {
        front_opaque: bool,
        shown: bool,
        heard: Rc<RefCell<Vec<Msg>>>,
    }

    fn region(name: &'static str, child: impl Widget<Msg> + 'static) -> MouseRegion<Msg> {
        MouseRegion::new(child)
            .on_enter(move |at| Msg::Enter(name, at))
            .on_hover(move |_| Msg::Move(name))
            .on_exit(move |_| Msg::Exit(name))
    }

    impl Application for Page {
        type Message = Msg;

        fn update(&mut self, message: Msg) -> Command<Msg> {
            if message == Msg::Show {
                self.shown = true;
            } else {
                self.heard.borrow_mut().push(message);
            }
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Msg>> {
            // 0..200: outer (300 wide), with inner 100×50 at its top-left.
            let nested = region(
                "outer",
                Container::new().width(300.0).height(200.0).child(
                    region("inner", Container::new().width(100.0).height(50.0))
                        .cursor(Cursor::Pointer),
                ),
            )
            .cursor(Cursor::Grab);
            // 200..400: back fills a 300×200 stack; front sits at (50, 50), 100×100, over it.
            let stack = Stack::new()
                .width(300.0)
                .height(200.0)
                .layer(region("back", Container::new().width(300.0).height(200.0)))
                .layer(
                    Positioned::new(
                        region("front", Container::new().width(100.0).height(100.0))
                            .opaque(self.front_opaque),
                    )
                    .left(50.0)
                    .top(50.0),
                );
            // 400..500: a field inside a region that asks for a hand.
            let field = region("field", TextField::new("").width(300.0)).cursor(Cursor::Pointer);
            // 500..600: a region that appears.
            let appearing: Box<dyn Widget<Msg>> = if self.shown {
                Box::new(region("late", Container::new().width(300.0).height(100.0)))
            } else {
                Box::new(Container::new().width(300.0).height(100.0))
            };
            Box::new(
                Container::new().width(W).height(H).child(
                    Flex::column()
                        .child(nested)
                        .child(stack)
                        .child(Container::new().height(100.0).child(field))
                        .child(appearing),
                ),
            )
        }
    }

    fn driver(front_opaque: bool) -> (Driver<Page>, Rc<RefCell<Vec<Msg>>>) {
        let heard = Rc::new(RefCell::new(Vec::new()));
        let page = Page {
            front_opaque,
            shown: false,
            heard: heard.clone(),
        };
        let mut driver = Driver::new(page, W, H);
        driver.run(0.2);
        (driver, heard)
    }

    fn take(heard: &Rc<RefCell<Vec<Msg>>>) -> Vec<Msg> {
        std::mem::take(&mut *heard.borrow_mut())
    }

    fn mouse(d: &mut Driver<Page>, x: f32, y: f32) {
        d.move_mouse(Point::new(x, y));
        d.run(0.02);
    }

    /// **Into a region inside another, both are entered**, the outer first, each told where
    /// the pointer is in its own coordinates; a move inside is heard by both; out of the
    /// inner one only it is left, and out of both the outer one is too.
    #[test]
    fn nested_regions_are_entered_and_left_together() {
        let (mut d, heard) = driver(true);
        mouse(&mut d, 20.0, 10.0);
        assert_eq!(
            take(&heard),
            vec![
                Msg::Enter("outer", Point::new(20.0, 10.0)),
                Msg::Enter("inner", Point::new(20.0, 10.0)),
            ]
        );
        mouse(&mut d, 30.0, 12.0);
        let moved = take(&heard);
        assert!(moved.contains(&Msg::Move("inner")) && moved.contains(&Msg::Move("outer")));
        mouse(&mut d, 200.0, 150.0);
        assert_eq!(take(&heard), vec![Msg::Exit("inner"), Msg::Move("outer")]);
        mouse(&mut d, 350.0, 150.0);
        assert_eq!(take(&heard), vec![Msg::Exit("outer")]);
    }

    /// **An opaque region hides the one behind it**: over the overlap, only the front one is
    /// in; one that is not opaque lets the back one in too.
    #[test]
    fn an_opaque_region_hides_the_one_behind() {
        let (mut d, heard) = driver(true);
        mouse(&mut d, 80.0, 280.0);
        let entered: Vec<_> = take(&heard);
        assert!(
            entered.iter().any(|m| matches!(m, Msg::Enter("front", _))),
            "{entered:?}"
        );
        assert!(
            !entered.iter().any(|m| matches!(m, Msg::Enter("back", _))),
            "{entered:?}"
        );
        // Out of the front one and still in the back: the back one is entered now.
        mouse(&mut d, 250.0, 280.0);
        let after = take(&heard);
        assert!(after.contains(&Msg::Exit("front")), "{after:?}");
        assert!(
            after.iter().any(|m| matches!(m, Msg::Enter("back", _))),
            "{after:?}"
        );

        let (mut d, heard) = driver(false);
        mouse(&mut d, 80.0, 280.0);
        let entered = take(&heard);
        assert!(
            entered.iter().any(|m| matches!(m, Msg::Enter("front", _))),
            "{entered:?}"
        );
        assert!(
            entered.iter().any(|m| matches!(m, Msg::Enter("back", _))),
            "{entered:?}"
        );
    }

    /// **With a button held, a region is entered and left but hears no moves**, as the
    /// reference's hover is only a pointer with nothing pressed.
    #[test]
    fn no_moves_while_a_button_is_held() {
        let (mut d, heard) = driver(true);
        mouse(&mut d, 350.0, 150.0);
        take(&heard);
        d.press_mouse(Point::new(350.0, 150.0));
        d.run(0.02);
        d.move_mouse(Point::new(40.0, 20.0));
        d.run(0.02);
        d.move_mouse(Point::new(45.0, 22.0));
        d.run(0.02);
        let heard_now = take(&heard);
        assert!(
            heard_now
                .iter()
                .any(|m| matches!(m, Msg::Enter("inner", _))),
            "{heard_now:?}"
        );
        assert!(
            !heard_now.iter().any(|m| matches!(m, Msg::Move(_))),
            "{heard_now:?}"
        );
        d.release_mouse(Point::new(45.0, 22.0));
        d.run(0.02);
    }

    /// **A finger is in a region while it touches**: entered at the press, left at the lift.
    #[test]
    fn a_finger_enters_while_it_touches() {
        let (mut d, heard) = driver(true);
        d.press(Point::new(200.0, 150.0));
        d.run(0.02);
        assert_eq!(
            take(&heard),
            vec![Msg::Enter("outer", Point::new(200.0, 150.0))]
        );
        d.release(Point::new(200.0, 150.0));
        d.run(0.02);
        assert_eq!(take(&heard), vec![Msg::Exit("outer")]);
    }

    /// **A region that comes under a still pointer is entered** at the next frame, with no
    /// movement at all.
    #[test]
    fn a_region_appearing_under_the_pointer_is_entered() {
        let (mut d, heard) = driver(true);
        mouse(&mut d, 150.0, 550.0);
        assert!(take(&heard).is_empty());
        d.update(Msg::Show);
        d.run(0.05);
        let heard_now = take(&heard);
        assert!(
            heard_now.iter().any(|m| matches!(m, Msg::Enter("late", _))),
            "{heard_now:?}"
        );
    }

    /// **The cursor is the innermost region's**, unless what is under the pointer asks for
    /// one of its own: a field keeps its text cursor inside a region asking for a hand.
    #[test]
    fn the_innermost_region_sets_the_cursor() {
        let (mut d, _) = driver(true);
        mouse(&mut d, 20.0, 10.0);
        assert_eq!(d.cursor_shown(), Cursor::Pointer, "the inner region's");
        mouse(&mut d, 200.0, 150.0);
        assert_eq!(d.cursor_shown(), Cursor::Grab, "the outer region's");
        mouse(&mut d, 350.0, 150.0);
        assert_eq!(d.cursor_shown(), Cursor::Default, "no region");
        mouse(&mut d, 100.0, 420.0);
        assert_eq!(d.cursor_shown(), Cursor::Text, "the field's own");
    }
}

/// The pointer's raw events on a [`Listener`](frus_widgets::Listener), driven through the
/// shell (milestone 586).
#[cfg(test)]
mod listener_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{
        Button, Container, Flex, Listener, ListenerEvent, ListenerEventKind as Raw, Point,
        SingleChildScrollView, Theme, Widget,
    };
    use std::cell::RefCell;
    use std::rc::Rc;

    const W: f32 = 400.0;
    const H: f32 = 400.0;

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Heard(&'static str, Raw, Point),
        Pressed,
    }

    /// In a scroll taller than the window: an outer listener (300×300 at the top, 40 px down)
    /// holding an inner one (100×100 at its top-left) with a button in it.
    struct Page {
        heard: Rc<RefCell<Vec<Msg>>>,
    }

    fn listen(name: &'static str) -> impl Fn(ListenerEvent) -> Option<Msg> {
        move |event| Some(Msg::Heard(name, event.kind, event.local))
    }

    impl Application for Page {
        type Message = Msg;

        fn update(&mut self, message: Msg) -> Command<Msg> {
            self.heard.borrow_mut().push(message);
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Msg>> {
            let inner = Listener::new(
                Container::new()
                    .width(100.0)
                    .height(100.0)
                    .child(Button::new("Press").on_press(Msg::Pressed)),
                listen("inner"),
            );
            let outer = Listener::new(
                Container::new().width(300.0).height(300.0).child(inner),
                listen("outer"),
            );
            Box::new(
                SingleChildScrollView::new().width(W).height(H).child(
                    Flex::column()
                        .child(Container::new().width(300.0).height(40.0))
                        .child(outer)
                        .child(Container::new().width(300.0).height(1000.0)),
                ),
            )
        }
    }

    fn driver() -> (Driver<Page>, Rc<RefCell<Vec<Msg>>>) {
        let heard = Rc::new(RefCell::new(Vec::new()));
        let mut d = Driver::new(
            Page {
                heard: heard.clone(),
            },
            W,
            H,
        );
        d.run(0.2);
        (d, heard)
    }

    fn take(heard: &Rc<RefCell<Vec<Msg>>>) -> Vec<Msg> {
        std::mem::take(&mut *heard.borrow_mut())
    }

    /// The events `name` heard, in order.
    fn of(heard: &[Msg], name: &str) -> Vec<(Raw, Point)> {
        heard
            .iter()
            .filter_map(|m| match m {
                Msg::Heard(n, kind, at) if *n == name => Some((*kind, *at)),
                _ => None,
            })
            .collect()
    }

    fn scroll_y(d: &Driver<Page>) -> f32 {
        d.offsets().first().map_or(0.0, |(_, offset)| offset.1)
    }

    /// **A press is heard by every listener under it, the innermost first**, each in its own
    /// coordinates.
    #[test]
    fn a_press_is_heard_innermost_first() {
        let (mut d, heard) = driver();
        d.press(Point::new(250.0, 90.0));
        d.run(0.02);
        let h = take(&heard);
        assert_eq!(of(&h, "outer"), vec![(Raw::Down, Point::new(250.0, 50.0))]);
        assert!(of(&h, "inner").is_empty(), "outside the inner one: {h:?}");
        d.release(Point::new(250.0, 90.0));
        d.run(0.02);
        take(&heard);

        d.press(Point::new(60.0, 80.0));
        d.run(0.02);
        let h = take(&heard);
        let order: Vec<_> = h
            .iter()
            .filter_map(|m| match m {
                Msg::Heard(n, Raw::Down, _) => Some(*n),
                _ => None,
            })
            .collect();
        assert_eq!(order, vec!["inner", "outer"], "{h:?}");
        assert_eq!(of(&h, "inner"), vec![(Raw::Down, Point::new(60.0, 40.0))]);
        d.release(Point::new(60.0, 80.0));
        d.run(0.02);
    }

    /// **The pointer that went down inside is followed wherever it goes**, out of the box,
    /// until it lifts — and the listener does not keep the page from scrolling under it.
    #[test]
    fn the_pointer_is_followed_out_and_the_page_still_scrolls() {
        let (mut d, heard) = driver();
        let from = Point::new(250.0, 300.0);
        d.press(from);
        d.run(0.02);
        for step in 1..=8 {
            d.move_to(Point::new(250.0, 300.0 - 35.0 * step as f32));
            d.run(0.02);
        }
        d.release(Point::new(250.0, 20.0));
        d.run(0.02);
        let h = take(&heard);
        let outer = of(&h, "outer");
        assert_eq!(outer.first().map(|e| e.0), Some(Raw::Down), "{outer:?}");
        assert_eq!(outer.last().map(|e| e.0), Some(Raw::Up), "{outer:?}");
        assert!(
            outer.iter().filter(|e| e.0 == Raw::Move).count() >= 7,
            "{outer:?}"
        );
        assert!(scroll_y(&d) > 50.0, "the page scrolled: {}", scroll_y(&d));
    }

    /// **A pointer that leaves the box is still heard**, outside it, until it lifts — a mouse,
    /// which scrolls nothing, carried right out of both listeners.
    #[test]
    fn a_pointer_that_leaves_is_still_heard() {
        let (mut d, heard) = driver();
        d.press_mouse(Point::new(60.0, 80.0));
        d.run(0.02);
        d.move_mouse(Point::new(390.0, 390.0));
        d.run(0.02);
        d.release_mouse(Point::new(390.0, 390.0));
        d.run(0.02);
        let h = take(&heard);
        let inner = of(&h, "inner");
        assert_eq!(
            inner,
            vec![
                (Raw::Down, Point::new(60.0, 40.0)),
                (Raw::Move, Point::new(390.0, 350.0)),
                (Raw::Up, Point::new(390.0, 350.0)),
            ],
            "{h:?}"
        );
        assert_eq!(of(&h, "outer").len(), 3, "{h:?}");
    }

    /// **A button inside keeps its tap**, and the listeners hear the press and the release.
    #[test]
    fn a_button_inside_keeps_its_tap() {
        let (mut d, heard) = driver();
        let at = Point::new(30.0, 55.0);
        d.press(at);
        d.release(at);
        d.run(0.05);
        let h = take(&heard);
        assert!(h.contains(&Msg::Pressed), "{h:?}");
        let inner = of(&h, "inner");
        assert_eq!(
            inner.iter().map(|e| e.0).collect::<Vec<_>>(),
            vec![Raw::Down, Raw::Up]
        );
    }

    /// **A mouse with nothing held is heard as a hover** by the listeners under it, and by no
    /// other.
    #[test]
    fn a_mouse_hovering_is_heard() {
        let (mut d, heard) = driver();
        d.move_mouse(Point::new(250.0, 90.0));
        d.run(0.02);
        let h = take(&heard);
        assert_eq!(of(&h, "outer"), vec![(Raw::Hover, Point::new(250.0, 50.0))]);
        assert!(of(&h, "inner").is_empty());
        d.move_mouse(Point::new(390.0, 390.0));
        d.run(0.02);
        assert!(take(&heard).is_empty(), "outside both");
    }
}

#[cfg(test)]
mod menu_keyboard_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{
        KeyStroke, MenuBar, MenuItem, MenuPath, Point, ShortcutKey, SubmenuButton, Theme, Widget,
    };

    const W: f32 = 600.0;
    const H: f32 = 400.0;

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Menu(MenuPath),
        Picked(&'static str),
    }

    /// File: New, Open recent ▸ (notes.txt, todo.md), Quit.
    #[derive(Default)]
    struct Editor {
        menu: MenuPath,
        /// The last row picked.
        picked: Option<&'static str>,
    }

    impl Application for Editor {
        type Message = Msg;

        fn update(&mut self, message: Msg) -> Command<Msg> {
            match message {
                Msg::Menu(path) => self.menu = path,
                Msg::Picked(what) => {
                    self.picked = Some(what);
                    self.menu = MenuPath::closed();
                }
            }
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Msg>> {
            Box::new(
                MenuBar::new(&self.menu, Msg::Menu).menu(
                    SubmenuButton::new("File")
                        .item(MenuItem::new("New", Msg::Picked("new")))
                        .submenu(
                            SubmenuButton::new("Open recent")
                                .item(MenuItem::new("notes.txt", Msg::Picked("notes")))
                                .item(MenuItem::new("todo.md", Msg::Picked("todo"))),
                        )
                        .item(MenuItem::new("Quit", Msg::Picked("quit"))),
                ),
            )
        }
    }

    /// The identity of the row whose words are `label`, from what the last frame drew.
    fn row(d: &Driver<Editor>, label: &str) -> Option<frus_widgets::WidgetId> {
        let (_, rect) = d.texts().into_iter().find(|(text, _)| text == label)?;
        d.hit(Point::new(rect.x + 4.0, rect.y + 4.0))
    }

    /// **A menu that opens gives its first row the focus**, a submenu that opens gives its
    /// own first row the focus, and Escape closes one level and hands the focus back.
    #[test]
    fn opening_a_menu_focuses_its_first_row_and_escape_goes_back_one_level() {
        let mut d = Driver::new(Editor::default(), W, H);
        d.run(0.1);
        assert_eq!(d.focused(), None);

        d.update(Msg::Menu(MenuPath::from_indices(vec![0])));
        d.run(0.1);
        let new = row(&d, "New").expect("the menu is open");
        assert_eq!(d.focused(), Some(new), "the first row has the focus");

        d.update(Msg::Menu(MenuPath::from_indices(vec![0, 1])));
        d.run(0.1);
        let notes = row(&d, "notes.txt").expect("the submenu is open");
        assert_eq!(d.focused(), Some(notes), "the submenu's first row has it");

        d.escape();
        d.run(0.1);
        assert_eq!(
            d.app().menu,
            MenuPath::from_indices(vec![0]),
            "one level closed"
        );
        assert!(row(&d, "notes.txt").is_none());
        assert_eq!(d.focused(), Some(new), "and the focus is back in the menu");

        d.escape();
        d.run(0.1);
        assert!(!d.app().menu.is_open(), "then the menu");
    }

    /// **The whole menu from the keyboard**, through the shell's own handling of each key
    /// (milestone 608): down to the row that opens a submenu, right into it, down to its
    /// second row, left back out, up to the first row and Enter on it.
    #[test]
    fn the_menu_is_worked_from_the_keyboard() {
        let key = |d: &mut Driver<Editor>, k: ShortcutKey| {
            d.key(KeyStroke::new(k));
            d.run(0.1);
        };
        let mut d = Driver::new(Editor::default(), W, H);
        d.run(0.1);
        d.update(Msg::Menu(MenuPath::from_indices(vec![0])));
        d.run(0.1);
        let (new, recent) = (row(&d, "New").unwrap(), row(&d, "Open recent").unwrap());
        assert_eq!(d.focused(), Some(new));

        key(&mut d, ShortcutKey::Down);
        assert_eq!(d.focused(), Some(recent), "down to the next row");
        key(&mut d, ShortcutKey::Right);
        assert_eq!(
            d.app().menu,
            MenuPath::from_indices(vec![0, 1]),
            "right opens it"
        );
        assert_eq!(
            d.focused(),
            row(&d, "notes.txt"),
            "and its first row has the focus"
        );
        key(&mut d, ShortcutKey::Down);
        assert_eq!(d.focused(), row(&d, "todo.md"));
        key(&mut d, ShortcutKey::Left);
        assert_eq!(
            d.app().menu,
            MenuPath::from_indices(vec![0]),
            "left closes it"
        );
        assert_eq!(
            d.focused(),
            Some(recent),
            "and the focus is back on its row"
        );
        key(&mut d, ShortcutKey::Up);
        assert_eq!(d.focused(), Some(new));
        key(&mut d, ShortcutKey::Enter);
        assert_eq!(d.app().picked, Some("new"), "Enter picks the row");
        assert!(!d.app().menu.is_open(), "and the menus close");
    }

    /// **A key with modifiers held** reaches a shortcut bound to it, and the modifiers are
    /// let go after it: a bare key that follows is not taken for the shortcut.
    #[test]
    fn a_stroke_holds_its_modifiers_for_the_key_alone() {
        let mut d = Driver::new(Editor::default(), W, H);
        d.run(0.1);
        d.key(KeyStroke::new(ShortcutKey::Char('a')).ctrl());
        assert!(!d.shell_modifiers().0, "ctrl let go after the stroke");
    }

    /// **The focus goes back to the word on the bar** when its menu closes: Tab onto File,
    /// Enter opens it and the focus goes into it, Escape closes it and the focus is on File
    /// again. A word whose wrappers changed as its menu opened was a different widget once
    /// it closed, and the focus had nowhere to go back to (milestone 608).
    #[test]
    fn closing_a_menu_hands_the_focus_back_to_its_word() {
        let key = |d: &mut Driver<Editor>, k: ShortcutKey| {
            d.key(KeyStroke::new(k));
            d.run(0.1);
        };
        let mut d = Driver::new(Editor::default(), W, H);
        d.run(0.1);
        key(&mut d, ShortcutKey::Tab);
        let file = d.focused().expect("Tab reached the bar");
        key(&mut d, ShortcutKey::Enter);
        assert!(d.app().menu.is_open(), "Enter opened the menu");
        assert_eq!(d.focused(), row(&d, "New"), "and the focus went into it");
        key(&mut d, ShortcutKey::Escape);
        assert!(!d.app().menu.is_open(), "Escape closed it");
        assert_eq!(d.focused(), Some(file), "and the focus is back on its word");
    }

    /// **A row that is not the first gets the focus back too.** With the focus on Quit, the
    /// pointer opens the submenu beside Open recent, which takes the focus; Escape closes it,
    /// and the focus is on Quit again. The other rows of a menu gained a hover region when a
    /// submenu opened, which moved them, and the focus fell to the first row instead, the
    /// one that takes it when nothing else does (milestone 608).
    #[test]
    fn a_submenu_closing_hands_the_focus_back_to_any_row() {
        let key = |d: &mut Driver<Editor>, k: ShortcutKey| {
            d.key(KeyStroke::new(k));
            d.run(0.1);
        };
        let mut d = Driver::new(Editor::default(), W, H);
        d.run(0.1);
        d.update(Msg::Menu(MenuPath::from_indices(vec![0])));
        d.run(0.1);
        key(&mut d, ShortcutKey::Down);
        key(&mut d, ShortcutKey::Down);
        let quit = row(&d, "Quit");
        assert_eq!(d.focused(), quit, "down twice reaches Quit");
        // What the pointer moving onto Open recent sends.
        d.update(Msg::Menu(MenuPath::from_indices(vec![0, 1])));
        d.run(0.1);
        assert_eq!(d.focused(), row(&d, "notes.txt"));
        key(&mut d, ShortcutKey::Escape);
        assert_eq!(d.app().menu, MenuPath::from_indices(vec![0]));
        assert_eq!(d.focused(), quit, "the focus is back on Quit");
    }
}

/// **A right-click on a field opens its selection bar**, the desktop's context menu for the
/// four things the bar holds (milestone 568), driven through the shell's own path: the
/// milestone had built it and not run it.
#[cfg(test)]
mod right_click_bar_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{Point, TextField, Theme, Widget};

    struct Form;

    impl Application for Form {
        type Message = ();

        fn update(&mut self, _message: ()) -> Command<()> {
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<()>> {
            Box::new(TextField::new("some words in a field"))
        }
    }

    #[test]
    fn a_right_click_on_a_field_opens_its_bar() {
        let mut d = Driver::new(Form, 500.0, 300.0);
        d.run(0.1);
        let shown = |d: &Driver<Form>, label: &str| d.texts().iter().any(|(t, _)| t == label);
        assert!(!shown(&d, "Select all"), "no bar before the click");
        let (_, words) = d
            .texts()
            .into_iter()
            .find(|(t, _)| t.contains("some words"))
            .expect("the field's words");
        d.secondary_click(Point::new(words.x + 20.0, words.y + words.height * 0.5));
        d.run(0.1);
        // Only what applies: nothing is selected, so nothing to cut or copy; and the
        // driver's clipboard is its own and empty, so nothing to paste — it no longer
        // follows the machine's (a CI runner's had text on it).
        assert!(shown(&d, "Select all"), "the bar is open: {:?}", d.texts());
        assert!(!shown(&d, "Copy") && !shown(&d, "Cut"));
        assert!(
            !shown(&d, "Paste"),
            "an empty clipboard offers nothing to paste"
        );
    }

    /// The same field, under a theme that follows Linux.
    struct DesktopForm;

    impl Application for DesktopForm {
        type Message = ();

        fn update(&mut self, _message: ()) -> Command<()> {
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<()>> {
            Box::new(TextField::new("some words in a field"))
        }

        fn theme(&self) -> Theme {
            Theme::default().with_platform(frus_widgets::TargetPlatform::Linux)
        }
    }

    /// **A right-click opens the menu where the pointer is** (milestone 618), as the
    /// reference's context menu goes to the last secondary tap: its first row's words sit
    /// 20 px after the pointer, on the pointer's line.
    #[test]
    fn a_right_click_opens_the_menu_at_the_pointer() {
        let mut d = Driver::new(DesktopForm, 500.0, 300.0);
        d.run(0.1);
        let (_, words) = d
            .texts()
            .into_iter()
            .find(|(t, _)| t.contains("some words"))
            .expect("the field's words");
        let click = Point::new(words.x + 20.0, words.y + words.height * 0.5);
        d.secondary_click(click);
        d.run(0.1);
        let (_, row) = d
            .texts()
            .into_iter()
            .find(|(t, _)| t == "Select all")
            .expect("the menu is open");
        assert_eq!(row.x, click.x + 20.0, "the menu starts at the pointer");
        assert!(
            row.y >= click.y && row.y < click.y + 36.0,
            "its first row is on the pointer's line: {row:?} {click:?}"
        );
    }

    /// **On a desktop, the menu's Select all puts the menu away** (milestone 625), as the
    /// reference's field does on macOS, Linux and Windows. A test runs on one of the three,
    /// whose system — not the theme — decides. The selection stays: the menu opened again
    /// over it offers Copy.
    #[test]
    fn a_desktop_s_select_all_puts_the_menu_away() {
        assert!(frus_widgets::default_target_platform().is_desktop());
        let mut d = Driver::new(DesktopForm, 500.0, 300.0);
        d.run(0.1);
        let shown = |d: &Driver<DesktopForm>, label: &str| {
            d.texts()
                .into_iter()
                .find(|(t, _)| t == label)
                .map(|(_, r)| r)
        };
        let words = shown(&d, "some words in a field").expect("the field's words");
        let click = Point::new(words.x + 20.0, words.y + words.height * 0.5);
        d.secondary_click(click);
        d.run(0.1);
        let row = shown(&d, "Select all").expect("the menu is open");
        let row = Point::new(row.x + 10.0, row.y + row.height * 0.5);
        d.press(row);
        d.release(row);
        d.run(0.1);
        assert!(shown(&d, "Select all").is_none(), "the menu is gone");
        assert!(shown(&d, "Copy").is_none(), "all of it: {:?}", d.texts());
        d.secondary_click(click);
        d.run(0.1);
        assert!(shown(&d, "Copy").is_some(), "the text is still selected");
    }
}

#[cfg(test)]
mod scroll_behavior_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{
        Container, Point, ScrollBehavior, ScrollConfiguration, SingleChildScrollView,
        TargetPlatform, Theme, VelocityStrategy, Widget,
    };

    /// A tall page in a scroll view that follows iOS, in an application whose theme says
    /// Android.
    struct Page;

    impl Application for Page {
        type Message = ();

        fn update(&mut self, _message: ()) -> Command<()> {
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<()>> {
            Box::new(ScrollConfiguration::new(
                ScrollBehavior::material().with_platform(TargetPlatform::Ios),
                SingleChildScrollView::new()
                    .width(300.0)
                    .height(400.0)
                    .child(Container::new().width(300.0).height(2000.0)),
            ))
        }

        fn theme(&self) -> Theme {
            Theme::default().with_platform(TargetPlatform::Android)
        }
    }

    /// **A drag on a scroll area reads its fling the way the area's behaviour does**
    /// (milestone 616), not the application's: the reference's scrollable builds its drag
    /// recognizer from its own configuration.
    #[test]
    fn a_drag_on_an_area_reads_its_fling_the_area_s_way() {
        let mut d = Driver::new(Page, 300.0, 400.0);
        d.run(0.2);
        d.press(Point::new(150.0, 200.0));
        assert_eq!(
            d.fling_strategy(),
            VelocityStrategy::RecentAverage(frus_widgets::BOUNCING_FLING_WEIGHTS)
        );
        d.release(Point::new(150.0, 200.0));
    }
}

/// A switch's thumb dragged through the shell (milestone 638): it follows the finger, flips
/// when let go past half way and goes back when not, and a tap still flips it.
#[cfg(test)]
mod switch_drag_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{Container, Point, Rect, Switch, Theme, Widget};

    const W: f32 = 300.0;
    const H: f32 = 200.0;

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Set(bool),
    }

    #[derive(Default)]
    struct Page {
        on: bool,
        heard: Vec<Msg>,
    }

    impl Application for Page {
        type Message = Msg;

        fn update(&mut self, message: Msg) -> Command<Msg> {
            let Msg::Set(on) = message;
            self.on = on;
            self.heard.push(message);
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Msg>> {
            Box::new(
                Container::new()
                    .width(W)
                    .height(H)
                    .child(Switch::new(self.on).on_toggle(Msg::Set)),
            )
        }
    }

    fn driver() -> Driver<Page> {
        let mut d = Driver::new(Page::default(), W, H);
        d.run(0.2);
        d
    }

    /// The track and the thumb the last frame drew: the 52 × 32 rectangle, and the last one.
    fn track_and_thumb(d: &Driver<Page>) -> (Rect, Rect) {
        let (ui, _) = d.frame_parts().expect("a frame");
        let rects: Vec<Rect> = ui
            .scene()
            .primitives()
            .iter()
            .filter_map(|p| match p {
                frus_widgets::Primitive::Rect { rect, .. } => Some(*rect),
                _ => None,
            })
            .collect();
        let track = *rects
            .iter()
            .find(|r| r.width == 52.0 && r.height == 32.0)
            .expect("the track");
        (track, *rects.last().expect("the thumb"))
    }

    /// How far along its travel the thumb's centre is, 0 at the start and 1 at the end.
    fn along(d: &Driver<Page>) -> f32 {
        let (track, thumb) = track_and_thumb(d);
        (thumb.x + thumb.width * 0.5 - track.x - 16.0) / 20.0
    }

    /// A finger on the thumb, moved by `dx` in eight steps; lifted when `lift`.
    fn drag(d: &mut Driver<Page>, dx: f32, lift: bool) {
        let (track, _) = track_and_thumb(d);
        let from = Point::new(track.x + 16.0, track.y + 16.0);
        d.press(from);
        d.run(0.02);
        for step in 1..=8 {
            d.move_to(Point::new(from.x + dx * step as f32 / 8.0, from.y));
            d.run(0.02);
        }
        if lift {
            d.release(Point::new(from.x + dx, from.y));
            d.run(0.02);
        }
    }

    /// **The thumb is where the finger is** while it is down, past the slop: placed, not
    /// animated, and the switch has said nothing yet.
    #[test]
    fn the_thumb_follows_the_finger() {
        let mut d = driver();
        assert!(along(&d).abs() < 1e-3, "off at rest");
        drag(&mut d, 40.0, false);
        let now = along(&d);
        assert!(now > 0.3 && now <= 1.0, "moved with the finger: {now}");
        assert!(d.app().heard.is_empty(), "nothing said while held");
        // Held, it stays: frames pass and the thumb does not go back.
        d.run(0.5);
        assert!((along(&d) - now).abs() < 1e-3, "held where it was put");
    }

    /// **Let go past half way, it flips** — and the release is not also a tap, which would
    /// flip it straight back.
    #[test]
    fn let_go_past_half_way_it_flips() {
        let mut d = driver();
        drag(&mut d, 60.0, true);
        assert_eq!(d.app().heard, vec![Msg::Set(true)]);
        d.run(0.5);
        assert!((along(&d) - 1.0).abs() < 1e-3, "settled on");
    }

    /// **Short of half way, it goes back**, and says nothing.
    #[test]
    fn let_go_short_of_half_way_it_goes_back() {
        let mut d = driver();
        // Out past the slop, then most of the way back: a finger that thought better of it.
        drag(&mut d, 30.0, false);
        let (track, _) = track_and_thumb(&d);
        let back = Point::new(track.x + 16.0 + 15.0, track.y + 16.0);
        d.move_to(back);
        d.run(0.02);
        assert!(along(&d) > 0.0, "it had moved");
        assert!(along(&d) < 0.5, "but is short of half way: {}", along(&d));
        d.release(back);
        d.run(0.5);
        assert!(d.app().heard.is_empty(), "nothing said");
        assert!(along(&d).abs() < 1e-3, "back off: {}", along(&d));
    }

    /// **A tap still flips it**: a drag begins only past the slop.
    #[test]
    fn a_tap_still_flips_it() {
        let mut d = driver();
        let (track, _) = track_and_thumb(&d);
        let at = Point::new(track.x + 16.0, track.y + 16.0);
        d.press(at);
        d.release(at);
        d.run(0.5);
        assert_eq!(d.app().heard, vec![Msg::Set(true)]);
        assert!((along(&d) - 1.0).abs() < 1e-3);
    }
}

/// A range slider dragged through the shell (milestone 651): the press picks the nearer
/// thumb and the drag carries it; a press where the thumbs meet waits for the movement; the
/// thumb last taken is painted on top.
#[cfg(test)]
mod range_slider_drag_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{Container, Point, RangeSlider, Rect, Theme, Widget};

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Range(f32, f32),
        Start(f32, f32),
        End(f32, f32),
    }

    struct Page {
        values: (f32, f32),
        heard: Vec<Msg>,
    }

    impl Application for Page {
        type Message = Msg;

        fn update(&mut self, message: Msg) -> Command<Msg> {
            if let Msg::Range(s, e) | Msg::End(s, e) = message {
                self.values = (s, e);
            }
            self.heard.push(message);
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Msg>> {
            let (start, end) = self.values;
            Box::new(
                Container::new().width(300.0).height(200.0).child(
                    RangeSlider::new(start, end)
                        .width(248.0)
                        .divisions(20)
                        .on_change(Msg::Range)
                        .on_change_start(Msg::Start)
                        .on_change_end(Msg::End),
                ),
            )
        }
    }

    fn driver(start: f32, end: f32) -> Driver<Page> {
        let page = Page {
            values: (start, end),
            heard: Vec::new(),
        };
        let mut d = Driver::new(page, 300.0, 200.0);
        d.run(0.2);
        d
    }

    /// The thumbs the last frame drew, in the order they were painted.
    fn thumbs(d: &Driver<Page>) -> Vec<Rect> {
        let (ui, _) = d.frame_parts().expect("a frame");
        ui.scene()
            .primitives()
            .iter()
            .filter_map(|p| match p {
                frus_widgets::Primitive::Rect { rect, blur, .. }
                    if *blur == 0.0 && rect.width == 20.0 && rect.height == 20.0 =>
                {
                    Some(*rect)
                }
                _ => None,
            })
            .collect()
    }

    fn centre(r: Rect) -> Point {
        Point::new(r.x + r.width * 0.5, r.y + r.height * 0.5)
    }

    /// A finger pressed at `from`, moved by `dx` in four steps, and lifted.
    fn drag(d: &mut Driver<Page>, from: Point, dx: f32) {
        d.press(from);
        d.run(0.02);
        for step in 1..=4 {
            d.move_to(Point::new(from.x + dx * step as f32 / 4.0, from.y));
            d.run(0.02);
        }
        d.release(Point::new(from.x + dx, from.y));
        d.run(0.02);
    }

    fn close(a: (f32, f32), b: (f32, f32)) -> bool {
        (a.0 - b.0).abs() < 1e-3 && (a.1 - b.1).abs() < 1e-3
    }

    /// **The press takes the nearer thumb and the drag carries it**: the bracket opens on
    /// the interval as it was and closes on the one the drag settled on; the other thumb
    /// stays.
    #[test]
    fn a_drag_carries_the_nearer_thumb() {
        let mut d = driver(0.25, 0.75);
        let t = thumbs(&d);
        assert_eq!(t.len(), 2);
        let start = centre(t[0]).x.min(centre(t[1]).x);
        // Just right of the start thumb, nearer it than the end: it is taken, and carried
        // to 0.445 of the 200-pixel track, which snaps to 0.45.
        drag(&mut d, Point::new(start + 4.0, centre(t[0]).y), 34.0);
        let heard = &d.app().heard;
        assert_eq!(heard.first(), Some(&Msg::Start(0.25, 0.75)), "{heard:?}");
        let Some(Msg::End(s, e)) = heard.last().cloned() else {
            panic!("no end: {heard:?}");
        };
        assert!(close((s, e), (0.45, 0.75)), "({s}, {e})");
        assert!(close(d.app().values, (0.45, 0.75)));
        // The start, taken last, is now the one on top: painted last.
        let order = thumbs(&d);
        assert!(order[1].x < order[0].x, "the start on top: {order:?}");
    }

    /// **Where the thumbs meet, the movement decides**: leftwards takes the start, and a
    /// thumb never passes the other.
    #[test]
    fn where_the_thumbs_meet_the_movement_decides() {
        let mut d = driver(0.5, 0.5);
        let at = centre(thumbs(&d)[0]);
        drag(&mut d, at, -40.0);
        assert!(close(d.app().values, (0.3, 0.5)), "{:?}", d.app().values);

        let mut d = driver(0.5, 0.5);
        drag(&mut d, at, 40.0);
        assert!(close(d.app().values, (0.5, 0.7)), "{:?}", d.app().values);

        // The start dragged past the end stops at it.
        let mut d = driver(0.3, 0.5);
        let start = centre(thumbs(&d)[0]);
        drag(&mut d, start, 120.0);
        assert!(close(d.app().values, (0.5, 0.5)), "{:?}", d.app().values);
    }
}

/// The focus moving, through the shell (milestone 660): a group told when it arrives and
/// leaves, and a field told of a press outside it.
#[cfg(test)]
mod focus_change_tests {
    use super::testing::Driver;
    use crate::{Application, Command};
    use frus_widgets::{Flex, Focus, Point, Rect, TextField, Theme, Widget};

    #[derive(Clone, Debug, PartialEq)]
    enum Msg {
        Group(bool),
        Outside,
        Typed,
    }

    #[derive(Default)]
    struct Page {
        heard: Vec<Msg>,
    }

    impl Application for Page {
        type Message = Msg;

        fn update(&mut self, message: Msg) -> Command<Msg> {
            if message != Msg::Typed {
                self.heard.push(message);
            }
            Command::none()
        }

        fn view(&self, _theme: &Theme) -> Box<dyn Widget<Msg>> {
            Box::new(
                Flex::column()
                    .width(300.0)
                    .height(400.0)
                    .gap(40.0)
                    .child(
                        Focus::new(
                            TextField::new("a")
                                .on_input(|_| Msg::Typed)
                                .on_tap_outside(Msg::Outside),
                        )
                        .skip_traversal()
                        .on_focus_change(Msg::Group),
                    )
                    .child(TextField::new("b").on_input(|_| Msg::Typed)),
            )
        }
    }

    /// The two fields' boxes, `a` then `b`.
    fn fields(d: &Driver<Page>) -> (Rect, Rect) {
        let (ui, _) = d.frame_parts().expect("a frame");
        let rects: Vec<Rect> = ui
            .focusable_ids()
            .filter_map(|id| ui.widget_rect(id))
            .filter(|r| r.height < 100.0)
            .collect();
        (rects[0], rects[rects.len() - 1])
    }

    fn centre(r: Rect) -> Point {
        Point::new(r.x + r.width / 2.0, r.y + r.height / 2.0)
    }

    fn tap(d: &mut Driver<Page>, at: Point) {
        d.press(at);
        d.release(at);
        d.run(0.05);
    }

    /// **A press on the field brings the focus into the group; a press elsewhere tells the
    /// field it was outside, then the group that the focus left.**
    #[test]
    fn the_shell_reports_the_focus_moving() {
        let mut d = Driver::new(Page::default(), 300.0, 400.0);
        d.run(0.2);
        let (a, b) = fields(&d);
        tap(&mut d, centre(a));
        assert_eq!(d.app().heard, vec![Msg::Group(true)], "arrived");
        tap(&mut d, centre(a));
        assert_eq!(
            d.app().heard,
            vec![Msg::Group(true)],
            "a press inside says nothing"
        );
        tap(&mut d, centre(b));
        assert_eq!(
            d.app().heard,
            vec![Msg::Group(true), Msg::Outside, Msg::Group(false)],
            "outside, then left"
        );
        tap(&mut d, Point::new(150.0, 390.0));
        assert_eq!(
            d.app().heard.len(),
            3,
            "the other field holds no `on_tap_outside`: {:?}",
            d.app().heard
        );
    }
}