nsh-engine 0.4.0

Engine thread that drives the JS host and the core and emits mount batches.
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
//! The engine thread of one surface.
//!
//! The engine owns a [`nsh_core::Core`] on a dedicated thread and runs one
//! app ([`App`]): a Rust app's root component, or a JS bundle in a QuickJS
//! VM (`nsh_js::Host`, feature `js-core`; `js` adds the standard modules
//! `zlib` and `crypto`). Each wake-up (input event, timer,
//! resize) runs the app's code (component tasks; JS and its microtasks),
//! applies what JS committed, lays out, and hands one [`MountBatch`] to the
//! platform through a [`MountSink`]. The platform thread never blocks on
//! the engine.

#[cfg(all(feature = "browser", target_arch = "wasm32", not(feature = "js-core")))]
pub mod browser;

mod access;
mod app_directory;
mod cache;
mod error;
mod host_channel;
mod local_storage;
#[cfg(feature = "net")]
pub mod net;
pub mod perf;
mod script;
#[cfg(feature = "shader")]
pub mod shader;
#[cfg(not(target_arch = "wasm32"))]
mod storage;
#[cfg(feature = "js-core")]
mod symbolicate;

// The typed API check (docs/dev/geometry.md, "Typed API"): the scan is
// nsh-core's; this crate's lists are `unitless.txt` and `untyped.txt`.
#[cfg(test)]
#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
mod unit_scan;

#[cfg(test)]
#[test]
fn public_api_is_typed() {
    unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
}

use std::{io, mem::ManuallyDrop, rc::Rc, sync::Arc, time::Duration};

pub use app_directory::app_dir_name;
use crossbeam_channel::{Receiver, Sender};
pub use local_storage::local_storage_prefix;
use nsh_core::{
    ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
    PayloadValue, TextEngine, element::JsEvent, time::Instant,
};
pub use nsh_core::{
    JsonValue,
    access::{Access, Capabilities},
    element::{EngineContext, Root, Tokens},
    geometry::{self, Bounds, Edges, Point, Points, Size},
    js::{HostLimits, Limits},
    platform::{
        ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HttpBody, HttpHead,
        HttpRequest, Idiom, Lifecycle, Locale, Os,
    },
    storage::{StorageBackend, StorageChange},
    time::Clock,
};
#[cfg(feature = "js-core")]
pub use nsh_js::BYTECODE_VERSION;
/// Signed packages, release-key certificates, revocations and trust stores.
#[cfg(feature = "js-core")]
pub use nsh_package as package;
use rustc_hash::FxHashMap;
#[cfg(not(target_arch = "wasm32"))]
pub use storage::{FileStorage, data_dir};

use crate::script::{NetworkQueue, RequestId, Script};
pub use crate::{
    cache::{ByteSize, CacheLocation, CacheOptions, CachePolicy},
    error::{AppError, AppErrorKind, PackageInfo},
    host_channel::{HostCall, HostChannel, HostReply, OpenUrlRequest},
};

#[cfg(not(target_arch = "wasm32"))]
/// Stack size of the engine thread. QuickJS recursion (and deep Solid
/// component trees) needs more than the 512 KiB default of secondary
/// threads on Apple platforms.
const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;

/// Minimum time between idle cycle collections. QuickJS frees acyclic
/// garbage immediately; only cycles (such as detached node subtrees, whose
/// parent/child links reference each other) wait for the collector.
const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);

/// How long the engine has had nothing to do (no message, no timer due)
/// before an idle collection: a collection walks every object of the VM,
/// tens of milliseconds for an app holding a lot of data, so it waits for
/// a pause rather than land between the turns of a paste held down or of
/// work done in slices on timers. An engine never quiet that long (a
/// timer every few frames) still collects every [`IDLE_GC_LONGEST`].
const IDLE_GC_QUIET: Duration = Duration::from_millis(300);

/// The longest time between idle collections, quiet or not.
const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);

/// The shortest time between two deliveries of mouse motion: a frame at
/// 120 Hz. Mice report moves far more often (up to 1000 Hz), and a handler
/// that redraws a crosshair needs no more than one per frame.
const MOUSE_MOVE_INTERVAL: Duration = Duration::from_millis(8);

/// The app an engine runs.
#[derive(Debug, Clone)]
#[allow(
    clippy::large_enum_variant,
    reason = "one app per surface; keep the public constructor API without allocation"
)]
pub enum App {
    /// A Rust app: its root component, mounted as the surface's content.
    Rust(Root),
    /// A JS app (feature `js-core`).
    Js(Bundle),
}

impl From<Bundle> for App {
    fn from(bundle: Bundle) -> Self {
        App::Js(bundle)
    }
}

impl App {
    /// The app's id (`nsh.json` `"id"`), when it carries one.
    pub fn app_id(&self) -> Option<&str> {
        match self {
            App::Rust(root) => root.app_id_ref(),
            App::Js(bundle) => bundle.app_id.as_deref(),
        }
    }
}

impl From<Root> for App {
    fn from(root: Root) -> Self {
        App::Rust(root)
    }
}

/// An app bundle: its code plus, in development, a source map.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Bundle {
    /// The code.
    pub code: BundleCode,
    /// Source map (JSON) used to show app source locations in stack traces.
    pub source_map: Option<Arc<str>>,
    /// What the code may do.
    pub policy: Policy,
    /// What relative request URLs resolve against (the page's URL on the
    /// web); `None`: they are invalid.
    pub base_url: Option<Arc<str>>,
    /// The chunks of a split bundle that come with it (`import()` loads
    /// them without asking the platform); those missing are asked of
    /// [`MountSink::load_chunk`]. Shared by the bundle's clones.
    pub chunks: Arc<Vec<Chunk>>,
    /// The app's id (`nsh.json` `"id"`; a signed package's verified one):
    /// it names where the app keeps its data (`nsh/storage`).
    pub app_id: Option<String>,
    /// Trusted filesystem anchors selected by the native host, never decoded
    /// from application code, its manifest or a development server message.
    /// Missing anchors deny relative and corresponding placeholder grants.
    pub system_paths: nsh_core::access::TrustedPaths,
    /// The signed package the bundle came from ([`Bundle::from_package`]),
    /// named in the app's errors ([`AppError::package`]).
    pub package: Option<Arc<PackageInfo>>,
}

/// A chunk of a split bundle (`nsh_bundler::Chunk`): app code that
/// `import()` loads on demand.
#[derive(Debug, Clone)]
pub struct Chunk {
    /// Its id (`Screen.js`), as the bundle imports it.
    pub id: String,
    /// The code.
    pub code: BundleCode,
    /// Source map (JSON), for stack traces.
    pub source_map: Option<Arc<str>>,
}

impl Chunk {
    /// A chunk as JS source.
    pub fn source(id: impl Into<String>, code: String) -> Self {
        Self {
            id: id.into(),
            code: BundleCode::Source(code),
            source_map: None,
        }
    }

    /// A chunk as bytecode (`nsh_js::compile_chunk_bytecode`).
    ///
    /// # Safety
    ///
    /// As [`Bundle::bytecode`].
    pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
        Self {
            id: id.into(),
            code: BundleCode::Bytecode(bytes),
            source_map: None,
        }
    }

    /// Attaches a source map.
    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
        self.source_map = Some(map.into());
        self
    }
}

/// What a bundle's code may do.
#[derive(Debug, Clone)]
pub struct Policy {
    /// Run without `eval`, the function constructors and writable shared
    /// prototypes (see `nsh_js::HostOptions::harden`). On by default; off for
    /// development bundles.
    pub harden: bool,
    /// What the app declared (`nsh.json` `capabilities`); `None`: no
    /// declaration, everything.
    pub declared: Option<Capabilities>,
    /// What the embedding app grants at most; `None`: whatever the app
    /// declared.
    pub granted: Option<Capabilities>,
}

impl Default for Policy {
    fn default() -> Self {
        Self {
            harden: true,
            declared: None,
            granted: None,
        }
    }
}

impl Policy {
    /// Development bundles: `eval` and friends stay (debugging); the
    /// capabilities are still enforced, so a missing one shows during
    /// development.
    pub fn development() -> Self {
        Self {
            harden: false,
            ..Self::default()
        }
    }

    /// What the app may reach under this policy.
    pub fn access(&self) -> Access {
        Access {
            declared: self.declared.clone().unwrap_or_else(Capabilities::all),
            granted: self.granted.clone(),
        }
    }
}

/// The code of a bundle.
#[derive(Debug, Clone)]
pub enum BundleCode {
    /// QuickJS bytecode from `nsh_js::compile_bytecode`.
    Bytecode(Vec<u8>),
    /// JS source; slower to start than bytecode.
    Source(String),
}

impl Default for Bundle {
    fn default() -> Self {
        Self::source(String::new())
    }
}

impl Bundle {
    /// A bytecode bundle.
    ///
    /// # Safety
    ///
    /// `bytes` must be bytecode from `nsh_js::compile_bytecode` for this
    /// runtime's `BYTECODE_VERSION`, from a trusted source: QuickJS does not
    /// validate bytecode, and loading crafted bytecode corrupts memory. Trusted
    /// are the app's own signed resources, a development server the developer
    /// pointed the host at, and verified packages ([`Bundle::from_package`]).
    pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
        Self {
            code: BundleCode::Bytecode(bytes),
            source_map: None,
            policy: Policy::default(),
            base_url: None,
            chunks: Arc::default(),
            app_id: None,
            system_paths: nsh_core::access::TrustedPaths::default(),
            package: None,
        }
    }

    /// A JS source bundle.
    pub fn source(code: String) -> Self {
        Self {
            code: BundleCode::Source(code),
            source_map: None,
            policy: Policy::default(),
            base_url: None,
            chunks: Arc::default(),
            app_id: None,
            system_paths: nsh_core::access::TrustedPaths::default(),
            package: None,
        }
    }

    /// Selects trusted source/package and home directory anchors. Supplying a
    /// path grants nothing by itself: the manifest and host grant must still
    /// allow the filesystem operation. Only existing absolute directories
    /// are accepted; unavailable anchors are left unset.
    pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
        paths.plugin_dir = trusted_directory(paths.plugin_dir);
        paths.home_dir = trusted_directory(paths.home_dir);
        self.system_paths = paths;
        self
    }

    /// The app's id ([`Bundle::app_id`]), as `nsh.json` or the dev server
    /// gives it.
    pub fn with_app_id(mut self, id: Option<&str>) -> Self {
        self.app_id = id.map(str::to_owned);
        self
    }

    /// Attaches a source map.
    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
        self.source_map = Some(map.into());
        self
    }

    /// Sets the URL relative request URLs resolve against.
    pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Replaces the policy.
    pub fn with_policy(mut self, policy: Policy) -> Self {
        self.policy = policy;
        self
    }

    /// Adds chunks of a split bundle (see [`Bundle::chunks`]).
    pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
        Arc::make_mut(&mut self.chunks).extend(chunks);
        self
    }

    /// Reads a JS source bundle written by `nsh build` (`bundle.js`), plus
    /// `bundle.js.map`, the app's `capabilities.json` and its id
    /// (`app.json` `"id"`) next to it if present. Bytecode (`bundle.nshc`) is refused: files can be replaced, and
    /// only [`Bundle::read_trusted`] (the app's own resources) or a verified
    /// package may load bytecode.
    pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
        if path.extension().is_some_and(|e| e == "nshc") {
            return Err(io::Error::other(
                "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
            ));
        }
        // SAFETY: not bytecode.
        unsafe { Self::read_trusted(path) }
    }

    /// Like [`Bundle::read`], also reading `bundle.nshc` as bytecode.
    ///
    /// # Safety
    ///
    /// A `.nshc` file must be trusted as [`Bundle::bytecode`] requires (e.g.
    /// inside the app's own signed bundle).
    pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
        let bytes = std::fs::read(path)?;
        let bundle = if path.extension().is_some_and(|e| e == "nshc") {
            // SAFETY: guaranteed by the caller.
            unsafe { Bundle::bytecode(bytes) }
        } else {
            Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
        };
        let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
            Ok(map) if !map.is_empty() => bundle.with_source_map(map),
            _ => bundle,
        };
        if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
            bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
        }
        bundle.app_id = read_app_id(&path.with_file_name("app.json"));
        bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
            .parent()
            .map(std::path::Path::to_path_buf);
        Ok(bundle)
    }
}

#[cfg(feature = "js-core")]
impl Bundle {
    /// The bundle of a verified package: its bytecode when it was compiled
    /// for this runtime (else its source), its source map and its declared
    /// capabilities. What a newer signer wrote that this runtime does not
    /// know (header fields, files, capabilities) is logged and left out: an
    /// unknown capability is not granted.
    pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
        for ignored in &package.ignored {
            log::warn!("package {}: ignored {ignored}", package.app.id);
        }
        let bundle = match package.bytecode() {
            // SAFETY: verified: signed by a certified release key, hashed,
            // and compiled for this runtime.
            Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
            None => Bundle::source(package.source.clone()),
        };
        let mut bundle = match &package.source_map {
            Some(map) => bundle.with_source_map(map.clone()),
            None => bundle,
        };
        if let Some(json) = &package.capabilities {
            let (declared, dropped) = Capabilities::from_json_lenient(json)?;
            for dropped in dropped {
                log::warn!("package {}: not granted: {dropped}", package.app.id);
            }
            bundle.policy.declared = Some(declared);
        }
        bundle.app_id = Some(package.app.id.clone());
        bundle.package = Some(Arc::new(PackageInfo {
            id: package.app.id.clone(),
            name: package.app.name.clone(),
            version: package.app.version.clone(),
            build: package.app.build,
            sha256: package.sha256.clone(),
        }));
        Ok(bundle)
    }
}

/// The `"id"` of an `app.json` (`nsh build`'s, a packaged app's).
fn read_app_id(path: &std::path::Path) -> Option<String> {
    let json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()?;
    json.get("id")?.as_str().map(str::to_owned)
}

/// A verified package, unpacked ([`load_package`], [`verify_package`]).
#[cfg(feature = "js-core")]
#[derive(Debug)]
pub struct LoadedPackage {
    /// Its bundle.
    pub bundle: Bundle,
    /// Where its assets are (`asset:/…`).
    pub assets: std::path::PathBuf,
    /// Its app.
    pub app: nsh_package::App,
    /// What accepting it records ([`accept_package`]).
    pub receipt: nsh_package::PackageReceipt,
}

/// Verifies the package `bytes` with `trust`, writes its assets under
/// `assets_root` (`<root>/<app id>/<package hash>/`, once per package) and
/// records its build (older builds of the app are refused from now on):
/// [`verify_package`], then [`accept_package`].
#[cfg(feature = "js-core")]
pub fn load_package(
    trust: &mut nsh_package::TrustStore,
    bytes: &[u8],
    assets_root: &std::path::Path,
) -> Result<LoadedPackage, String> {
    let package = verify_package(trust, bytes, assets_root)?;
    accept_package(trust, &package)?;
    Ok(package)
}

/// [`load_package`] without recording the build: the package is verified as
/// strictly (signature, certificate, revocations, hashes, and its build not
/// older than the highest accepted) and its assets written, but the builds
/// accepted before keep verifying. An embedding app runs it, and once it
/// decided the package is healthy (its first frame drawn, no fatal error for
/// a while) calls [`accept_package`]; if it fails before, the app can go
/// back to the package it ran before, which still verifies.
#[cfg(feature = "js-core")]
pub fn verify_package(
    trust: &nsh_package::TrustStore,
    bytes: &[u8],
    assets_root: &std::path::Path,
) -> Result<LoadedPackage, String> {
    let package = trust
        .verify(bytes, BYTECODE_VERSION)
        .map_err(|e| e.to_string())?;
    let bundle = Bundle::from_package(&package)?;
    let dir = assets_root.join(&package.app.id).join(&package.sha256);
    let done = dir.join(".complete");
    if !done.exists() {
        let assets = dir.join("assets");
        for (path, data) in &package.assets {
            // Paths were checked (relative, no `..`) when the package was read.
            let dest = assets.join(path);
            if let Some(parent) = dest.parent() {
                std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
            }
            std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
        }
        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
        std::fs::write(&done, b"").map_err(|e| e.to_string())?;
    }
    Ok(LoadedPackage {
        bundle,
        assets: dir.join("assets"),
        receipt: package.receipt(),
        app: package.app,
    })
}

/// Rewrites every `bundle.js:LINE:COL` in `text` (a reported error and its
/// stack) to the app source position `source_map` (the bundle's) gives,
/// as the engine does with a bundle's own map: for stacks reported by
/// packages published without their map (`nsh symbolicate`).
#[cfg(feature = "js-core")]
pub fn symbolicate(source_map: &str, text: &str) -> String {
    symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
}

/// Records the build of `package` ([`verify_package`]) in `trust`: older
/// builds of its app are refused from now on. Refused if the package or its
/// release key was revoked since it was verified.
#[cfg(feature = "js-core")]
pub fn accept_package(
    trust: &mut nsh_package::TrustStore,
    package: &LoadedPackage,
) -> Result<(), String> {
    trust
        .accept_receipt(&package.receipt)
        .map_err(|e| e.to_string())
}

/// Parses capabilities in their JSON form (`capabilities.json`, the dev
/// protocol, an embedder's grant).
pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
    let value: serde_json::Value =
        serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
    Capabilities::from_json(&value)
}

impl Bundle {
    /// The declared capabilities from their JSON form, if any.
    pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
        self.policy.declared = json.map(parse_capabilities).transpose()?;
        Ok(self)
    }
}

/// Receives mount batches on the engine thread. Implementations forward
/// them to the UI thread.
pub trait MountSink: Send + 'static {
    /// Called once per commit, in order.
    fn submit(&self, batch: MountBatch);

    /// An error of the app, as text (the message and the stack): the
    /// bundle failed to load, an exception escaped a JS callback, the VM
    /// was stopped. Errors are always logged; development hosts also show
    /// them on screen. What [`MountSink::report`] calls unless it is
    /// implemented.
    fn report_error(&self, _message: &str) {}

    /// An error of the app, with its parts: what went wrong (whether the
    /// app can go on), the message, the stack and the package it came
    /// from. By default, [`MountSink::report_error`] with its text.
    fn report(&self, error: &AppError) {
        self.report_error(&error.to_string());
    }

    /// JS or a component's task asked for a display frame
    /// (`requestAnimationFrame`, `nsh_core::element::next_frame`), or lists have
    /// overscan cells left to bind: call [`EngineControl::frame`] at the
    /// next vsync. Requests are not repeated until that call.
    fn request_frame(&self) {}

    /// A development update ([`EngineControl::hot_update`]) could not be
    /// applied in place: reload the latest full bundle.
    fn hot_update_failed(&self) {}

    /// The engine laid the app out at `size` ([`EngineControl::resize`]):
    /// called after the commit of the turn that applied the resize (if it
    /// changed anything, its batch came before), once per turn, with the
    /// latest size. A platform that waits for the layout at a new size, to
    /// show it in the frame the window takes the size, stops waiting here.
    fn resized(&self, _size: Size<Points>) {}

    /// The engine has handled the first `events` events sent with
    /// [`EngineControl::dispatch_event`]. Called after the commit of the
    /// turn that handled them (what they changed came before), once per
    /// turn. A platform holding typed text for the field an event may focus
    /// gives it to the focused field from here.
    fn handled(&self, _events: u64) {}

    /// The app imports chunk `id` of a split bundle (`import()`), which its
    /// [`Bundle`] does not hold: load it and hand it over with
    /// [`EngineControl::chunk_loaded`] (or [`EngineControl::chunk_failed`]),
    /// from any thread, and return true. False (the default): this host
    /// has no chunks to load, and the import fails.
    fn load_chunk(&self, _id: &str) -> bool {
        false
    }
}

/// Receives what happens to a request started by [`Network::fetch`], in
/// order, on any thread. After [`FetchTask::cancel`] it may still be called
/// (the engine then ignores it).
pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;

/// A request in flight, driven from the engine thread.
pub trait FetchTask: Send {
    /// The next chunk of a streamed body ([`HttpBody::Stream`]), after
    /// [`FetchEvent::BodyWanted`].
    fn send(&mut self, chunk: Vec<u8>);
    /// A streamed body is complete.
    fn finish(&mut self);
    /// Stops (`true`) or resumes (`false`) reading the response body: JS
    /// does not read what arrived (back pressure). Bytes already on their
    /// way may still arrive.
    fn pause(&mut self, paused: bool);
    /// Aborts the request.
    fn cancel(self: Box<Self>);
}

/// The platform's HTTP stack, used by JS `fetch`.
pub trait Network: Send + Sync + 'static {
    /// Starts `request`: its response head, then its body in chunks as they
    /// arrive, are reported to `events`.
    fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
}

/// Reads the app's bundled files (`asset:/…` URIs): from the app's
/// resources, or from the dev server during development. The engine reads
/// the fonts it registers with it, and answers the app's requests of
/// `asset:/` URLs (`fetch`) from it.
pub trait Assets: Send + Sync + 'static {
    /// The bytes of `uri`. Blocking: the engine calls it on its thread for
    /// the fonts it registers, and on a thread of the runtime's blocking
    /// pool for the app's requests (in WebAssembly on its thread).
    fn read(&self, uri: &str) -> Result<Vec<u8>, String>;

    /// Where `uri` is served, for files [`Assets::read`] does not have at
    /// hand: the engine downloads them from there with its network stack
    /// (the web page, which holds only the files it preloaded). `None`, the
    /// default, when `read` is the only way.
    fn url(&self, uri: &str) -> Option<String> {
        let _ = uri;
        None
    }

    /// Where `asset:/` URIs resolve, when it is a directory or a URL the
    /// image loader can read itself: the core's image loads ([`svg`]s)
    /// then share the platform's cache entries. `None`: through
    /// [`Assets::read`].
    ///
    /// [`svg`]: nsh_core::element::svg
    #[cfg(not(target_arch = "wasm32"))]
    fn base(&self) -> Option<nsh_core::image::loader::AssetBase> {
        None
    }
}

/// Engine settings.
#[derive(Clone)]
pub struct EngineConfig {
    /// The app.
    pub app: App,
    /// Initial size of the root view.
    pub viewport: Size<Points>,
    /// Log per-commit timings (target `nsh::perf`, level info).
    pub trace: bool,
    /// The HTTP stack behind `fetch`; without one, requests fail.
    pub network: Option<Arc<dyn Network>>,
    /// The host transport for WebSockets, including the browser WebSocket API.
    pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
    /// Refuses the app's connections (`net` sockets and both WebSocket
    /// APIs) with the error it gives for what they connect to, before they
    /// reach the network: a test's, which reaches it only when the test
    /// asks (`nsh test`'s `network: "live"`). `None`: they connect.
    pub refuse_connections: Option<nsh_core::element::RefuseConnections>,
    /// App-private host filesystem service (for browser storage).
    pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
    /// Source of bundled files such as fonts; without one, they fail to load.
    pub assets: Option<Arc<dyn Assets>>,
    /// The surface's initial environment (its `window` is `viewport`).
    pub environment: Environment,
    /// Height of the platform's screen header bar, normal and with a large
    /// title (status bar excluded).
    pub header_heights: (Points, Points),
    /// The JS VM's resource limits (a JS app's; Rust code has none).
    pub limits: Limits,
    /// The UI sets JS imports (`nsh_base::registry()` by default, the app's
    /// own): their Rust components and modules. A Rust app's
    /// components need no registration.
    pub ui_sets: Vec<nsh_core::element::Registry>,
    /// The tokio runtime the components' async tasks use (timers, IO,
    /// background work); `None`: one shared by the engines of the process.
    pub runtime: Option<tokio::runtime::Handle>,
    /// Where apps keep their data: each app in `<data_dir>/<app id>`
    /// ([`App::app_id`]; `default` without one), its storage
    /// (`nsh/storage`) in `storage.json` there. The platform's: the
    /// system's data directory ([`data_dir`]) for apps of their own,
    /// `…/nsh` in an embedding app's. `None`: nothing is kept.
    pub data_dir: Option<std::path::PathBuf>,
    /// Where the app's caches are kept and how much each keeps: the engine
    /// opens them in `<root>/<app id>/<kind>` ([`Engine::image_cache`]).
    /// [`EngineConfig::new`]: none.
    pub cache: CacheOptions,
    /// The app's storage, overriding the one [`EngineConfig::data_dir`]
    /// names (the browser's `localStorage`, an embedder's own); `None`
    /// with no data directory either: in memory, for the engine's life.
    pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
    /// The time the app runs on: the system's, or a manual clock a test
    /// moves (`nsh_core::time::Clock::manual`), which its timers, frames
    /// and `Date` follow.
    pub clock: Clock,
    /// What the host gives this engine's Rust code, which its UI sets'
    /// functions and components read while it runs them
    /// (`nsh_core::element::engine_context`): a host serving several engines
    /// tells them apart by it.
    pub context: EngineContext,
    /// Values of the environment kept whatever the platform reports (a
    /// test's locale, reduced motion and safe area: `nsh test --target`).
    pub pinned: EnvironmentPins,
    /// Serves the app's clipboard calls in place of the platform's
    /// clipboard (a test's own: `nsh test --target`); `None`: the
    /// platform's.
    pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
    /// The embedding app's channel with the app (`nsh/host`): its launch
    /// parameters, its events and its handlers of the app's calls and
    /// posts. A view keeps one for every app it runs; the default is a
    /// channel of the engine's own, with none of them.
    pub host: HostChannel,
    /// Answers the app's picks (`Picker.pickImages`) in place of the
    /// platform's picker: the embedding app's own picker, or a test's
    /// files; `None`: the platform's.
    pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
    /// Recognizes the app's speech (`Speech.start`) instead of the
    /// platform's recognizer: the embedding app's own, or a test's fake
    /// (`nsh_testing`'s). `None` (the default): the platform's, where it
    /// has one (`Environment::speech`).
    pub speech: Option<Arc<dyn nsh_core::speech::SpeechBackend>>,
}

/// Values of the environment an engine keeps whatever its platform reports
/// ([`EngineConfig::pinned`]); `None` leaves the platform's.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[non_exhaustive]
pub struct EnvironmentPins {
    /// The locale (`Environment::locale`).
    pub locale: Option<nsh_core::platform::Locale>,
    /// Whether the user asked for less motion
    /// (`Environment::reduce_motion`).
    pub reduce_motion: Option<bool>,
    /// The safe area insets (`Environment::safe_area`).
    pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
}

impl EnvironmentPins {
    /// `environment` with these values in place of the platform's.
    pub fn apply(&self, environment: &mut Environment) {
        if let Some(locale) = self.locale {
            environment.locale = locale;
        }
        if let Some(reduce_motion) = self.reduce_motion {
            environment.reduce_motion = reduce_motion;
        }
        if let Some(safe_area) = self.safe_area {
            environment.safe_area = safe_area;
        }
    }
}

fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
    let path = path.filter(|path| path.is_absolute())?;
    nsh_core::access::canonicalize(&path)
        .ok()
        .filter(|path| path.is_dir())
}

/// Native hosts choose these anchors before any application JavaScript runs.
#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
    let mut paths = bundle.system_paths.clone();
    paths.plugin_dir = trusted_directory(paths.plugin_dir);
    paths.home_dir = trusted_directory(paths.home_dir);
    if paths.home_dir.is_none() {
        paths.home_dir = ["HOME", "USERPROFILE"]
            .into_iter()
            .filter_map(std::env::var_os)
            .map(std::path::PathBuf::from)
            .find_map(|path| trusted_directory(Some(path)));
    }
    // Local `nsh run` passes its canonical entry directory directly to the
    // native child process. Remote dev messages never contain this field.
    // A packaged/hardened bundle cannot inherit a development source anchor.
    if paths.plugin_dir.is_none() && !bundle.policy.harden {
        paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
            .map(std::path::PathBuf::from)
            .and_then(|path| trusted_directory(Some(path)));
    }
    paths
}

impl EngineConfig {
    /// `app` on a phone-sized surface (390 × 844 points, iOS's header
    /// heights) with nothing else: no network, assets, data directory or
    /// UI sets, the default environment and limits, the shared runtime.
    /// Set the fields that matter over it (`EngineConfig { ui_sets,
    /// ..EngineConfig::new(app) }`). There is no `Default`: an engine has
    /// no app to run by default.
    pub fn new(app: impl Into<App>) -> Self {
        Self {
            app: app.into(),
            viewport: Size::new(Points(390.0), Points(844.0)),
            trace: false,
            network: None,
            websocket: None,
            refuse_connections: None,
            filesystem: None,
            assets: None,
            environment: Environment::default(),
            header_heights: (Points(44.0), Points(96.0)),
            limits: Limits::default(),
            ui_sets: Vec::new(),
            runtime: None,
            data_dir: None,
            cache: CacheOptions::off(),
            storage: None,
            clock: Clock::system(),
            context: EngineContext::default(),
            pinned: EnvironmentPins::default(),
            clipboard: None,
            host: HostChannel::default(),
            picker: None,
            speech: None,
        }
    }
}

/// The storage of the app `config` runs: [`EngineConfig::storage`], or a
/// file in its directory of [`EngineConfig::data_dir`].
fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
    if let Some(storage) = &config.storage {
        return Some(storage.clone());
    }
    #[cfg(not(target_arch = "wasm32"))]
    if let Some(root) = &config.data_dir {
        let dir = root.join(app_dir_name(config.app.app_id()));
        return Some(FileStorage::open(dir));
    }
    None
}

#[cfg(not(target_arch = "wasm32"))]
/// The runtime of components' tasks when the embedder gives none: a few
/// threads, made on first use, shared by every engine (like a thread pool,
/// it holds no engine's state).
fn shared_runtime() -> tokio::runtime::Handle {
    static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
    RUNTIME
        .get_or_init(|| {
            tokio::runtime::Builder::new_multi_thread()
                .worker_threads(2)
                .thread_name("nsh-tasks")
                .enable_all()
                .build()
                .expect("the tasks' runtime starts")
        })
        .handle()
        .clone()
}

impl std::fmt::Debug for EngineConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EngineConfig")
            .field("app", &self.app)
            .field("viewport", &self.viewport)
            .field("trace", &self.trace)
            .field("network", &self.network.is_some())
            .field("assets", &self.assets.is_some())
            .field("environment", &self.environment)
            .field("header_heights", &self.header_heights)
            .field("limits", &self.limits)
            .field("ui_sets", &self.ui_sets)
            .field("clock", &self.clock)
            .field("context", &self.context)
            .field("pinned", &self.pinned)
            .field("clipboard", &self.clipboard.is_some())
            .field("host", &self.host)
            .field("picker", &self.picker.is_some())
            .field("speech", &self.speech.is_some())
            .finish()
    }
}

/// How many times [`EngineControl::advance_clock`] stops for what comes
/// due at most (sinon's fake timers stop at 1000 for one `runAll`; this
/// leaves room for a long run of 60 Hz intervals).
const MAX_ADVANCE_ROUNDS: usize = 100_000;

/// How many times [`EngineControl::flush`] runs what is queued again when
/// running it queued more (a task woken by another, a request answered at
/// once): a task that keeps waking itself leaves the engine busy.
const MAX_FLUSH_ROUNDS: usize = 64;

enum Message {
    Event(NodeId, EventKind, EventPayload),
    Scroll(NodeId, Point<Points>, u32),
    Kept(Vec<NodeId>),
    InputScroll(NodeId, Point<Points>, Size<Points>, Size<Points>),
    Zoom(NodeId, f32),
    ComponentSize(NodeId, Size<Points>),
    AnimationsFinished(Vec<nsh_core::animation::Finished>),
    Resize(Size<Points>),
    /// A component's task was woken: it runs in the loop.
    Wake,
    Environment(Environment),
    RootSize(NodeId, Size<Points>, EdgeInsets),
    ScreenHeader(NodeId, Option<Points>),
    Frame,
    States(NodeId, u16),
    FontsChanged,
    Remount,
    /// An event of a request (by the hop it is for: events of a hop the
    /// engine left are dropped).
    Fetch(Requester, u64, FetchEvent),
    /// Hop `.1` of the request `.2` for a bundled file read it on a
    /// blocking thread ([`Net::asset`]): its bytes, or why there are none.
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    AssetRead(Requester, u64, HttpRequest, Result<Vec<u8>, String>),
    Hot(HotUpdate),
    /// A chunk [`MountSink::load_chunk`] was asked for, or why it could
    /// not be loaded (its id and the message).
    Chunk(Result<Chunk, (String, String)>),
    Perf(Option<Arc<perf::PerfMonitor>>),
    /// The embedding app's design tokens.
    Tokens(Option<Box<Tokens>>),
    /// The embedding app's event (`nsh/host`'s `host.on`): its name and
    /// data.
    HostEvent(String, nsh_core::JsonValue),
    /// The embedding app's answer to call `.0` (`host.call`).
    HostReply(u64, Result<nsh_core::JsonValue, String>),
    /// The embedding app's URL handler answered URL request `id`: it took
    /// the URL, or the platform opens it.
    UrlHandled {
        id: u32,
        url: String,
        handled: bool,
    },
    /// Moves a manual clock forward by this much, then calls back.
    Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
    /// Runs what is queued and due now, then calls back with whether the
    /// engine is idle ([`EngineControl::flush`]).
    Flush(Box<dyn FnOnce(bool) + Send>),
    /// Sent by a dropped [`Engine`] (there is none in WebAssembly).
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    Shutdown,
}

/// A development update that replaces the app's changed modules in place,
/// keeping the JS context, the views and the state of everything else
/// (made by `nsh_bundler::HotBundle::patch`).
#[derive(Debug, Clone)]
pub struct HotUpdate {
    /// Script name in stack traces, unique per update (e.g. `hot-3.js`).
    pub name: String,
    /// The script.
    pub code: String,
    /// Its source map (JSON).
    pub source_map: Option<Arc<str>>,
}

/// Rounds of "list asks for items -> JS renders them -> layout" folded into
/// one frame. Bounded so a list that never settles cannot stall the engine;
/// leftovers continue next frame.
const MAX_LIST_ROUNDS: usize = 8;

/// The overscan a turn binds: cells until their ops reach this many (about
/// as many mount items, which the main thread applies in one go) or their
/// JS takes [`PACED_BIND_TIME`], at least one. A fast scroll asks for a
/// screen of cells at once and each bind rebuilds a cell's subtree; what
/// shows (the viewport, the leading edge, cells whose item moved) binds
/// regardless, the rest on the next display frames.
const PACED_BIND_OPS: usize = 150;
/// See [`PACED_BIND_OPS`].
const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);

/// A cheap, cloneable handle for sending input to the engine from any thread.
#[derive(Clone)]
pub struct EngineControl {
    tx: Sender<Message>,
}

impl EngineControl {
    /// Delivers an input event (and its data) to a node.
    pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
        let _ = self.tx.send(Message::Event(id, event, payload));
    }

    /// Reports the content offset of a scroll view or list, and how many
    /// scrolls the core asked for (`MountItem::ScrollBy` items and
    /// `Command::ScrollTo` commands for the view) were applied before it.
    /// Cheap to call on every scroll frame: offsets are coalesced per
    /// engine frame.
    pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
        let _ = self.tx.send(Message::Scroll(id, offset, applied));
    }

    /// Keeps the virtual list rows holding `nodes` rendered wherever they
    /// scroll (`Core::set_kept`): the ends of a text selection. Replaces
    /// the last call's; none releases them.
    pub fn keep_rendered(&self, nodes: Vec<NodeId>) {
        let _ = self.tx.send(Message::Kept(nodes));
    }

    /// Reports how far a multiline input's text scrolled: its offset, the
    /// size of the text it scrolls and of its viewport. Sent while a
    /// built-in bar takes the place of its indicator
    /// (`InputConfig::replaced`), on every change.
    pub fn input_scroll(
        &self,
        id: NodeId,
        offset: Point<Points>,
        content: Size<Points>,
        viewport: Size<Points>,
    ) {
        let _ = self
            .tx
            .send(Message::InputScroll(id, offset, content, viewport));
    }

    /// Reports the zoom scale of a zoomable scroll view (before the offset
    /// the zoom changed); `onScroll` carries it.
    pub fn zoom(&self, id: NodeId, scale: f32) {
        let _ = self.tx.send(Message::Zoom(id, scale));
    }

    /// A registered native component's own size (points): it is laid out at
    /// it where its style leaves a dimension open.
    pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
        let _ = self.tx.send(Message::ComponentSize(id, size));
    }

    /// Reports native animations that finished or were interrupted.
    pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
        let _ = self.tx.send(Message::AnimationsFinished(finished));
    }

    /// Resizes the root view.
    pub fn resize(&self, size: Size<Points>) {
        let _ = self.tx.send(Message::Resize(size));
    }

    /// Reports a change of the surface's environment (safe area, keyboard,
    /// appearance...).
    pub fn set_environment(&self, environment: Environment) {
        let _ = self.tx.send(Message::Environment(environment));
    }

    /// The platform presents root `id` (a modal) at `size`, with `insets`
    /// of it covered by system UI.
    pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
        let _ = self.tx.send(Message::RootSize(id, size, insets));
    }

    /// The platform measured where the content of screen `id` starts below
    /// its header (`None`: let the core estimate it).
    pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
        let _ = self.tx.send(Message::ScreenHeader(id, height));
    }

    /// Applies a development update in place. When it cannot be applied,
    /// [`MountSink::hot_update_failed`] asks the platform to reload.
    pub fn hot_update(&self, update: HotUpdate) {
        let _ = self.tx.send(Message::Hot(update));
    }

    /// Hands over the chunk [`MountSink::load_chunk`] asked for: the
    /// dynamic imports waiting for it continue.
    pub fn chunk_loaded(&self, chunk: Chunk) {
        let _ = self.tx.send(Message::Chunk(Ok(chunk)));
    }

    /// Chunk `id` could not be loaded: the dynamic imports waiting for it
    /// fail with `message` (a later import asks for it again).
    pub fn chunk_failed(&self, id: String, message: String) {
        let _ = self.tx.send(Message::Chunk(Err((id, message))));
    }

    /// A display frame began, after [`MountSink::request_frame`]: runs the
    /// `requestAnimationFrame` callbacks and the tasks waiting for it.
    pub fn frame(&self) {
        let _ = self.tx.send(Message::Frame);
    }

    /// Moves the engine's manual clock ([`EngineConfig::clock`]) forward
    /// by `by`: the timers and tasks due meanwhile run in the order they
    /// come due, each at its time, with what they make due in turn, and the
    /// clock's alarms (a response it holds back) go off on the way. Then
    /// `done` runs, after the batches of what ran were submitted. With the
    /// system's clock it only runs `done`.
    pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
        let _ = self.tx.send(Message::Advance(by, Box::new(done)));
    }

    /// Runs everything sent to the engine before it and everything due on
    /// its clock now (timers, woken tasks, answers that came at once), with
    /// what they queue in turn, without moving the clock. Then `done` runs,
    /// after the batches of what ran were submitted, with whether the
    /// engine is idle: nothing is left to run and no request waits for
    /// the network. False when work keeps coming (a task that keeps waking
    /// itself) or a request is in flight, whose answer comes later from
    /// elsewhere. A headless driver on a manual clock settles a step with
    /// it, instead of waiting for the batches to stop for a while.
    pub fn flush(&self, done: impl FnOnce(bool) + Send + 'static) {
        let _ = self.tx.send(Message::Flush(Box::new(done)));
    }

    /// Reports the interaction states of view `id` that the core asked to
    /// track ([`nsh_core::MountItem::TrackStates`]; bits of
    /// [`nsh_core::tailwind::state`]). Class styles that depend on them
    /// (`active:`, `hover:`, `focus:`) update without JS.
    pub fn set_states(&self, id: NodeId, states: u16) {
        let _ = self.tx.send(Message::States(id, states));
    }

    /// Fonts the platform loads asynchronously became usable (on the web,
    /// a `FontFace` finished loading): text measured with a fallback font
    /// is measured again.
    pub fn fonts_changed(&self) {
        let _ = self.tx.send(Message::FontsChanged);
    }

    /// The platform's views get everything again and text is measured
    /// again: the unit the platform converts values with changed (Android's
    /// density). Send the new environment and size too.
    pub fn remount(&self) {
        let _ = self.tx.send(Message::Remount);
    }

    /// Records the engine's commits into `monitor` from now on (`None`:
    /// stops). Measuring costs nothing while no monitor is installed.
    pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
        let _ = self.tx.send(Message::Perf(monitor));
    }

    /// Sets the embedding app's design tokens (`nsh-base`'s theme's),
    /// which the app renders with instead of its own (`None`: its own
    /// again; [`Core::set_host_tokens`]). Sent from
    /// [`Engine::start_with`]'s `setup`, they are in the first frame.
    pub fn set_tokens(&self, tokens: Option<Tokens>) {
        let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
    }
}

#[cfg(not(target_arch = "wasm32"))]
/// A running engine. Dropping it stops the thread.
pub struct Engine {
    control: EngineControl,
    thread: Option<std::thread::JoinHandle<()>>,
    /// Serializes shutdown with the embedding app's sends.
    host: HostChannel,
    /// Interrupts running JS when the engine stops.
    stop: Arc<std::sync::atomic::AtomicBool>,
    /// The app's disk cache of downloaded images.
    image_cache: Option<nsh_core::image::DiskCache>,
}

#[cfg(not(target_arch = "wasm32"))]
impl Engine {
    /// Starts the engine thread. `make_text_engine` runs on that thread.
    pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
    where
        M: TextEngine + 'static,
        F: FnOnce() -> M + Send + 'static,
        S: MountSink,
    {
        Self::start_with(config, make_text_engine, sink, |_| {})
    }

    /// [`Engine::start`], with `setup` sending input before the engine
    /// starts: what it sends (a theme, the environment) is applied before
    /// the first frame.
    pub fn start_with<M, F, S>(
        config: EngineConfig,
        make_text_engine: F,
        sink: S,
        setup: impl FnOnce(&EngineControl),
    ) -> io::Result<Engine>
    where
        M: TextEngine + 'static,
        F: FnOnce() -> M + Send + 'static,
        S: MountSink,
    {
        let image_cache = config.cache.open_images(config.app.app_id());
        let (tx, rx) = crossbeam_channel::unbounded();
        setup(&EngineControl { tx: tx.clone() });
        let engine_tx = tx.clone();
        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let engine_stop = stop.clone();
        let host = config.host.clone();
        let thread = std::thread::Builder::new()
            .name("nsh-engine".into())
            .stack_size(ENGINE_STACK_SIZE)
            .spawn(move || run(config, make_text_engine(), sink, engine_tx, rx, engine_stop))?;
        Ok(Engine {
            control: EngineControl { tx },
            thread: Some(thread),
            host,
            stop,
            image_cache,
        })
    }

    /// The disk cache of the images the app downloads
    /// ([`EngineConfig::cache`]; `None`: none). The platform's image loader
    /// routes the app's `http(s)` images through it.
    pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
        self.image_cache.clone()
    }

    /// A handle for sending input from other threads.
    pub fn control(&self) -> EngineControl {
        self.control.clone()
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for Engine {
    fn drop(&mut self) {
        // Dropped on the platform's main thread: a script still running is
        // aborted rather than waited for.
        self.host.shutdown(&self.control.tx, &self.stop);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
/// The engine thread turns input into frames: it is as latency-critical as
/// the UI thread. Without this, Apple platforms may run it on efficiency
/// cores at low clock speeds.
fn raise_thread_priority() {
    #[cfg(target_vendor = "apple")]
    // SAFETY: changes the QoS class of the calling thread only.
    unsafe {
        libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn run<M: TextEngine + 'static, S: MountSink>(
    config: EngineConfig,
    text_engine: M,
    sink: S,
    tx: Sender<Message>,
    rx: Receiver<Message>,
    stop: Arc<std::sync::atomic::AtomicBool>,
) {
    raise_thread_priority();
    // The thread's time is the engine's from its first line of JS on.
    let _clock = config.clock.enter();
    let _context = config.context.enter();
    let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
        return;
    };
    loop {
        let message = match driver.deadline() {
            Some(deadline) => match rx.recv_deadline(deadline) {
                Ok(message) => Some(message),
                Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
            },
            None => match rx.recv() {
                Ok(message) => Some(message),
                Err(_) => return,
            },
        };
        let started = driver.state.perf.is_some().then(Instant::now);
        if let Some(message) = message {
            if !driver.handle(message, &rx) {
                return;
            }
            // Coalesce everything already queued into this frame.
            while let Ok(message) = rx.try_recv() {
                if !driver.handle(message, &rx) {
                    return;
                }
            }
        }
        driver.turn();
        driver.state.record_perf(started);
        if rx.is_empty() {
            driver.collect_if_idle();
        }
    }
}

/// An engine driven by its host's event loop instead of a thread of its
/// own: the browser's main thread in WebAssembly, where there are no
/// threads to block. Input sent through its [`EngineControl`] is handled
/// at the next [`LocalEngine::pump`].
pub struct LocalEngine<M: TextEngine + 'static> {
    /// Dropped while this engine's context is the thread's. The guard
    /// would otherwise end when `drop` returns, before the fields drop.
    driver: ManuallyDrop<Driver<M>>,
    rx: Receiver<Message>,
    control: EngineControl,
    /// The host's wake ([`LocalEngine::set_wake`]).
    wake: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Set while [`LocalEngine::pump`] runs: what it wakes it runs itself,
    /// so the host's wake is not called for it.
    pumping: Arc<std::sync::atomic::AtomicBool>,
}

impl<M: TextEngine + 'static> LocalEngine<M> {
    /// Starts the app (its first frame goes to `sink` before this returns);
    /// `None` if it could not start (reported to `sink`).
    pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
        let (tx, rx) = crossbeam_channel::unbounded();
        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let control = EngineControl { tx: tx.clone() };
        let _clock = config.clock.enter();
        let _context = config.context.enter();
        let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
        Some(LocalEngine {
            driver: ManuallyDrop::new(driver),
            rx,
            control,
            wake: None,
            pumping: Arc::default(),
        })
    }

    /// A handle for sending input.
    pub fn control(&self) -> EngineControl {
        self.control.clone()
    }

    /// Calls `wake` when there is work outside a [`pump`](Self::pump): a
    /// component task is woken or Rust posts a JS call while no pump runs
    /// (a callback of the host's completing what a task waits for, such as
    /// a WebSocket message through wasm-bindgen), once per wake-up, or a
    /// pump ends with work its bound left. The host then calls `pump` soon,
    /// instead of only at the deadline it returned or at the next input.
    /// What a pump wakes itself (a task waking another, a reply it hands
    /// over) it runs without calling `wake`.
    pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
        let tx = self.control.tx.clone();
        let pumping = self.pumping.clone();
        let host = wake.clone();
        let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
            let _ = tx.send(Message::Wake);
            // After the send: a pump that is ending sees the message
            // (`pump` clears the flag, then looks at the queue).
            if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
                host();
            }
        });
        self.driver.state.core.set_task_notify(notify.clone());
        self.driver.posts.set_notify(notify);
        self.wake = Some(wake);
    }

    /// Serves `ui_sets` (a superset of the config's, after a UI set or
    /// part was registered while the app runs: the web runtime's late
    /// gates) to what is mounted from now on.
    pub fn extend_ui_sets(&mut self, ui_sets: &[nsh_core::element::Registry]) {
        let sets: Vec<_> = nsh_core::runtime::registries()
            .iter()
            .chain(ui_sets)
            .cloned()
            .collect();
        self.driver
            .state
            .core
            .extend_components(nsh_core::element::Registry::merged(&sets));
    }

    /// Handles the input sent since the last call, runs what is due
    /// (timers, tasks) and commits. Returns when to call again at the
    /// latest (sooner if input arrives); `None`: only for input.
    pub fn pump(&mut self) -> Option<Instant> {
        let _clock = self.driver.clock.enter();
        let _context = self.driver.context.enter();
        self.pumping
            .store(true, std::sync::atomic::Ordering::SeqCst);
        // Bounded: messages sent while handling (a task waking another)
        // are handled in the same call, a loop that never settles is not.
        for _ in 0..4 {
            let started = self.driver.state.perf.is_some().then(Instant::now);
            while let Ok(message) = self.rx.try_recv() {
                self.driver.handle(message, &self.rx);
            }
            self.driver.turn();
            self.driver.state.record_perf(started);
            if self.rx.is_empty() {
                break;
            }
        }
        self.driver.collect_if_idle();
        self.pumping
            .store(false, std::sync::atomic::Ordering::SeqCst);
        // What the bound left waits for the next pump: soon, not at the
        // deadline.
        if !self.rx.is_empty()
            && let Some(wake) = &self.wake
        {
            wake();
        }
        self.driver.deadline()
    }
}

impl<M: TextEngine + 'static> Drop for LocalEngine<M> {
    fn drop(&mut self) {
        // Cancelling tasks and dropping what they captured reads this
        // engine's context. `run` keeps its guard across the driver's
        // drop; this path enters for the drop itself.
        let _context = self.driver.context.enter();
        // SAFETY: `driver` is dropped once, here. `ManuallyDrop` keeps
        // the field drop from dropping it again.
        unsafe { ManuallyDrop::drop(&mut self.driver) };
    }
}

/// One engine's state and the work of one wake-up, whoever drives it.
struct Driver<M: TextEngine + 'static> {
    state: State<Rc<M>>,
    script: Option<Script>,
    sink: Rc<dyn MountSink>,
    assets: Option<Arc<dyn Assets>>,
    /// A VM stopped for good (out of memory, over a quota) is reported
    /// once; its views stay as they were and no JS runs any more.
    stopped: bool,
    last_gc: Instant,
    /// When a message or a due timer last gave the engine work
    /// ([`IDLE_GC_QUIET`]).
    last_active: Instant,
    /// The queue of the JS calls Rust posts: its notify wakes the engine,
    /// as the core's task notify does ([`LocalEngine::set_wake`]).
    posts: nsh_core::element::Posts,
    /// The engine's clock, its thread's ([`Clock::enter`]).
    clock: Clock,
    /// The host's context, its thread's ([`EngineContext::enter`]).
    context: EngineContext,
    /// When the last display frame ran, on a clock that moves with the
    /// display's frames: the next one comes a frame after it.
    last_frame: Option<Instant>,
    /// The engine's attachment to the embedding app's channel: its events
    /// come here while the engine runs.
    _host: host_channel::HostAttachment,
}

impl<M: TextEngine + 'static> Driver<M> {
    /// Sets up the core, starts the app and submits its first frame.
    fn start(
        mut config: EngineConfig,
        text_engine: M,
        sink: Rc<dyn MountSink>,
        tx: Sender<Message>,
        rx: &Receiver<Message>,
        stop: Arc<std::sync::atomic::AtomicBool>,
    ) -> Option<Self> {
        config.pinned.apply(&mut config.environment);
        #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
        let system_tx = tx.clone();
        #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
        let host_bridge = config.host.bridge(tx.clone());
        let host_tx = tx.clone();
        let text_engine = Rc::new(text_engine);
        let access = Arc::new(match &config.app {
            App::Js(bundle) => bundle.policy.access(),
            // Native code is trusted: it reaches what the platform allows.
            App::Rust(_) => Policy::default().access(),
        });
        let mut core = Core::new(text_engine.clone(), config.viewport);
        // The runtime's components (`nsh/mobile`'s `TabBar`) and the UI
        // sets the host serves.
        let sets: Vec<_> = nsh_core::runtime::registries()
            .iter()
            .chain(&config.ui_sets)
            .cloned()
            .collect();
        core.set_components(nsh_core::element::Registry::merged(&sets));
        // The JS calls Rust posts queue in one place, which the core
        // releases in order with the ops (a post during a synchronous call)
        // and the script runs.
        let posts = nsh_core::element::Posts::new();
        core.set_posts(posts.clone());
        if let App::Js(_) = &config.app {
            // Only JS is limited (Rust code is as trusted as the platform).
            core.set_max_nodes(config.limits.max_nodes);
        }
        core.set_access(access.clone());
        #[cfg(not(target_arch = "wasm32"))]
        core.set_image_context(nsh_core::image::loader::Context {
            asset_base: config.assets.as_ref().and_then(|a| a.base()),
            read_asset: config.assets.clone().map(|assets| {
                Arc::new(move |uri: &str| assets.read(uri)) as nsh_core::image::loader::ReadAsset
            }),
            access: access.clone(),
            // The same cache as the platform's ([`Engine::image_cache`]).
            disk: config.cache.open_images(config.app.app_id()),
            // The platform's, if it set one ([`nsh_core::image::loader::set_transport`]).
            transport: None,
        });
        core.set_storage(app_storage(&config));
        core.set_clipboard(config.clipboard.clone());
        core.set_picker(config.picker.clone());
        core.set_speech(config.speech.clone());
        core.set_font_scale(config.environment.font_scale);
        core.set_class_environment(class_environment(&config.environment));
        core.set_header_heights(config.header_heights.0, config.header_heights.1);
        core.set_safe_area(insets(&config.environment));
        core.set_environment(ui_environment(&config.environment, config.viewport));
        // WebAssembly has no threads for a runtime: tasks' timers are
        // `nsh_core::time`'s there, fired by the driver.
        #[cfg(not(target_arch = "wasm32"))]
        let runtime = config.runtime.clone().unwrap_or_else(shared_runtime);
        #[cfg(not(target_arch = "wasm32"))]
        core.set_task_runtime(runtime.clone());
        // A Rust app's theme and fonts come with its root (a JS app's from
        // its bundle).
        if let App::Rust(root) = &config.app {
            if let Some(tokens) = root.tokens_ref() {
                core.set_tokens(tokens.clone());
            }
            if let Some(appearance) = root.appearance_ref() {
                core.set_appearance(appearance);
            }
            for font in root.fonts() {
                if let Err(err) = core.register_font(font) {
                    log::error!("font failed: {err}");
                    sink.report(&AppError::new(
                        AppErrorKind::Asset,
                        &format!("font failed: {err}"),
                    ));
                }
            }
        }
        // The fonts the UI sets' crates ship, before anything is measured.
        let fonts = config
            .ui_sets
            .iter()
            .flat_map(nsh_core::element::Registry::asset_files)
            .filter(|file| file.kind == nsh_core::element::AssetKind::Font);
        for font in fonts {
            let result = match config.assets.as_deref() {
                Some(assets) => assets.read(font.uri),
                None => Err("this host cannot load assets".to_owned()),
            }
            .and_then(|data| core.register_font(&data));
            if let Err(err) = result {
                log::error!("font failed: {}: {err}", font.uri);
                let message = format!("font failed: {}: {err}", font.uri);
                let package = match &config.app {
                    App::Js(bundle) => bundle.package.clone(),
                    App::Rust(_) => None,
                };
                sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
            }
        }
        // A task woken on any thread wakes the loop, and so does a JS call
        // Rust queues.
        let wake = tx.clone();
        core.set_task_notify(Arc::new(move || {
            let _ = wake.send(Message::Wake);
        }));
        let wake = tx.clone();
        posts.set_notify(Arc::new(move || {
            let _ = wake.send(Message::Wake);
        }));
        // The embedding app's tokens sent before the start
        // (`Engine::start_with`) are there as the bundle evaluates, so its
        // first render reads them; the rest comes after it, in order.
        let mut early = Vec::new();
        while let Ok(message) = rx.try_recv() {
            match message {
                Message::Tokens(tokens) => core.set_host_tokens(tokens.map(|t| *t)),
                message => early.push(message),
            }
        }
        let js_tokens = core.tokens().clone();
        let state = State {
            core,
            js_tokens,
            frame_requested: false,
            ops: Vec::new(),
            binds: Vec::new(),
            events: Vec::new(),
            trace: config.trace,
            perf: None,
            perf_commit: perf::CommitTiming::default(),
            committed_since_gc: false,
            hot: Vec::new(),
            scroll_events: FxHashMap::default(),
            touch_move: None,
            mouse_moves: Vec::new(),
            mouse_moved: None,
            sets_seen: FxHashMap::default(),
            resized: None,
            events_handled: 0,
            events_reported: 0,
            pinned: config.pinned,
            host: config.host.clone(),
            url_opens: Vec::new(),
            net: Net {
                network: config.network.clone(),
                tx,
                queue: NetworkQueue::default(),
                inflight: FxHashMap::default(),
                tasks: Vec::new(),
                abandoned: Vec::new(),
                access: access.clone(),
                hops: 0,
                assets: config.assets.clone(),
                #[cfg(not(target_arch = "wasm32"))]
                runtime,
            },
        };

        let mut environment = config.environment;
        environment.window = config.viewport;
        let start = Instant::now();
        let mut driver = Driver {
            state,
            script: None,
            sink: sink.clone(),
            assets: config.assets.clone(),
            stopped: false,
            last_gc: Instant::now(),
            last_active: Instant::now(),
            posts: posts.clone(),
            clock: config.clock.clone(),
            context: config.context.clone(),
            last_frame: None,
            _host: config.host.attach(host_tx, rx.clone()),
        };
        let eval_us = match &config.app {
            App::Js(bundle) => {
                #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
                let system = {
                    script::SystemConfig {
                        access: (*access).clone(),
                        websocket: config.websocket.clone(),
                        refuse_connections: config.refuse_connections.clone(),
                        filesystem: config.filesystem.clone(),
                        data_dir: config
                            .data_dir
                            .as_ref()
                            .map(|root| root.join(app_dir_name(config.app.app_id()))),
                        paths: bundle_system_paths(bundle),
                        wake: Arc::new(move || {
                            let _ = system_tx.send(Message::Wake);
                        }),
                        host: Rc::new(host_bridge),
                    }
                };
                #[cfg(not(any(
                    feature = "js-core",
                    all(feature = "browser", target_arch = "wasm32")
                )))]
                let system = script::SystemConfig;
                let (script, eval_us) = Script::start(
                    bundle,
                    config.limits,
                    &config.ui_sets,
                    posts,
                    &environment,
                    driver.state.js_tokens.clone(),
                    driver.state.core.theme_tokens(),
                    text_engine,
                    stop,
                    sink,
                    system,
                )?;
                driver.script = Some(script);
                eval_us
            }
            App::Rust(root) => {
                driver.state.core.mount_root(root);
                0
            }
        };
        let Driver {
            state,
            script,
            sink,
            assets,
            ..
        } = &mut driver;
        let script = script.as_ref();
        // What was sent before the start (`Engine::start_with`) is in the
        // first frame; a move of the clock comes after it.
        let mut moves = Vec::new();
        let pending = early
            .into_iter()
            .chain(std::iter::from_fn(|| rx.try_recv().ok()));
        for message in pending {
            if let Message::Advance(..) | Message::Flush(..) = message {
                moves.push(message);
            } else if !handle(script, state, message) {
                return None;
            }
        }
        // Workers may finish while the first bundle evaluates. Deliver their
        // completions even when the startup drain already consumed their wakeup.
        if let Some(script) = script {
            script.run_system();
        }
        state.load_fonts(script, assets.as_deref(), &**sink);
        if let Some(batch) = state.commit(script) {
            if state.trace {
                log::info!(
                    target: "nsh::perf",
                    "first frame: eval {eval_us}µs, total {}µs",
                    start.elapsed().as_micros()
                );
            }
            sink.submit(batch);
        }
        state.report_handled(&**sink);
        state.net.pump(script, &mut state.core);
        state.load_chunks(script, &**sink);
        state.request_frame(script, &**sink);
        driver.check_stopped();
        for message in moves {
            if !driver.handle(message, rx) {
                return None;
            }
        }
        Some(driver)
    }

    /// When the loop wakes next: for the next timer or throttled event
    /// (on the system's clock; a manual one moves only when told), or the
    /// idle collection (the system's time, whatever the clock).
    fn deadline(&self) -> Option<Instant> {
        let gc_deadline =
            (self.script.is_some() && self.state.committed_since_gc).then(|| self.next_gc());
        let due = if self.clock.is_manual() {
            None
        } else {
            self.due()
        };
        [due, gc_deadline].into_iter().flatten().min()
    }

    /// When the next timer, task timer or throttled scroll or mouse move
    /// is due, on the engine's clock.
    fn due(&self) -> Option<Instant> {
        [
            self.script.as_ref().and_then(Script::next_timer),
            self.state.next_scroll_event(),
            self.state.next_mouse_move(),
            self.state.core.next_task_timer(),
        ]
        .into_iter()
        .flatten()
        .min()
    }

    /// Handles one message; false on shutdown.
    fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
        self.last_active = Instant::now();
        match message {
            Message::Advance(by, done) => {
                let running = self.advance(by, rx, self.clock.moves_with_frames());
                done();
                running
            }
            Message::Flush(done) => {
                let running = self.flush(rx);
                done(running && self.idle(rx));
                running
            }
            // A test's clock on a real platform: the display's frame moves it
            // to the frame's time first (a frame after the last, else now),
            // as a headless run's frames do.
            Message::Frame if self.clock.moves_with_frames() => {
                // The frame runs there, once, as the frames a move runs on
                // the way do (whatever the messages handled meanwhile do).
                self.state.frame_requested = true;
                let by = self.next_frame() - self.clock.now();
                self.advance(by, rx, true)
            }
            message => handle(self.script.as_ref(), &mut self.state, message),
        }
    }

    /// Moves a manual clock forward by `by` ([`EngineControl::advance_clock`]):
    /// to each time something comes due on the way, running it (and the
    /// messages its alarms sent) before going on; with `frames`, also to
    /// each display frame's time ([`nsh_core::time::FRAME`]) while the app
    /// waits for frames, running the frame there, as a headless run's
    /// display does (a clock that moves with a real display's frames:
    /// [`Clock::with_frames`]). False on shutdown.
    fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
        if !self.clock.is_manual() {
            // What the messages before it did is submitted before `done`.
            self.turn();
            return true;
        }
        let to = self.clock.now() + by;
        for round in 0.. {
            // A timer that keeps scheduling itself at once (`setTimeout(f,
            // 0)` in `f`) would hold the clock at one time for good.
            let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
            let next = [self.due(), self.clock.next_alarm(), frame]
                .into_iter()
                .flatten()
                .min()
                .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
            if round == MAX_ADVANCE_ROUNDS {
                log::warn!(
                    "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
                     a timer keeps scheduling another at once"
                );
            }
            let at = next.unwrap_or(to);
            self.clock.advance_to(at);
            while let Ok(message) = rx.try_recv() {
                if !self.handle(message, rx) {
                    return false;
                }
            }
            // Once: what was handled meanwhile may have run it already.
            if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
                && self.state.frame_requested
            {
                self.frame();
            }
            self.turn();
            if next.is_none() {
                break;
            }
        }
        true
    }

    /// Runs what is queued and what is due now ([`EngineControl::flush`]),
    /// again while that queues more, [`MAX_FLUSH_ROUNDS`] times at most.
    /// False on shutdown.
    fn flush(&mut self, rx: &Receiver<Message>) -> bool {
        let frames = self.clock.moves_with_frames();
        for _ in 0..MAX_FLUSH_ROUNDS {
            while let Ok(message) = rx.try_recv() {
                if !self.handle(message, rx) {
                    return false;
                }
            }
            // A manual clock stays where it is: what is due now runs.
            if !self.advance(std::time::Duration::ZERO, rx, frames) {
                return false;
            }
            // What a turn queued (a task's wake, a response answered at
            // once) runs too, as long as it stops coming.
            if rx.is_empty() {
                break;
            }
        }
        true
    }

    /// Whether nothing is left to run: no message queued, nothing due at
    /// the clock's time (a timer that keeps scheduling another at once
    /// outlasts a flush's rounds) and no request in flight.
    fn idle(&self, rx: &Receiver<Message>) -> bool {
        let now = self.clock.now();
        rx.is_empty()
            && self.state.net.idle()
            && [self.due(), self.clock.next_alarm()]
                .into_iter()
                .flatten()
                .all(|at| at > now)
    }

    /// When the next display frame of a clock that moves with the
    /// display's frames is: a frame after the last, at the display's pace
    /// whatever else comes due meanwhile, else (the first, or after a
    /// pause) a frame from now or now.
    fn next_frame(&self) -> Instant {
        let now = self.clock.now();
        self.last_frame
            .map_or(now + nsh_core::time::FRAME, |last| {
                last + nsh_core::time::FRAME
            })
            .max(now)
    }

    /// Runs a display frame of a clock that moves with the display's
    /// frames, now.
    fn frame(&mut self) {
        self.last_frame = Some(self.clock.now());
        handle(self.script.as_ref(), &mut self.state, Message::Frame);
    }

    /// Runs what the handled messages and the time made due, and submits
    /// the frame.
    fn turn(&mut self) {
        let Driver {
            state,
            script,
            sink,
            assets,
            ..
        } = self;
        let script = script.as_ref();
        if script
            .and_then(Script::next_timer)
            .is_some_and(|due| due <= nsh_core::time::now())
        {
            self.last_active = Instant::now();
        }
        let turn_start = state.trace.then(Instant::now);
        state.dispatch_touch_move(script);
        if state
            .next_mouse_move()
            .is_some_and(|due| due <= nsh_core::time::now())
        {
            state.dispatch_mouse_moves(script);
        }
        state.dispatch_scroll_events(script);
        let hot = std::mem::take(&mut state.hot);
        if let Some(script) = script {
            for update in hot {
                script.hot_update(update, &**sink);
            }
            script.run_timers(nsh_core::time::now());
            script.run_system();
        }
        state.core.run_component_tasks();
        // What JS timers and Rust component tasks took; a Rust component
        // renders in the commit.
        let tasks = turn_start.map(|s| s.elapsed());
        state.load_fonts(script, assets.as_deref(), &**sink);
        if let Some(batch) = state.commit(script) {
            sink.submit(batch);
            if let (Some(start), Some(tasks)) = (turn_start, tasks) {
                log::info!(
                    target: "nsh::perf",
                    "turn: {}µs (timers and tasks {}µs)",
                    start.elapsed().as_micros(),
                    tasks.as_micros(),
                );
            }
        }
        if let Some(size) = state.resized.take() {
            sink.resized(size);
        }
        state.report_handled(&**sink);
        state.net.pump(script, &mut state.core);
        state.load_chunks(script, &**sink);
        state.request_frame(script, &**sink);
        self.check_stopped();
    }

    /// When the next idle collection may run: a second after the last, once
    /// the engine has been quiet for [`IDLE_GC_QUIET`] (or at the latest
    /// [`IDLE_GC_LONGEST`] after the last).
    fn next_gc(&self) -> Instant {
        let quiet = (self.last_active + IDLE_GC_QUIET).min(self.last_gc + IDLE_GC_LONGEST);
        (self.last_gc + IDLE_GC_INTERVAL).max(quiet)
    }

    /// Collects cycles when the engine has been idle long enough, so
    /// released nodes free their views.
    fn collect_if_idle(&mut self) {
        if let Some(script) = &self.script
            && self.state.committed_since_gc
            && Instant::now() >= self.next_gc()
        {
            let start = self.state.trace.then(Instant::now);
            script.collect_garbage();
            if let Some(start) = start {
                log::info!(target: "nsh::perf", "gc: {}µs", start.elapsed().as_micros());
            }
            self.last_gc = Instant::now();
            self.state.committed_since_gc = false;
            if let Some(batch) = self.state.commit(Some(script)) {
                self.sink.submit(batch);
            }
        }
    }

    fn check_stopped(&mut self) {
        if let Some(script) = &self.script
            && !self.stopped
            && let Some(reason) = script.fatal()
        {
            self.stopped = true;
            script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
        }
    }
}

struct ScrollEvent {
    x: f32,
    y: f32,
    content: Size<Points>,
    viewport: Size<Points>,
    /// The zoom scale.
    zoom: f32,
    throttle: Duration,
    last: Option<Instant>,
    /// An offset not reported yet.
    pending: bool,
}

struct State<M: TextEngine> {
    core: Core<M>,
    /// The design tokens JS has (`token()`): the core's when they were
    /// last sent.
    js_tokens: Arc<nsh_core::element::Tokens>,
    /// What the environment keeps whatever the platform reports
    /// ([`EngineConfig::pinned`]).
    pinned: EnvironmentPins,
    /// A display frame was requested and has not begun yet.
    frame_requested: bool,
    ops: Vec<Op>,
    /// List render requests not yet sent to JS.
    binds: Vec<ListBind>,
    /// Events raised by the core (e.g. `onLoadMore`, `onLayout`).
    events: Vec<JsEvent>,
    trace: bool,
    /// Where commit timings go ([`EngineControl::set_perf_monitor`]).
    perf: Option<Arc<perf::PerfMonitor>>,
    /// The core's share of the wake-up being measured (`layout`, `ops`,
    /// `items`; `js` is the rest of the wake-up).
    perf_commit: perf::CommitTiming,
    committed_since_gc: bool,
    /// The embedding app's channel: its URL handler sees the app's URLs
    /// first.
    host: HostChannel,
    /// URLs the app asked to open, taken from the core (a reused buffer).
    url_opens: Vec<(u32, String)>,
    net: Net,
    /// Development updates to apply.
    hot: Vec<HotUpdate>,
    /// `onScroll` events: the latest offset per scroll view, sent once per
    /// frame at most (and not more often than the view's throttle).
    scroll_events: FxHashMap<NodeId, ScrollEvent>,
    /// Touch moves not delivered yet: those queued in one frame become one.
    touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
    /// Mouse moves not delivered yet: the latest per view, in the order they
    /// came; sent once per [`MOUSE_MOVE_INTERVAL`] at most, and before
    /// any other event.
    mouse_moves: Vec<(NodeId, EventPayload)>,
    /// When `mouse_moves` were last delivered.
    mouse_moved: Option<Instant>,
    /// [`keep_last_sets`]'s buffer, reused.
    sets_seen: FxHashMap<(u8, NodeId), usize>,
    /// The viewport size a resize set this turn ([`MountSink::resized`]).
    resized: Option<Size<Points>>,
    /// Events received ([`EngineControl::dispatch_event`]), and the count
    /// last reported ([`MountSink::handled`]).
    events_handled: u64,
    events_reported: u64,
}

/// Who made a request: JS (`fetch`), or a Rust component's task
/// (`nsh_core::element::fetch`, [`Core::take_fetches`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Requester {
    Js(RequestId),
    Task(u32),
}

/// Requests between the app (JS and Rust components' tasks) and the
/// platform's network stack.
struct Net {
    network: Option<Arc<dyn Network>>,
    tx: Sender<Message>,
    queue: NetworkQueue,
    inflight: FxHashMap<Requester, Inflight>,
    /// The tasks' requests taken from the core, and those they gave up
    /// (reused buffers).
    tasks: Vec<(u32, HttpRequest)>,
    abandoned: Vec<u32>,
    /// What the app may reach.
    access: Arc<nsh_core::access::Access>,
    /// Hops started so far (the id of the next).
    hops: u64,
    /// Where requests of `asset:/` URLs are answered from
    /// ([`EngineConfig::assets`]).
    assets: Option<Arc<dyn Assets>>,
    /// The runtime whose blocking pool reads them (the components'
    /// tasks').
    #[cfg(not(target_arch = "wasm32"))]
    runtime: tokio::runtime::Handle,
}

/// The task of a request for a bundled file while it is read: the read
/// finishes on its own, and a cancelled request drops what it gives.
struct AssetTask;

impl FetchTask for AssetTask {
    fn send(&mut self, _: Vec<u8>) {}
    fn finish(&mut self) {}
    fn pause(&mut self, _: bool) {}
    fn cancel(self: Box<Self>) {}
}

/// Whether `url` names a bundled file (`asset:/…`).
fn is_asset(url: &str) -> bool {
    url.get(..6)
        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("asset:"))
}

/// Whether the bundled file `url` names stays inside the app's files
/// whichever way a host maps `asset:/<path>` to its asset directory: the
/// path is relative, and no segment is empty, `.` or `..` (encoded or not)
/// or holds a backslash, a NUL or a colon (a Windows drive). Hosts join the
/// path to their directory as it comes, so they never see one that
/// escapes it.
fn is_inside_assets(url: &str) -> bool {
    let Some(path) = url.get(6..).and_then(|rest| rest.strip_prefix('/')) else {
        return false;
    };
    path.split('/').all(|segment| {
        let segment = segment.to_ascii_lowercase();
        let named = !matches!(segment.replace("%2e", ".").as_str(), "" | "." | "..");
        let plain = !segment.contains(['\\', '\0', ':'])
            && !["%2f", "%5c", "%00", "%3a"]
                .iter()
                .any(|encoded| segment.contains(encoded));
        named && plain
    })
}

/// The media type a bundled file's response carries, from its extension:
/// the dev server's (`nsh-dev`'s `content_type`), so a file read from the
/// app's files and one downloaded from where a web app serves them answer
/// with the same type.
fn asset_type(url: &str) -> &'static str {
    let name = url.rsplit('/').next().unwrap_or_default();
    let extension = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
    match extension.as_deref() {
        Some("html") => "text/html; charset=utf-8",
        Some("js" | "mjs") => "text/javascript; charset=utf-8",
        Some("json" | "map") => "application/json",
        Some("webmanifest") => "application/manifest+json",
        Some("wasm") => "application/wasm",
        Some("css") => "text/css; charset=utf-8",
        Some("txt") => "text/plain; charset=utf-8",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("avif") => "image/avif",
        Some("svg") => "image/svg+xml",
        Some("ico") => "image/x-icon",
        Some("heic") => "image/heic",
        Some("ttf") => "font/ttf",
        Some("otf") => "font/otf",
        Some("woff") => "font/woff",
        Some("woff2") => "font/woff2",
        Some("mp4" | "m4v") => "video/mp4",
        Some("webm") => "video/webm",
        Some("mov") => "video/quicktime",
        Some("mp3") => "audio/mpeg",
        Some("m4a") => "audio/mp4",
        Some("wav") => "audio/wav",
        _ => "application/octet-stream",
    }
}

/// A request in flight.
struct Inflight {
    task: Box<dyn FetchTask>,
    /// The hop the task is.
    hop: u64,
    /// Requests whose redirects the engine follows (to check each hop).
    followed: Option<access::Followed>,
    /// The bundled file (`asset:/…`) a download is of: a status other than
    /// a success fails it, as a file the host does not have does.
    asset: Option<String>,
}

impl Net {
    /// Whether no request waits for the network.
    fn idle(&self) -> bool {
        self.inflight.is_empty()
    }

    /// Hands what JS and the components' tasks asked of their requests to
    /// the network.
    fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
        let mut abandoned = std::mem::take(&mut self.abandoned);
        core.take_fetches(&mut self.tasks, &mut abandoned);
        for id in abandoned.drain(..) {
            self.cancel(Requester::Task(id));
        }
        self.abandoned = abandoned;
        let mut tasks = std::mem::take(&mut self.tasks);
        for (id, request) in tasks.drain(..) {
            if let Err(refused) = self.request(Requester::Task(id), request) {
                core.fetch_event(id, FetchEvent::Failed(refused.message));
            }
        }
        self.tasks = tasks;
        let Some(script) = script else { return };
        script.take_network(&mut self.queue);
        for (id, op) in std::mem::take(&mut self.queue.ops) {
            let who = Requester::Js(id);
            match op {
                FetchOp::Start(request) => {
                    if let Err(refused) = self.request(who, request) {
                        script.fetch_refused(id, &refused.message, &refused.url);
                    }
                }
                FetchOp::Send(chunk) => {
                    if let Some(i) = self.inflight.get_mut(&who) {
                        i.task.send(chunk);
                    }
                }
                FetchOp::Finish => {
                    if let Some(i) = self.inflight.get_mut(&who) {
                        i.task.finish();
                    }
                }
                FetchOp::Pause(paused) => {
                    if let Some(i) = self.inflight.get_mut(&who) {
                        i.task.pause(paused);
                    }
                }
                FetchOp::Cancel => self.cancel(who),
            }
        }
    }

    /// Aborts `who`'s request.
    fn cancel(&mut self, who: Requester) {
        if let Some(i) = self.inflight.remove(&who) {
            i.task.cancel();
        }
    }

    /// Makes `who`'s request, if the app may (else why not). Bundled files
    /// are the app's own: their requests need no capability.
    fn request(&mut self, who: Requester, request: HttpRequest) -> Result<(), access::Refused> {
        if is_asset(&request.url) {
            self.asset(who, request);
        } else if self.access.is_unrestricted() {
            self.start(who, request, None);
        } else if !self.access.allows_http(&request.method, &request.url) {
            return Err(access::refused(&request.method, &request.url));
        } else if request.follow_redirects {
            let hop = access::hop(&request);
            let followed = access::Followed { request, hops: 0 };
            self.start(who, hop, Some(followed));
        } else {
            self.start(who, request, None);
        }
        Ok(())
    }

    /// Hands one request (or redirect hop) to the network.
    fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
        self.hops += 1;
        let hop = self.hops;
        let Some(network) = &self.network else {
            let failed = FetchEvent::Failed("this host has no network stack".to_owned());
            let _ = self.tx.send(Message::Fetch(id, hop, failed));
            return;
        };
        let tx = self.tx.clone();
        let events: FetchEvents = Box::new(move |event| {
            let _ = tx.send(Message::Fetch(id, hop, event));
        });
        let task = network.fetch(request, events);
        self.inflight.insert(
            id,
            Inflight {
                task,
                hop,
                followed,
                asset: None,
            },
        );
    }

    /// Answers `who`'s request of a bundled file (an `asset:/` URL) from
    /// the host's assets: read on the runtime's blocking pool, which reports
    /// with [`Message::AssetRead`] (in WebAssembly, which has no threads,
    /// here).
    fn asset(&mut self, who: Requester, request: HttpRequest) {
        self.hops += 1;
        let hop = self.hops;
        self.inflight.insert(
            who,
            Inflight {
                task: Box::new(AssetTask),
                hop,
                followed: None,
                asset: None,
            },
        );
        // Failed here, before any host reads the file or serves it
        // ([`Assets::url`]): a request no host may answer reaches none.
        let refused = if !is_inside_assets(&request.url) {
            Some(format!(
                "{}: bundled files are named by a path inside the app's files",
                request.url
            ))
        } else if !matches!(request.method.as_str(), "GET" | "HEAD") {
            Some(format!(
                "{} {}: bundled files are read with GET",
                request.method, request.url
            ))
        } else {
            None
        };
        if let Some(refused) = refused {
            let _ = self
                .tx
                .send(Message::Fetch(who, hop, FetchEvent::Failed(refused)));
            return;
        }
        let Some(assets) = &self.assets else {
            let failed = Err("this host cannot load assets".to_owned());
            self.asset_read(who, hop, request, failed);
            return;
        };
        #[cfg(not(target_arch = "wasm32"))]
        {
            let assets = assets.clone();
            let tx = self.tx.clone();
            // The read reports itself; nothing awaits its handle.
            drop(self.runtime.spawn_blocking(move || {
                let bytes = assets.read(&request.url);
                let _ = tx.send(Message::AssetRead(who, hop, request, bytes));
            }));
        }
        #[cfg(target_arch = "wasm32")]
        {
            let bytes = assets.read(&request.url);
            self.asset_read(who, hop, request, bytes);
        }
    }

    /// Hop `hop` of `who`'s request of a bundled file read it: its response,
    /// or, when the host has no copy but serves the file at a URL
    /// ([`Assets::url`]), the download of it. Only requests [`Net::asset`]
    /// let through come here. Dropped when the request was cancelled
    /// meanwhile.
    fn asset_read(
        &mut self,
        who: Requester,
        hop: u64,
        request: HttpRequest,
        read: Result<Vec<u8>, String>,
    ) {
        if self.inflight.get(&who).is_none_or(|i| i.hop != hop) {
            return;
        }
        let events = match read {
            Ok(bytes) => {
                let head = HttpHead {
                    status: 200,
                    status_text: "OK".to_owned(),
                    headers: vec![
                        ("content-length".to_owned(), bytes.len().to_string()),
                        (
                            "content-type".to_owned(),
                            asset_type(&request.url).to_owned(),
                        ),
                    ],
                    url: request.url.clone(),
                    ..HttpHead::default()
                };
                let mut events = vec![FetchEvent::Head(head)];
                if request.method == "GET" && !bytes.is_empty() {
                    events.push(FetchEvent::Data(bytes));
                }
                events.push(FetchEvent::End);
                events
            }
            Err(error) => match self.assets.as_ref().and_then(|a| a.url(&request.url)) {
                Some(url) => {
                    self.inflight.remove(&who);
                    let uri = request.url.clone();
                    self.start(who, HttpRequest { url, ..request }, None);
                    if let Some(download) = self.inflight.get_mut(&who) {
                        download.asset = Some(uri);
                    }
                    return;
                }
                None => vec![FetchEvent::Failed(error)],
            },
        };
        for event in events {
            let _ = self.tx.send(Message::Fetch(who, hop, event));
        }
    }

    /// An event of hop `hop` of request `id`: what JS is told, if anything
    /// (`None` for events of hops left behind, and redirects the engine
    /// follows; `Err` for a redirect the app may not follow).
    fn event(
        &mut self,
        id: Requester,
        hop: u64,
        event: FetchEvent,
    ) -> Option<Result<FetchEvent, access::Refused>> {
        if self.network.is_none() {
            return Some(Ok(event));
        }
        let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
        match event {
            FetchEvent::Head(mut head) => {
                let missing = (inflight.asset.as_ref())
                    .filter(|_| !(200..300).contains(&head.status))
                    .map(|uri| format!("{uri}: HTTP {}", head.status));
                if let Some(missing) = missing {
                    if let Some(i) = self.inflight.remove(&id) {
                        i.task.cancel();
                    }
                    return Some(Ok(FetchEvent::Failed(missing)));
                }
                // A downloaded bundled file answers as one read from the
                // app's files: its `asset:/` URL, and a type even where the
                // server gave none.
                if let Some(uri) = &inflight.asset {
                    head.url = uri.clone();
                    head.redirected = false;
                    if !head
                        .headers
                        .iter()
                        .any(|(name, _)| name.eq_ignore_ascii_case("content-type"))
                    {
                        head.headers
                            .push(("content-type".to_owned(), asset_type(uri).to_owned()));
                    }
                }
                let Some(followed) = &mut inflight.followed else {
                    return Some(Ok(FetchEvent::Head(head)));
                };
                match access::next(&self.access, followed, head) {
                    access::Next::Done(head) => Some(Ok(FetchEvent::Head(head))),
                    access::Next::Fail(message) => {
                        if let Some(i) = self.inflight.remove(&id) {
                            i.task.cancel();
                        }
                        Some(Ok(FetchEvent::Failed(message)))
                    }
                    access::Next::Refused(refused) => {
                        if let Some(i) = self.inflight.remove(&id) {
                            i.task.cancel();
                        }
                        Some(Err(refused))
                    }
                    access::Next::Hop(request) => {
                        let i = self.inflight.remove(&id)?;
                        let followed = i.followed;
                        i.task.cancel();
                        self.start(id, request, followed);
                        None
                    }
                }
            }
            FetchEvent::End | FetchEvent::Failed(_) => {
                self.inflight.remove(&id);
                Some(Ok(event))
            }
            event => Some(Ok(event)),
        }
    }
}

impl<M: TextEngine> State<M> {
    /// Ends the measured wake-up that began at `started`
    /// ([`EngineControl::set_perf_monitor`]).
    fn record_perf(&mut self, started: Option<Instant>) {
        let (Some(started), Some(monitor)) = (started, &self.perf) else {
            return;
        };
        let busy = started.elapsed();
        monitor.record_busy(busy);
        let mut commit = std::mem::take(&mut self.perf_commit);
        if commit.ops > 0 || commit.items > 0 {
            commit.js = busy.saturating_sub(commit.layout);
            monitor.record_commit(commit);
        }
    }

    /// Sends the pending touch move.
    fn dispatch_touch_move(&mut self, script: Option<&Script>) {
        if let Some((id, touch)) = self.touch_move.take()
            && let Some(script) = script
        {
            script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
        }
    }

    /// When the pending `onMouseMove`s are due.
    fn next_mouse_move(&self) -> Option<Instant> {
        if self.mouse_moves.is_empty() {
            return None;
        }
        Some(
            self.mouse_moved
                .map_or_else(nsh_core::time::now, |t| t + MOUSE_MOVE_INTERVAL),
        )
    }

    /// Delivers the pending `onMouseMove`s: to the Rust components whose
    /// parts they are on, the others to JS.
    fn dispatch_mouse_moves(&mut self, script: Option<&Script>) {
        if self.mouse_moves.is_empty() {
            return;
        }
        self.mouse_moved = Some(nsh_core::time::now());
        for (id, payload) in std::mem::take(&mut self.mouse_moves) {
            if self
                .core
                .component_event(id, EventKind::MouseMove, &payload)
            {
                continue;
            }
            if let Some(script) = script {
                script.dispatch_event(id, EventKind::MouseMove, &payload);
            }
        }
    }

    /// When a throttled `onScroll` is due.
    fn next_scroll_event(&self) -> Option<Instant> {
        self.scroll_events
            .values()
            .filter(|e| e.pending)
            .filter_map(|e| e.last.map(|t| t + e.throttle))
            .min()
    }

    /// Sends the `onScroll` events that are due.
    fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
        if self.scroll_events.is_empty() {
            return;
        }
        let now = nsh_core::time::now();
        // Views that stopped listening (or are gone).
        let core = &self.core;
        self.scroll_events
            .retain(|&id, _| core.scroll_listener(id).is_some());
        for (&id, e) in &mut self.scroll_events {
            if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
                continue;
            }
            e.pending = false;
            e.last = Some(now);
            let n = |v: f32| PayloadValue::Number(v as f64);
            let payload = EventPayload::Map(vec![
                (
                    "offset",
                    PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
                ),
                ("contentSize", PayloadValue::Size(e.content)),
                ("size", PayloadValue::Size(e.viewport)),
                ("zoomScale", n(e.zoom)),
            ]);
            // A Rust component's scroll view is the component's.
            if !self.core.component_event(id, EventKind::Scroll, &payload)
                && let Some(script) = script
            {
                script.dispatch_event(id, EventKind::Scroll, &payload);
            }
        }
    }

    /// Asks the platform for the chunks JS imports and does not have.
    fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
        let Some(script) = script else { return };
        let mut ids = Vec::new();
        script.take_chunk_requests(&mut ids);
        for id in ids {
            if !sink.load_chunk(&id) {
                let message = "this host does not load chunks (the app was built split)".to_owned();
                let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
            }
        }
    }

    /// Tells the platform how many events were handled, once the commit
    /// of what they changed is submitted.
    fn report_handled(&mut self, sink: &dyn MountSink) {
        if self.events_handled != self.events_reported {
            self.events_reported = self.events_handled;
            sink.handled(self.events_handled);
        }
    }

    /// Asks the platform for a frame when JS or a component's task waits
    /// for one.
    fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
        if !self.frame_requested
            && (script.is_some_and(Script::wants_frame)
                || self.core.wants_frame()
                || (script.is_some() && self.core.has_paced_list_binds()))
        {
            self.frame_requested = true;
            sink.request_frame();
        }
    }

    /// Registers fonts imported by JS. Blocking: text using them must not be
    /// measured with a fallback font first.
    fn load_fonts(
        &mut self,
        script: Option<&Script>,
        assets: Option<&dyn Assets>,
        sink: &dyn MountSink,
    ) {
        let Some(script) = script else { return };
        let mut fonts = Vec::new();
        script.take_fonts(&mut fonts);
        for uri in fonts {
            let result = match assets {
                Some(assets) => assets.read(&uri),
                None => Err("this host cannot load assets".to_owned()),
            }
            .and_then(|data| self.core.register_font(&data));
            if let Err(err) = result {
                script.report(
                    sink,
                    AppErrorKind::Asset,
                    "font failed",
                    &format!("{uri}: {err}"),
                );
            }
        }
    }

    /// Produces one frame: applies JS ops, lays out, and lets lists pull
    /// the items they need, merging everything into a single batch.
    /// Hands the URLs the app asked to open to the embedding app's URL
    /// handler, or, without one, to the platform ([`nsh_core::open_url`]);
    /// true when the platform has one to open (the core's commit sends it).
    fn open_urls(&mut self) -> bool {
        self.core.take_url_opens(&mut self.url_opens);
        let mut platform = false;
        for (id, url) in self.url_opens.drain(..) {
            if self.host.open_url(id, url.clone(), &self.net.tx).is_none() {
                self.core.open_url_on_platform(id, url);
                platform = true;
            }
        }
        platform
    }

    fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
        let start = Instant::now();
        let mut merged: Option<MountBatch> = None;
        let mut commits = 0;
        let mut op_count = 0;
        let mut js = std::time::Duration::ZERO;
        // The overscan bound this turn ([`PACED_BIND_OPS`]).
        let mut paced = PacedBinds::default();
        for _ in 0..MAX_LIST_ROUNDS {
            // Requests from the previous round (or frame) first.
            let js_start = Instant::now();
            // Without JS, lists bind nowhere (Rust components' lists bind in
            // the core).
            let binds = self.binds.drain(..);
            if let Some(script) = script {
                for bind in binds {
                    script.bind_list(bind.list, &bind.binds);
                }
                script.take_ops(&mut self.ops);
                let mut binds = Vec::new();
                while paced.left() && self.core.has_paced_list_binds() {
                    let start = Instant::now();
                    let ops = self.ops.len();
                    self.core.take_paced_list_binds(1, &mut binds);
                    for bind in binds.drain(..) {
                        paced.cells += bind.binds.len();
                        script.bind_list(bind.list, &bind.binds);
                    }
                    script.take_ops(&mut self.ops);
                    paced.ops += self.ops.len() - ops;
                    paced.time += start.elapsed();
                }
            } else {
                drop(binds);
            }
            // The JS calls Rust queued (callbacks' posts), in order, before
            // the events: a task's posts come before its result.
            if let Some(script) = script {
                script.run_posted();
            }
            // The core's events (layouts, ends reached, ...) on a Rust
            // component's nodes are the component's; the rest are JS's, in
            // order with Rust components' events and calls' results.
            for event in self.events.drain(..) {
                match event {
                    JsEvent::Event(id, event, payload) => {
                        if !self.core.component_event(id, event, &payload)
                            && let Some(script) = script
                        {
                            script.dispatch_event(id, event, &payload);
                        }
                    }
                    JsEvent::LayoutListener {
                        host,
                        id,
                        listener,
                        frame,
                    } => {
                        self.core.component_layout(host, id, &listener, frame);
                    }
                    // Without JS nothing waits for them.
                    other => {
                        if let Some(script) = script {
                            script.deliver(other);
                        }
                    }
                }
            }
            if let Some(script) = script {
                script.take_ops(&mut self.ops);
            }
            js += js_start.elapsed();
            op_count += self.ops.len();
            // A stop drops the rest of the ops, releasing what they hold
            // for Rust classes.
            let mut ops = self.ops.drain(..);
            while let Some(op) = ops.next() {
                match self.core.apply(op) {
                    Ok(()) => {}
                    Err(err) if err.is_fatal() => {
                        self.core.discard_ops(ops.by_ref());
                        let Some(script) = script else { break };
                        script.stop(match err {
                            ApplyError::TooManyNodes(max) => {
                                format!("the app created more than {max} nodes and was stopped")
                            }
                            other => {
                                format!("the app sent an invalid op ({other:?}) and was stopped")
                            }
                        });
                        break;
                    }
                    Err(err) => log::error!("invalid op: {err:?}"),
                }
            }
            drop(ops);
            if let Some(batch) = self.core.commit() {
                commits += 1;
                match &mut merged {
                    Some(m) => extend_frame(&mut m.items, batch.items),
                    None => merged = Some(batch),
                }
            }
            self.core.take_list_binds(&mut self.binds);
            self.core.take_events(&mut self.events);
            // URLs the platform opens go out in another round.
            let urls = self.open_urls();
            // Posts the ops queued (in program order) run in another round.
            let posted = script.is_some_and(Script::has_posted);
            // New tokens (the app's theme, the embedding app's) reach what
            // read them in JS, whose ops come in another round.
            let retheme = match script {
                Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
                    self.js_tokens = self.core.tokens().clone();
                    script.set_tokens(self.js_tokens.clone());
                    true
                }
                _ => false,
            };
            let more_paced = script.is_some() && paced.left() && self.core.has_paced_list_binds();
            // What waited for the app's answer to the events just taken runs
            // in the next round, once JS has handled them, and shows in this
            // batch.
            let answers = self.core.has_due_answers();
            if self.binds.is_empty()
                && self.events.is_empty()
                && !posted
                && !retheme
                && !more_paced
                && !urls
                && !answers
            {
                break;
            }
        }
        if commits > 1
            && let Some(batch) = &mut merged
        {
            keep_last_sets(&mut batch.items, &mut self.sets_seen);
        }
        self.committed_since_gc |= op_count > 0;
        if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
            let c = &mut self.perf_commit;
            c.layout += start.elapsed().saturating_sub(js);
            c.ops += op_count as u32;
            c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
        }
        if self.trace && (op_count > 0 || merged.is_some()) {
            log::info!(
                target: "nsh::perf",
                "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
                start.elapsed().as_micros(),
                js.as_micros(),
                merged.as_ref().map_or(0, |b| b.items.len()),
                self.core.node_count(),
            );
        }
        merged
    }
}

fn insets(env: &Environment) -> EdgeInsets {
    env.safe_area
}

/// What Rust components read from the environment.
fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::element::Environment {
    nsh_core::element::Environment {
        window,
        safe_area: insets(env),
        title_bar: env.title_bar,
        keyboard_height: env.keyboard_height,
        keyboard_duration: env.keyboard_duration,
        dark: env.color_scheme == ColorScheme::Dark,
        font_scale: env.font_scale,
        reduce_motion: env.reduce_motion,
        screen_reader: env.screen_reader,
        rtl: env.rtl,
        pixel_ratio: env.pixel_ratio,
        os: env.os,
        os_version: env.os_version,
        idiom: env.idiom,
        locale: env.locale,
        apple_keyboard: env.apple_keyboard,
        host: env.host,
        lifecycle: env.lifecycle,
        screen_color: env.screen_color,
        file_requests: env.file_requests,
        speech: env.speech,
        web_input: env.web_input,
    }
}

/// What class variants read from the environment.
fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
    nsh_core::tailwind::ClassEnvironment {
        dark: env.color_scheme == ColorScheme::Dark,
        platform: if env.os == Os::Web {
            nsh_core::tailwind::Platform::Web
        } else if cfg!(target_os = "android") {
            nsh_core::tailwind::Platform::Android
        } else {
            nsh_core::tailwind::Platform::Ios
        },
        reduce_motion: env.reduce_motion,
    }
}

/// Returns false on shutdown.
fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
    match message {
        Message::Event(id, event, mut payload) => {
            state.events_handled += 1;
            if state.trace {
                log::info!(target: "nsh::perf", "event {event:?} on view {id}");
            }
            // Mouse moves wait for the frame, the latest per view; any other
            // event comes after the moves before it (a view hears where the
            // mouse went before it hears it leave).
            if event == EventKind::MouseMove {
                match state.mouse_moves.iter_mut().find(|(v, _)| *v == id) {
                    Some((_, pending)) => *pending = payload,
                    None => state.mouse_moves.push((id, payload)),
                }
                return true;
            }
            state.dispatch_mouse_moves(script);
            // The core tracks input text for layout and to recognize stale
            // values (from JS and from Rust components alike).
            if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
                state.core.input_changed(id, text, *count);
            }
            // The platform knows the caret in the input, the core where
            // the input is.
            if event == EventKind::CaretMove {
                state.core.locate_caret(id, &mut payload);
            }
            if event == EventKind::Paste {
                payload = payload.into_paste();
            }
            // Events on a Rust component's parts are the component's.
            if state.core.component_event(id, event, &payload) {
                return true;
            }
            if let EventPayload::Touch(touch) = payload {
                if touch.phase == nsh_core::TouchPhase::Move {
                    match &mut state.touch_move {
                        Some((_, pending)) => pending.merge_move(*touch),
                        None => state.touch_move = Some((id, touch)),
                    }
                    return true;
                }
                // Moves before a start, end or cancel go first.
                state.dispatch_touch_move(script);
                if let Some(script) = script {
                    script.dispatch_event(id, event, &EventPayload::Touch(touch));
                }
                return true;
            }
            let Some(script) = script else { return true };
            let start = state.trace.then(Instant::now);
            script.dispatch_event(id, event, &payload);
            if let Some(start) = start {
                // The handler, its microtasks and the decode of what it
                // committed.
                log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
            }
        }
        Message::Scroll(id, offset, applied) => {
            state.core.set_scroll_offset(id, offset, applied);
            let (x, y) = (offset.x.0, offset.y.0);
            if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
                let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
                    x,
                    y,
                    content,
                    viewport,
                    zoom,
                    throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
                    last: None,
                    pending: true,
                });
                (event.x, event.y, event.content, event.viewport, event.zoom) =
                    (x, y, content, viewport, zoom);
                event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
                event.pending = true;
            }
        }
        Message::Kept(nodes) => state.core.set_kept(&nodes),
        Message::InputScroll(id, offset, content, viewport) => {
            state.core.set_input_scroll(id, offset, content, viewport);
        }
        Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
        Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
        Message::AnimationsFinished(mut finished) => {
            // The components' animations end in the core, JS's in JS.
            state.core.animations_finished(&mut finished);
            if let Some(script) = script {
                script.animations_finished(&finished);
            }
        }
        Message::Resize(size) => {
            state.core.set_viewport(size);
            state.resized = Some(size);
        }
        Message::Wake => {}
        Message::Environment(mut env) => {
            state.pinned.apply(&mut env);
            state.core.set_font_scale(env.font_scale);
            state.core.set_class_environment(class_environment(&env));
            state.core.set_safe_area(insets(&env));
            let window = env.window;
            state.core.set_environment(ui_environment(&env, window));
            if let Some(script) = script {
                script.set_environment(&env);
            }
        }
        Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
        Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
        Message::Frame => {
            state.frame_requested = false;
            state.core.run_frame(nsh_core::time::now());
            if let Some(script) = script {
                script.run_frame();
            }
        }
        Message::States(id, states) => state.core.set_states(id, states),
        Message::FontsChanged => state.core.fonts_changed(),
        Message::Remount => state.core.remount(),
        Message::Fetch(who, hop, event) => match (who, state.net.event(who, hop, event)) {
            (_, None) => {}
            (Requester::Js(id), Some(event)) => {
                if let Some(script) = script {
                    match event {
                        Ok(event) => script.fetch_event(id, event),
                        Err(refused) => script.fetch_refused(id, &refused.message, &refused.url),
                    }
                }
            }
            (Requester::Task(id), Some(event)) => {
                let event = event.unwrap_or_else(|refused| FetchEvent::Failed(refused.message));
                if !state.core.fetch_event(id, event) {
                    state.net.cancel(who);
                }
            }
        },
        Message::AssetRead(who, hop, request, read) => {
            state.net.asset_read(who, hop, request, read)
        }
        Message::Hot(update) => state.hot.push(update),
        Message::Chunk(chunk) => {
            if let Some(script) = script {
                script.chunk(chunk);
            }
        }
        Message::Perf(monitor) => {
            state.perf = monitor;
            state.perf_commit = perf::CommitTiming::default();
        }
        Message::Tokens(tokens) => {
            state.core.set_host_tokens(tokens.map(|t| *t));
            if let Some(script) = script {
                script.set_theme_tokens(state.core.theme_tokens());
            }
        }
        // A Rust app has no `nsh/host`: what the host sends it goes.
        Message::HostEvent(name, data) => {
            if let Some(script) = script {
                script.host_event(&name, data);
            }
        }
        Message::HostReply(id, result) => {
            if let Some(script) = script {
                script.host_reply(id, result);
            }
        }
        Message::UrlHandled { id, url, handled } => {
            if handled {
                state.core.answer_open_url(id, true);
            } else {
                state.core.open_url_on_platform(id, url);
            }
        }
        // The driver handles it ([`Driver::handle`]), and keeps the ones
        // sent before it started for after the first frame.
        Message::Advance(..) | Message::Flush(..) => unreachable!("the driver moves the clock"),
        Message::Shutdown => return false,
    }
    true
}

/// What a turn spent binding overscan cells.
#[derive(Default)]
struct PacedBinds {
    cells: usize,
    ops: usize,
    time: std::time::Duration,
}

impl PacedBinds {
    /// Whether the turn may bind another: at least one, then within the
    /// budget.
    fn left(&self) -> bool {
        self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
    }
}

/// Appends a commit's items to the frame's. A scroll view's content size
/// that the frame already sets is updated to the later size (unless the
/// view scrolls in between): a row relaid over two commits must not send
/// the platform a transient size, which clamps the offset before the
/// content grows back (a list jumping when a row expands).
fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
    use nsh_core::MountItem;
    let start = frame.len();
    frame.extend(items);
    for k in start..frame.len() {
        let MountItem::ScrollContent { id, size } = frame[k] else {
            continue;
        };
        let earlier = frame[..k].iter().rposition(|m| {
            matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
        });
        if let Some(j) = earlier
            && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
        {
            *s = size;
        }
    }
}

/// Of the items of a frame merged from several commits that set one part
/// of a view whole (its frame, style, text, ...), keeps the last: the
/// platform would apply each in one pass, and a list's rounds (binds, then
/// the paced ones) relay and restyle the same cells. Once per turn, with
/// `last` the reused buffer.
fn keep_last_sets(frame: &mut Vec<nsh_core::MountItem>, last: &mut FxHashMap<(u8, NodeId), usize>) {
    last.clear();
    let mut repeated = false;
    for (k, item) in frame.iter().enumerate() {
        if let Some(key) = sets_whole(item) {
            repeated |= last.insert(key, k).is_some();
        }
    }
    if !repeated {
        return;
    }
    let mut k = 0;
    frame.retain(|item| {
        k += 1;
        sets_whole(item).is_none_or(|key| last[&key] == k - 1)
    });
}

/// The part of a view an item sets whole, and the view: of two such items
/// the later is all the view ends up with.
fn sets_whole(item: &nsh_core::MountItem) -> Option<(u8, nsh_core::NodeId)> {
    use nsh_core::MountItem;
    Some(match *item {
        MountItem::Frame { id, .. } => (0, id),
        MountItem::Overflow { id, .. } => (1, id),
        MountItem::ViewStyle { id, .. } => (2, id),
        MountItem::Text { id, .. } => (3, id),
        MountItem::Events { id, .. } => (4, id),
        MountItem::Image { id, .. } => (5, id),
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    #[test]
    fn pinned_values_hold_whatever_the_platform_reports() {
        let pins = super::EnvironmentPins {
            locale: nsh_core::platform::Locale::parse("de-DE"),
            reduce_motion: Some(true),
            ..Default::default()
        };
        let mut reported = super::Environment {
            locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
            font_scale: 1.5,
            ..Default::default()
        };
        pins.apply(&mut reported);
        assert_eq!(reported.locale.as_str(), "de-DE");
        assert!(reported.reduce_motion);
        // What is not pinned stays the platform's.
        assert_eq!(reported.font_scale, 1.5);
        assert_eq!(reported.safe_area, Default::default());
    }

    #[test]
    fn bundle_default_has_no_application_selected_path_anchors() {
        let bundle = super::Bundle::default();
        assert!(bundle.system_paths.plugin_dir.is_none());
        assert!(bundle.system_paths.home_dir.is_none());
        assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
    }

    #[test]
    fn bundle_trusted_paths_reject_relative_and_missing_directories() {
        let mut paths = nsh_core::access::TrustedPaths::default();
        paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
        paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
        let bundle = super::Bundle::default().with_system_paths(paths);
        assert!(bundle.system_paths.plugin_dir.is_none());
        assert!(bundle.system_paths.home_dir.is_none());
        assert!(
            super::trusted_directory(Some(std::path::PathBuf::from(
                "/nsh-nonexistent-anchor-never-created"
            )))
            .is_none()
        );
    }

    #[test]
    fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
        let root = std::env::var_os("TMPDIR")
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|| {
                std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
                    .join(".cache/nsh-benchs-test-tmp")
            });
        assert!(root.is_absolute() && !root.starts_with("/tmp"));
        let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
        std::fs::create_dir_all(&directory).unwrap();
        let path = directory.join("bundle.js");
        std::fs::write(&path, "export default null;").unwrap();
        let bundle = super::Bundle::read(&path).unwrap();
        assert_eq!(
            bundle.system_paths.plugin_dir,
            Some(nsh_core::access::canonicalize(&directory).unwrap())
        );
        assert!(bundle.system_paths.home_dir.is_none());
        std::fs::remove_dir_all(directory).unwrap();
    }

    #[test]
    fn rust_environment_preserves_native_title_bar_insets() {
        use super::{Edges, Points};
        let title_bar = Edges {
            top: Points(42.0),
            left: Points(78.0),
            right: Points(138.0),
            bottom: Points(0.0),
        };
        let environment = super::Environment {
            title_bar,
            ..Default::default()
        };
        assert_eq!(
            super::ui_environment(
                &environment,
                nsh_core::Size::new(Points(840.0), Points(630.0))
            )
            .title_bar,
            title_bar
        );
    }

    use nsh_core::{MountItem, Points, Size};

    #[test]
    fn a_frame_sends_a_scroll_views_last_content_size() {
        let content = |height| MountItem::ScrollContent {
            id: 2,
            size: Size::new(Points(390.0), height),
        };
        let heights = |frame: &[MountItem]| -> Vec<f32> {
            frame
                .iter()
                .filter_map(|m| match m {
                    MountItem::ScrollContent { size, .. } => Some(size.height.0),
                    _ => None,
                })
                .collect()
        };
        let mut frame = vec![content(Points(313.0))];
        super::extend_frame(&mut frame, vec![content(Points(544.0))]);
        assert_eq!(heights(&frame), [544.0, 544.0]);
        // A scroll in between keeps the size it scrolled against.
        let mut frame = vec![
            content(Points(313.0)),
            MountItem::ScrollBy {
                id: 2,
                dx: Points(0.0),
                dy: Points(10.0),
            },
        ];
        super::extend_frame(&mut frame, vec![content(Points(544.0))]);
        assert_eq!(heights(&frame), [313.0, 544.0]);
    }

    #[test]
    fn a_frame_sends_a_views_last_frame_once() {
        use nsh_core::{Bounds, Point};
        let at = |id, y| MountItem::Frame {
            id,
            frame: Bounds::new(
                Point::new(Points(0.0), Points(y)),
                Size::new(Points(10.0), Points(10.0)),
            ),
        };
        let mut frame = vec![
            MountItem::Create {
                id: 4,
                kind: nsh_core::ViewKind::View,
            },
            at(4, 0.0),
            at(6, 0.0),
        ];
        super::extend_frame(&mut frame, vec![at(4, 50.0)]);
        super::keep_last_sets(&mut frame, &mut Default::default());
        assert!(matches!(frame[0], MountItem::Create { id: 4, .. }));
        let frames: Vec<_> = frame
            .iter()
            .filter_map(|m| match m {
                MountItem::Frame { id, frame } => Some((*id, frame.origin.y.0)),
                _ => None,
            })
            .collect();
        assert_eq!(frames, [(6, 0.0), (4, 50.0)]);
    }
}