velox-renderer 0.1.2

Rendering backends (Skia) for the Velox UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
//! Renderer crate with optional backends.
//! No features enabled => stub, compiles fast.

use velox_dom::VNode;
use velox_style::Stylesheet;

/// Apply the renderer-wide UA < author < inline cascade before layout or paint.
///
/// The renderer always calls this once on a freshly-built VNode. Keeping the
/// composition here prevents a backend from accidentally dropping the UA layer.
pub fn style_vnode_with_hover<F>(vnode: &VNode, author: &Stylesheet, is_hovered: &F) -> VNode
where
    F: Fn(&str, &velox_dom::Props) -> bool,
{
    velox_style::apply_with_cascade_with_hover(vnode, author, is_hovered)
}

/// Lifecycle wiring helper — ensures `on_unmounted` / `before_destroy` hooks
/// fire even if the event loop exits via `Drop` rather than `CloseRequested`.
#[allow(dead_code)]
pub struct LifecycleCleanupGuard;

impl Drop for LifecycleCleanupGuard {
    fn drop(&mut self) {
        let _ = std::panic::catch_unwind(velox_core::lifecycle::run_all_destroy_hooks);
    }
}

#[allow(dead_code)]
pub fn ensure_mounted(flag: &mut bool) {
    if !*flag {
        *flag = true;
        velox_core::lifecycle::run_all_mounted_hooks();
    }
}

/// Return the VNode at a child source-index path, if it exists.
pub fn find_node_at_path<'a>(node: &'a VNode, path: &[usize]) -> Option<&'a VNode> {
    let mut cur = node;
    for &idx in path {
        match cur {
            VNode::Element { children, .. } => cur = children.get(idx)?,
            _ => return None,
        }
    }
    Some(cur)
}

/// Unified logical size helper — single rounding point for all frame paths.
/// Delegates to Viewport::from_i32 for consistent clamping; kept as free function for compat.
#[cfg(any(feature = "skia-native", test))]
fn viewport_logical_dimensions(width: i32, height: i32, scale_factor: f32) -> (u32, u32) {
    Viewport::from_i32(width, height, scale_factor).logical_size()
}

#[cfg(feature = "skia-native")]
pub fn logical_size(width: i32, height: i32, scale_factor: f32) -> (u32, u32) {
    viewport_logical_dimensions(width, height, scale_factor)
}

/// Notify resize hooks only after a coalesced physical resize has committed and
/// its logical viewport differs from the last committed size.
#[cfg(any(feature = "skia-native", test))]
fn dispatch_resize_if_changed(
    committed: bool,
    logical: (u32, u32),
    last_resize_size: &mut Option<(u32, u32)>,
) {
    if committed && *last_resize_size != Some(logical) {
        velox_core::lifecycle::run_resize_hooks(logical.0, logical.1);
        *last_resize_size = Some(logical);
    }
}

#[cfg(any(feature = "skia-native", test))]
fn frame_logical_size(
    width: i32,
    height: i32,
    scale_factor: f32,
    committed: bool,
    last_resize_size: &mut Option<(u32, u32)>,
) -> (u32, u32) {
    let logical = viewport_logical_dimensions(width, height, scale_factor);
    dispatch_resize_if_changed(committed, logical, last_resize_size);
    logical
}

/// Per-renderer resize state. Physical events are coalesced here and the
/// committed logical baseline is kept locally to this window/event loop.
#[cfg(any(feature = "skia-native", test))]
struct ResizeState {
    pending_resize: Option<(u32, u32)>,
    last_resize_size: Option<(u32, u32)>,
}

#[cfg(any(feature = "skia-native", test))]
impl ResizeState {
    fn new() -> Self {
        Self {
            pending_resize: None,
            last_resize_size: None,
        }
    }

    fn queue(&mut self, physical: (u32, u32)) {
        self.pending_resize = Some(physical);
    }

    fn take_pending(&mut self) -> Option<(u32, u32)> {
        self.pending_resize.take()
    }

    fn record_initial(&mut self, width: i32, height: i32, scale_factor: f32) -> (u32, u32) {
        let logical = viewport_logical_dimensions(width, height, scale_factor);
        self.last_resize_size = Some(logical);
        logical
    }

    fn frame_logical_size(
        &mut self,
        width: i32,
        height: i32,
        scale_factor: f32,
        committed: bool,
    ) -> (u32, u32) {
        frame_logical_size(
            width,
            height,
            scale_factor,
            committed,
            &mut self.last_resize_size,
        )
    }
}

/// Build hit-test targets from a precomputed layout. No layout recompute here.
#[cfg(feature = "skia-native")]
fn recompute_targets(
    vnode: &velox_dom::VNode,
    layout: &velox_dom::layout::LayoutNode,
    click_targets: &mut Vec<crate::events::ClickTarget>,
    hover_targets: &mut Vec<crate::events::HoverTarget>,
    input_targets: &mut Vec<crate::events::InputTarget>,
) {
    click_targets.clear();
    let mut order = 0;
    crate::events::collect_click_targets(
        vnode,
        layout,
        None,
        crate::events::StackCtx::ROOT,
        &mut order,
        click_targets,
    );
    hover_targets.clear();
    let mut order = 0;
    crate::events::collect_hover_targets(
        vnode,
        layout,
        None,
        crate::events::StackCtx::ROOT,
        &mut order,
        hover_targets,
    );
    // Edit state (focus / caret / selection / blink phase) lives on the targets,
    // and a target rebuild throws it all away. Move the old vector aside and
    // re-apply it onto the freshly collected targets by tree path, so a
    // re-render does not silently drop the caret. `std::mem::take` is only a
    // move — the fresh collection below reuses the same allocation.
    let previous = std::mem::take(input_targets);
    let mut order = 0;
    let mut path = Vec::new();
    crate::events::collect_input_targets(
        vnode,
        layout,
        None,
        crate::events::StackCtx::ROOT,
        &mut path,
        &mut order,
        input_targets,
    );
    crate::events::preserve_input_state(input_targets, &previous, &|p| {
        input_value_char_len(vnode, p)
    });
}

#[cfg(feature = "skia-native")]
fn with_hover_ids(vnode: &velox_dom::VNode, next_id: &mut u32) -> velox_dom::VNode {
    match vnode {
        velox_dom::VNode::Text(_) => vnode.clone(),
        velox_dom::VNode::Element {
            tag,
            props,
            children,
        } => {
            let mut new_props = props.clone();
            if crate::events::is_hoverable(tag, props) {
                let id = *next_id;
                *next_id += 1;
                new_props = new_props.set("data-hover-id", id.to_string());
            }
            let new_children = children
                .iter()
                .map(|c| with_hover_ids(c, next_id))
                .collect();
            velox_dom::VNode::Element {
                tag: tag.clone(),
                props: new_props,
                children: new_children,
            }
        }
    }
}

/// Caret blink half-period, in milliseconds.
///
/// 530 ms is the conventional caret cadence. It is a named const rather than a
/// literal at the call site because the tick interval, the "solid while
/// typing" grace window, and the post-key re-arm deadline must all agree.
#[cfg(feature = "skia-native")]
const CARET_BLINK_MS: u64 = 530;

/// Posts a recurring `UserEvent` to the winit event loop so the caret blink has
/// a clock.
///
/// Why there is a thread at all: the loops run with `ControlFlow::Wait`, so they
/// only wake for real OS events. A bare `Instant::now()` deadline check inside
/// the event closure would therefore never fire while the user is idle, and the
/// caret would freeze solid. winit 0.28 has no timer API, so the tick has to
/// come in as a user event.
///
/// Why this is not a shared-state race: the thread owns nothing but an
/// `EventLoopProxy`, a cloned copy of the tick payload, and an `AtomicBool`
/// stop flag. It has no reference to `input_targets`, the VNode, the renderer,
/// or the presenter — it cannot read or write renderer state at all. Every
/// `blink_on` mutation happens on the event-loop thread, inside the event
/// closure, where the renderer is already single-threaded. This is exactly the
/// property a `Mutex<InputState>` design would have had to give up.
///
/// The thread is joined in `Drop`, so closing the window does not leave a
/// detached ticker posting events at a dead loop.
#[cfg(feature = "skia-native")]
struct CaretBlinkTicker<T: Clone + Send + 'static> {
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
    handle: Option<std::thread::JoinHandle<()>>,
    /// The tick payload is moved into the thread, so the struct itself does
    /// not otherwise mention `T`. This marker is what ties the type parameter
    /// to the type; it is zero-sized and owns nothing.
    _tick: std::marker::PhantomData<fn() -> T>,
}

#[cfg(feature = "skia-native")]
impl<T: Clone + Send + 'static> CaretBlinkTicker<T> {
    /// Start ticking. `tick` is the payload posted on every interval — `()` for
    /// the plain loop, [`HmrMessage::KeepWindow`] for the HMR loop, whose
    /// channel is typed.
    fn start(proxy: winit::event_loop::EventLoopProxy<T>, tick: T) -> Self {
        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let stop_thread = std::sync::Arc::clone(&stop);
        let period = std::time::Duration::from_millis(CARET_BLINK_MS);
        let handle = std::thread::Builder::new()
            .name("velox-caret-blink".into())
            .spawn(move || {
                while !stop_thread.load(std::sync::atomic::Ordering::Relaxed) {
                    std::thread::sleep(period);
                    if stop_thread.load(std::sync::atomic::Ordering::Relaxed) {
                        break;
                    }
                    // winit 0.28's `EventLoopProxy<T>::send_event` takes the
                    // user-event payload `T` directly — the platform layer wraps
                    // it into `Event::UserEvent(..)` on delivery. Sending fails
                    // once the loop is gone, which is the exit condition.
                    if proxy.send_event(tick.clone()).is_err() {
                        break;
                    }
                }
            })
            .ok();
        Self {
            stop,
            handle,
            _tick: std::marker::PhantomData,
        }
    }
}

#[cfg(feature = "skia-native")]
impl<T: Clone + Send + 'static> Drop for CaretBlinkTicker<T> {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
        if let Some(h) = self.handle.take() {
            let _ = h.join();
        }
    }
}

/// Advance the caret blink phase on a ticker event.
///
/// Returns `true` when the phase actually flipped and the frame must be
/// repainted. A tick that arrives inside the "solid while typing" window set by
/// a keypress or a focus change does *not* flip: it only re-arms the deadline,
/// which is what stops the caret from blinking off milliseconds after a
/// keystroke.
#[cfg(feature = "skia-native")]
fn on_caret_blink_tick(
    input_targets: &mut [crate::events::InputTarget],
    blink_deadline: &mut Option<std::time::Instant>,
) -> bool {
    let Some(idx) = crate::events::focused_input_index(input_targets) else {
        return false;
    };
    let now = std::time::Instant::now();
    if let Some(d) = *blink_deadline
        && now < d
    {
        return false;
    }
    input_targets[idx].blink_on = !input_targets[idx].blink_on;
    *blink_deadline = Some(now + std::time::Duration::from_millis(CARET_BLINK_MS));
    true
}

/// Re-arm the blink grace window after a keypress or focus change.
///
/// This is the "caret goes solid while you type" rule: any editing action
/// defers the next phase flip by one cadence period. Without it a keystroke
/// landing just before a tick would be blinked off a few milliseconds later,
/// which reads as flicker rather than as a caret.
#[cfg(feature = "skia-native")]
fn arm_blink_deadline(blink_deadline: &mut Option<std::time::Instant>) {
    *blink_deadline =
        Some(std::time::Instant::now() + std::time::Duration::from_millis(CARET_BLINK_MS));
}

/// Read a declaration out of a cascaded `style` attribute (`"a: b; c: d"`).
#[cfg(feature = "skia-native")]
fn style_decl<'s>(style: &'s str, key: &str) -> Option<&'s str> {
    style
        .split(';')
        .filter_map(|d| d.split_once(':'))
        .find(|(k, _)| k.trim() == key)
        .map(|(_, v)| v.trim())
}

/// The painter's own geometry for a text input's value text: content edges
/// **and** the font size its advances are measured at.
///
/// The click-to-caret mapping is relative to `text_left`, so padding shifts
/// the caret to match the painted glyphs.
///
/// This delegates to [`crate::input_metrics::input_text_metrics`] rather than
/// reading the authored string. It used to look up the literal key
/// `padding-left`, which is never present: the cascade does not expand
/// shorthands, so `padding: 6px 10px` survives under the key `padding` and the
/// lookup missed it, returning `rect.x + 0` while the paint lane drew glyphs at
/// `text_left`. Click-to-caret therefore disagreed with the painted glyphs by
/// the whole left padding, and only an inline `padding-left` happened to work.
/// Reading the *computed* side is the fix; the paint lane already calls the
/// same function, so the two lanes can no longer drift.
///
/// Returning the whole struct — rather than just `.text_left` — is what makes
/// the second half of the bug unrepresentable. The origin used to be shared
/// while the font size was re-derived by a lane-local `parse_px` that accepted
/// only a literal `px` suffix, so `em`/`%`/`rem` and bare inheritance all
/// collapsed to a fallback and every advance came out `16/14` too wide: a
/// click at the far end of the value landed the caret about one character
/// short for every seven clicked. One call, both fields.
///
/// `viewport` is the **logical** `(w, h)` the paint lane resolves `vw`/`vh`
/// against, so `padding-left: 2vw` lands the caret on the glyph in both lanes.
#[cfg(feature = "skia-native")]
fn resolve_text_metrics(
    props: &velox_dom::Props,
    rect: velox_dom::layout::Rect,
    viewport: (f32, f32),
) -> crate::input_metrics::InputTextMetrics {
    crate::input_metrics::input_text_metrics(
        props.attrs.get("style").map(|s| s.as_str()),
        rect,
        viewport,
        // This lane has no inheritance context, so it cannot read the parent's
        // size. The painter's root `TextStyle` IS that context — the size an
        // element that declares no `font-size` of its own paints at — so its
        // constant is the stand-in, and it must be the same number in both
        // lanes. Passing `DEFAULT_ROOT_FONT_SIZE` (16) here instead meant a field
        // with no `font-size` was measured 16/14 too wide and its `em` padding
        // resolved against 16 while paint used 14.
        crate::skia_render::PAINT_ROOT_FONT_SIZE,
    )
}

/// The `value` attribute of the element at `path`, if it is an element.
#[cfg(feature = "skia-native")]
fn input_value_at(vnode: &VNode, path: &[usize]) -> Option<String> {
    match find_node_at_path(vnode, path) {
        Some(VNode::Element { props, .. }) => {
            Some(props.attrs.get("value").cloned().unwrap_or_default())
        }
        _ => None,
    }
}

/// Char length of the value at `path`, 0 when there is no such input.
#[cfg(feature = "skia-native")]
fn input_value_char_len(vnode: &VNode, path: &[usize]) -> usize {
    input_value_at(vnode, path)
        .map(|s| s.chars().count())
        .unwrap_or(0)
}

/// Dispatch an explicit new value to the input at `path` via its `on:input`
/// handler, so the app's state and the next `make_view` see the edit.
#[cfg(feature = "skia-native")]
fn dispatch_input_value(
    last_vnode: &Option<VNode>,
    path: &[usize],
    new_value: &str,
    on_event: &mut impl FnMut(&str, Option<&str>),
) {
    let Some(vnode) = last_vnode else { return };
    let Some(node) = find_node_at_path(vnode, path) else {
        return;
    };
    let VNode::Element { props, .. } = node else {
        return;
    };
    let Some(handler) = props.attrs.get("on:input").cloned() else {
        return;
    };
    on_event(&handler, Some(new_value));
}

/// Apply one editing action to the focused input and dispatch any text change.
///
/// Shared by both event loops — that shared call is what keeps the HMR loop
/// from drifting away from the plain one again. Returns `true` when the caller
/// must repaint.
///
/// Public because a host that drives its own key handling needs the same
/// sequence the loops run, and because "is a keypress additive?" is only
/// testable if both halves of a keypress can be driven in one test.
#[cfg(feature = "skia-native")]
pub fn apply_edit_to_focused(
    input_targets: &mut [crate::events::InputTarget],
    action: crate::events::EditAction,
    last_vnode: &Option<VNode>,
    focused_input: &mut Option<Vec<usize>>,
    on_event: &mut impl FnMut(&str, Option<&str>),
) -> bool {
    let Some(idx) = crate::events::focused_input_index(input_targets) else {
        return false;
    };
    let path = input_targets[idx].path.clone();
    let value = last_vnode
        .as_ref()
        .and_then(|v| input_value_at(v, &path))
        .unwrap_or_default();
    let res = crate::events::apply_edit(&mut input_targets[idx], &value, action);
    if res.submit {
        // Submit always dispatches: with no selection the text is unchanged, and
        // the handler still has to see the submission.
        let v = res.value.clone().unwrap_or_else(|| value.clone());
        dispatch_input_value(last_vnode, &path, &v, on_event);
    } else if let Some(new_value) = &res.value {
        dispatch_input_value(last_vnode, &path, new_value, on_event);
    }
    // `InputTarget::focused` is the single source of truth for focus; the
    // loop's `focused_input` is its index-free mirror, so it has to follow
    // whatever the action did to the flag rather than drift one keypress
    // behind it. Every action except `Blur` leaves focus alone.
    if matches!(action, crate::events::EditAction::Blur) {
        *focused_input = None;
    }
    res.needs_repaint()
}

/// Resolve the VirtualKeyCode of a key event into an editing action, honouring
/// the Shift modifier. Returns `None` for keys that are not editing commands.
///
/// The match is closed on purpose: it is the *editor's* vocabulary, and a key
/// that is not an editing command has no business acquiring one just because an
/// app also listens for it. The author-facing listening vocabulary is
/// [`key_name`], and the two are peers rather than a chain — see
/// [`dispatch_keydown`], which runs both on the same press.
#[cfg(feature = "skia-native")]
pub fn edit_action_for_key(
    keycode: winit::event::VirtualKeyCode,
    shift: bool,
) -> Option<crate::events::EditAction> {
    use crate::events::EditAction;
    use winit::event::VirtualKeyCode as K;
    Some(match keycode {
        K::Left => EditAction::MoveLeft { shift },
        K::Right => EditAction::MoveRight { shift },
        K::Home => EditAction::Home { shift },
        K::End => EditAction::End { shift },
        K::Back => EditAction::Backspace,
        K::Delete => EditAction::Delete,
        K::Return => EditAction::Submit,
        // Esc ends the editing session: focus, selection and caret go, the
        // value stays. This match is closed — there is no fallthrough to user
        // code — so Esc belongs here or the user has no way out of a field.
        K::Escape => EditAction::Blur,
        _ => return None,
    })
}

/// Stable, author-facing name for a key press.
///
/// This is the whole payload contract of `@keydown`, and it is a *string*, not
/// the winit enum, for three reasons:
///
/// - the enum is a dependency's type, so putting it in a `.vx` handler's
///   signature would leak `winit` (and an optional feature) into every app;
/// - winit spells its variants `Key1`, `Numpad0`, `LWin`; an author writes
///   `"1"`, `"0"`, `"MetaLeft"`-or-`"Super"`, never the crate's spelling;
/// - a name is a *value*, so it can be compared, matched, printed and stored,
///   which is what an `if key == "F2"` branch needs.
///
/// The vocabulary is the DOM `KeyboardEvent.key` convention where the two
/// disagree (`"Enter"` not `"Return"`, `" "`-as-`"Space"`, `"Escape"`), and
/// upper-case bare letters so a shifted key is the *same* name as an unshifted
/// one — `shift` is not reported, and folding it into the name would mean an
/// author cannot tell `a` from `A` when they cannot tell them apart either.
/// Anything outside the table becomes `"Unidentified"`.
#[cfg(feature = "skia-native")]
pub fn key_name(keycode: winit::event::VirtualKeyCode) -> &'static str {
    use winit::event::VirtualKeyCode as K;
    match keycode {
        K::A => "A",
        K::B => "B",
        K::C => "C",
        K::D => "D",
        K::E => "E",
        K::F => "F",
        K::G => "G",
        K::H => "H",
        K::I => "I",
        K::J => "J",
        K::K => "K",
        K::L => "L",
        K::M => "M",
        K::N => "N",
        K::O => "O",
        K::P => "P",
        K::Q => "Q",
        K::R => "R",
        K::S => "S",
        K::T => "T",
        K::U => "U",
        K::V => "V",
        K::W => "W",
        K::X => "X",
        K::Y => "Y",
        K::Z => "Z",
        K::Key0 => "0",
        K::Key1 => "1",
        K::Key2 => "2",
        K::Key3 => "3",
        K::Key4 => "4",
        K::Key5 => "5",
        K::Key6 => "6",
        K::Key7 => "7",
        K::Key8 => "8",
        K::Key9 => "9",
        K::F1 => "F1",
        K::F2 => "F2",
        K::F3 => "F3",
        K::F4 => "F4",
        K::F5 => "F5",
        K::F6 => "F6",
        K::F7 => "F7",
        K::F8 => "F8",
        K::F9 => "F9",
        K::F10 => "F10",
        K::F11 => "F11",
        K::F12 => "F12",
        K::Up => "ArrowUp",
        K::Down => "ArrowDown",
        K::Left => "ArrowLeft",
        K::Right => "ArrowRight",
        K::Back => "Backspace",
        K::Delete => "Delete",
        K::Insert => "Insert",
        K::Home => "Home",
        K::End => "End",
        K::PageUp => "PageUp",
        K::PageDown => "PageDown",
        K::Return | K::NumpadEnter => "Enter",
        K::Escape => "Escape",
        K::Tab => "Tab",
        K::Space => "Space",
        K::LShift | K::RShift => "Shift",
        K::LControl | K::RControl => "Control",
        K::LAlt | K::RAlt => "Alt",
        K::LWin | K::RWin => "Meta",
        _ => "Unidentified",
    }
}

/// Focus the input the author named `data-focus-id="id"`.
///
/// The stable-name entry point, for a caller that already knows *which* field it
/// means — a host embedding the renderer that drives focus itself, or a test.
/// Resolution runs through the same [`crate::events::find_focus_id_path`] the
/// `@keydown` grant uses, so "focus the composer" means one thing in this
/// codebase no matter which door it came through.
///
/// Returns `true` when focus actually moved, so an already-focused field is not
/// mistaken for a change and does not have its caret reset.
#[cfg(feature = "skia-native")]
pub fn focus_input_by_id(
    input_targets: &mut [crate::events::InputTarget],
    last_vnode: &Option<VNode>,
    focused_input: &mut Option<Vec<usize>>,
    id: &str,
) -> bool {
    let Some(vnode) = last_vnode.as_ref() else {
        return false;
    };
    let Some(path) = crate::events::find_focus_id_path(vnode, &[], id) else {
        return false;
    };
    // Expressed as a one-focus `KeydownPlan` so this and the key path run the
    // same grant code — the flag, the caret, the anchor, the blink and the
    // index-free mirror are all written in exactly one place.
    let plan = crate::events::KeydownPlan {
        focus_paths: vec![path],
        ..Default::default()
    };
    crate::events::apply_keydown(
        &plan,
        "",
        input_targets,
        focused_input,
        &|p: &[usize]| input_value_char_len(vnode, p),
        &mut (|_: &str, _: Option<&str>| {}),
    )
}

/// Route one key press to the app: declarative focus grants plus every
/// `on:keydown` handler, with the key's [`key_name`] as the payload.
///
/// Shared by both event loops, for the same reason `apply_edit_to_focused` is:
/// the HMR loop drifting from the plain one is not a theoretical risk, it is the
/// specific bug that indirection exists to prevent. Returns `true` when the
/// caller must repaint.
///
/// Both loops call this from the key arm *before* the reload/quit guard and
/// outside the `match` that routes editing keys, and it returns no instruction
/// to consume the key. That placement is the additive contract made structural
/// instead of documented: `dispatch_keydown` and the editing branch are
/// siblings, so swallowing a keystroke would take deleting the adjacency to do.
#[cfg(feature = "skia-native")]
pub fn dispatch_keydown(
    keycode: winit::event::VirtualKeyCode,
    input_targets: &mut [crate::events::InputTarget],
    last_vnode: &Option<VNode>,
    focused_input: &mut Option<Vec<usize>>,
    on_event: &mut impl FnMut(&str, Option<&str>),
) -> bool {
    let name = crate::key_name(keycode);
    let Some(vnode) = last_vnode.as_ref() else {
        return false;
    };
    let plan = crate::events::plan_keydown(vnode, name);
    crate::events::apply_keydown(
        &plan,
        name,
        input_targets,
        focused_input,
        &|p: &[usize]| input_value_char_len(vnode, p),
        on_event,
    )
}

/// Inject the caret/selection/focus contract onto every text input in the tree.
///
/// Paint never reads live event state. It reads these five attrs off the styled
/// VNode, which is what makes the caret headless-testable — a golden can be
/// produced from a VNode alone, with no event loop running:
///
/// - `caret`       — caret position as a char index into the value
/// - `caret_blink` — `"true"` when the caret bar is visible this frame
/// - `sel_start`   — selection start char index (== `caret` when collapsed)
/// - `sel_end`     — selection end char index
/// - `focused`     — `"true"` when the input holds keyboard focus
///
/// Runs *after* `style_vnode_with_hover` (the single style-cascade application
/// site) and before layout, so it adds no second cascade and no second
/// rounding. Every text input always carries all five attrs, so paint never has
/// to invent a default for a missing one.
#[cfg(feature = "skia-native")]
fn inject_input_caret_attrs(vnode: &VNode, focused: Option<&crate::events::InputTarget>) -> VNode {
    /// Descend one level. `on_path` means "this node is an ancestor of (or is)
    /// the focused input"; `focused_path` is the remainder to match.
    fn walk(
        node: &VNode,
        focused_path: Option<&[usize]>,
        on_path: bool,
        focused: Option<&crate::events::InputTarget>,
    ) -> VNode {
        match node {
            VNode::Text(_) => node.clone(),
            VNode::Element {
                tag,
                props,
                children,
            } => {
                let mut new_props = props.clone();
                if crate::events::is_text_input(tag, props) {
                    let (is_focused, cursor, blink, sel_start, sel_end) = match focused {
                        Some(t) if on_path => {
                            let (a, b) = t.selection().unwrap_or((t.cursor, t.cursor));
                            (true, t.cursor, t.blink_on, a, b)
                        }
                        // Unfocused inputs still get the attrs, so paint reads
                        // a total contract rather than guessing at absence.
                        _ => (false, 0, true, 0, 0),
                    };
                    new_props = new_props
                        .set("focused", if is_focused { "true" } else { "false" })
                        .set("caret", cursor.to_string())
                        .set("caret_blink", if blink { "true" } else { "false" })
                        .set("sel_start", sel_start.to_string())
                        .set("sel_end", sel_end.to_string());
                }
                let new_children = children
                    .iter()
                    .enumerate()
                    .map(|(i, child)| {
                        let child_on_path = on_path
                            && focused_path
                                .and_then(|p| p.first())
                                .map(|first| *first == i)
                                .unwrap_or(false);
                        let rest = if child_on_path {
                            focused_path.map(|p| &p[1..])
                        } else {
                            None
                        };
                        walk(child, rest, child_on_path, focused)
                    })
                    .collect();
                VNode::Element {
                    tag: tag.clone(),
                    props: new_props,
                    children: new_children,
                }
            }
        }
    }

    let focused_path = focused.map(|t| t.path.as_slice());
    walk(vnode, focused_path, true, focused)
}

/// Effective font family of a styled element, for caret hit testing.
#[cfg(feature = "skia-native")]
fn resolve_font_family(props: &velox_dom::Props) -> String {
    props
        .attrs
        .get("style")
        .and_then(|s| style_decl(s, "font-family"))
        .filter(|f| !f.is_empty())
        .unwrap_or("system-ui, sans-serif")
        .to_string()
}

/// The **logical** `(w, h)` the paint lane will resolve `vw`/`vh` against this
/// frame, read from the live surface.
///
/// Read from the surface, not a constant, precisely so it cannot disagree with
/// paint: `render_frame` resolves viewport units against the same surface
/// dimensions through the same [`logical_size`] rounding. A surface-less
/// (headless) renderer yields `(0.0, 0.0)`, which only matters for
/// viewport-unit padding — and there is nothing painted to disagree with.
#[cfg(feature = "skia-native")]
fn surface_logical_viewport(
    renderer: &skia_backend::SkiaRenderer,
    scale_factor: f32,
) -> (f32, f32) {
    match &renderer.surface {
        Some(s) => {
            let (w, h) = logical_size(s.width, s.height, scale_factor);
            (w as f32, h as f32)
        }
        None => (0.0, 0.0),
    }
}

/// Move keyboard focus to the text input under the cursor (or drop focus),
/// and place the caret.
///
/// Shared by both event loops for the same reason `apply_edit_to_focused` is:
/// the HMR loop used to have no focus handling at all, and a second copy of
/// this is how the drift happened.
///
/// Caret placement differs by case, and the difference is deliberate:
/// - clicking an input that did **not** have focus is a focus *gain*, so the
///   caret goes to the end of the value (the conventional behaviour, and what
///   makes "click a field and start typing" replace rather than prepend);
/// - clicking an input that already had focus is a reposition, so the caret
///   goes to the clicked glyph via [`crate::events::click_to_char_index`].
///
/// Returns `true` when the caller must repaint — i.e. focus actually changed or
/// the caret moved.
///
/// `viewport` is the **logical** `(w, h)` the paint lane uses this frame (see
/// [`surface_logical_viewport`]). It is threaded in rather than reconstructed
/// here because the caret's origin is computed from the same lengths paint
/// resolves: pass a different viewport and a `vw`/`vh` field puts its caret in
/// one place and its glyphs in another.
#[cfg(feature = "skia-native")]
fn apply_click_focus(
    input_targets: &mut [crate::events::InputTarget],
    last_vnode: &Option<VNode>,
    focused_input: &mut Option<Vec<usize>>,
    x: f32,
    y: f32,
    scale_factor: f32,
    viewport: (f32, f32),
) -> bool {
    let Some(idx) = crate::events::hit_test_input_index(input_targets, x, y) else {
        // Clicked empty space: blur. Clearing the selection is what stops a
        // stale highlight from surviving on a field the user has left. The
        // caret position is deliberately kept, so re-entering the field
        // restores where the user was.
        let changed = crate::events::blur_focused_input(input_targets);
        return changed || focused_input.take().is_some();
    };

    let was_focused = input_targets[idx].focused;
    let rect = input_targets[idx].rect;
    let path = input_targets[idx].path.clone();
    let mut caret: Option<usize> = None;
    let mut value_len: Option<usize> = None;
    if let Some(vnode) = last_vnode.as_ref()
        && let Some(VNode::Element { props, .. }) = find_node_at_path(vnode, &path)
    {
        let value = props.attrs.get("value").cloned().unwrap_or_default();
        value_len = Some(value.chars().count());
        // ONE call for both the origin and the font size. Taking the origin
        // from here and the size from anywhere else is the defect this shape
        // removes: two lanes that must agree, each holding its own constant.
        let metrics = resolve_text_metrics(props, rect, viewport);
        let font_size = metrics.font_size;
        let config = crate::text::TextRenderConfig::new(&resolve_font_family(props), font_size);
        // Measure through the renderer's own text stack (single measure path,
        // skia-aware under `skia-native`) rather than a local heuristic, so the
        // caret lands on the glyph the paint lane will actually draw.
        let measure =
            |s: &str| crate::text::TextMeasurer::measure_with_scale(s, &config, scale_factor).0;
        caret = Some(crate::events::click_to_char_index(
            &value,
            rect,
            x,
            metrics.text_left,
            font_size,
            &measure,
        ));
    }

    // The one place focus is granted. `focus_input` also blurs any other field
    // that held focus, so a click straight from one field to another cannot
    // leave two of them flagged.
    crate::events::focus_input(input_targets, idx);
    input_targets[idx].blink_on = true;
    // A plain click is never a selection-extension; it collapses one.
    input_targets[idx].anchor = None;
    // `cursor` is a char index, so "the end" is the char count, not `len()`.
    input_targets[idx].cursor = if was_focused {
        caret.unwrap_or(input_targets[idx].cursor)
    } else {
        // Focus gain: caret to the end of the value.
        value_len.unwrap_or(input_targets[idx].cursor)
    };
    *focused_input = Some(path);
    true
}

pub mod event_binding;
pub mod events;
pub mod hmr;
// The single authority on an `<input>`'s content-box geometry. Public so both
// `skia_render`'s paint lane and `lib.rs`'s hit-test lane reach the SAME
// function instead of each growing an inset of its own, and so a test can
// assert against it without re-deriving the painter's arithmetic.
pub mod input_metrics;
pub mod text;
pub mod viewport;

pub use hmr::{DEFAULT_HMR_PORT, HmrMessage, hmr_config, run_hmr_client};
pub use viewport::{LogicalSize, PhysicalSize, Viewport};

// Native Skia GL helper module (feature-gated)
#[cfg(feature = "skia-native")]
mod skia_gl;
// Skia surface and renderer helpers (feature-gated)
#[cfg(feature = "skia-native")]
mod skia_render;
#[cfg(feature = "skia-native")]
pub mod skia_surface;
// Softbuffer presenter for window rendering (feature-gated)
#[cfg(feature = "skia-native")]
mod presenter;
#[cfg(feature = "skia-native")]
pub use skia_render::skia_impl::render_vnode_to_rgba;
// Test/diagnostic only, and public only because `tests/` is a separate crate
// that cannot see a private module. The decode counter is the honest way to
// assert the persistent `<img src>` cache works; a timing assertion would
// measure the machine instead of the cache. See `IMAGE_DECODE_COUNT`.
#[cfg(feature = "skia-native")]
pub use skia_render::skia_impl::{image_decode_count, reset_image_decode_count};
#[cfg(feature = "skia-native")]
pub use skia_render::{render_vnode_to_raster_png, render_vnode_to_raster_png_with_scale};

/// In-memory representation of a mounted tree (stubbed for now).
pub struct RenderTree {
    pub root: VNode,
    pub node_count: usize,
    pub text_count: usize,
}

#[derive(Debug, Clone, PartialEq)]
pub struct A11yNode {
    pub id: usize,
    pub role: String,
    pub name: String,
    pub rect: velox_dom::layout::Rect,
    pub children: Vec<A11yNode>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct A11yTree {
    pub root: A11yNode,
}

pub trait HmrRenderer {
    /// Initialize the rendering backend (e.g. create DirectContext, verify GPU).
    fn init() -> Result<(), String>
    where
        Self: Sized;

    /// Mount a VNode into the renderer for display.
    fn mount(&mut self, vnode: VNode) -> Result<(), String>;

    /// Hot-update the rendered VNode.
    fn hot_update(&mut self, new_vnode: VNode) -> Result<(), String>;

    /// Get the raw window handle for platform integration.
    fn get_window_handle(&self) -> *mut std::ffi::c_void;
}

/// High-level renderer lifecycle trait. Backends implement this to expose
/// a consistent `new -> mount -> hot_update` workflow that returns `Result`
/// instead of panicking on failure.
pub trait VeloxRenderer {
    /// Construct a new renderer instance.
    fn new() -> Result<Self, String>
    where
        Self: Sized;

    /// Mount a VNode tree for rendering, returning an error on failure.
    fn mount(&mut self, vnode: VNode) -> Result<(), String>;

    /// Hot-replace the rendered VNode tree, returning an error on failure.
    fn hot_update(&mut self, new_vnode: VNode) -> Result<(), String>;
}

fn summarize(v: &VNode, counts: &mut (usize, usize)) {
    match v {
        VNode::Text(_) => {
            counts.0 += 1;
            counts.1 += 1;
        }
        VNode::Element { children, .. } => {
            counts.0 += 1;
            for c in children {
                summarize(c, counts);
            }
        }
    }
}

fn build_render_tree(v: &VNode) -> RenderTree {
    let mut counts = (0, 0);
    summarize(v, &mut counts);
    RenderTree {
        root: v.clone(),
        node_count: counts.0,
        text_count: counts.1,
    }
}

fn vnode_text_content(node: &VNode) -> String {
    match node {
        VNode::Text(t) => t.clone(),
        VNode::Element { children, .. } => {
            let mut out = String::new();
            for ch in children {
                let s = vnode_text_content(ch);
                if !s.is_empty() {
                    if !out.is_empty() {
                        out.push(' ');
                    }
                    out.push_str(&s);
                }
            }
            out
        }
    }
}

fn a11y_role_for(tag: &str, props: &velox_dom::Props) -> String {
    if let Some(role) = props.attrs.get("role") {
        return role.clone();
    }
    match tag {
        "button" => "button",
        "img" => "image",
        "input" => "textbox",
        "label" => "label",
        "a" => "link",
        _ => "group",
    }
    .to_string()
}

fn a11y_name_for(tag: &str, props: &velox_dom::Props, node: &VNode) -> String {
    if let Some(label) = props.attrs.get("aria-label") {
        return label.clone();
    }
    if tag == "img"
        && let Some(alt) = props.attrs.get("alt")
    {
        return alt.clone();
    }
    vnode_text_content(node)
}

fn build_a11y_tree_with_layout(
    vnode: &VNode,
    layout: &velox_dom::layout::LayoutNode,
    next_id: &mut usize,
) -> A11yNode {
    let id = *next_id;
    *next_id += 1;
    match vnode {
        VNode::Text(t) => A11yNode {
            id,
            role: "text".to_string(),
            name: t.clone(),
            rect: layout.rect,
            children: Vec::new(),
        },
        VNode::Element {
            tag,
            props,
            children,
            ..
        } => {
            let mut child_nodes = Vec::new();
            for ch_layout in &layout.children {
                if ch_layout.display_none {
                    continue;
                }
                if let Some(src_idx) = ch_layout.source_index
                    && let Some(ch) = children.get(src_idx)
                {
                    child_nodes.push(build_a11y_tree_with_layout(ch, ch_layout, next_id));
                }
            }
            A11yNode {
                id,
                role: a11y_role_for(tag, props),
                name: a11y_name_for(tag, props, vnode),
                rect: layout.rect,
                children: child_nodes,
            }
        }
    }
}

/// Build the accessibility tree for `vnode` laid out at `width` x `height`.
///
/// DELIBERATE EXCEPTION to R-8's single-funnel invariant: this function runs its
/// own `compute_layout` and does not go through the renderer's `prepare_frame`.
///
/// The reason is that this is not a render path. It takes no `Stylesheet`, paints
/// nothing, and is given no `SkiaSurface`; its only output is a tree of roles,
/// names and rects. Funnelling it would mean inventing a stylesheet and a surface
/// for a caller that has neither, and then applying a style cascade to a tree
/// whose geometry — not its appearance — is what is being reported. It is named
/// here so the exception is on the record rather than discovered later as a
/// "missing" funnel site.
pub fn build_a11y_tree(vnode: &VNode, width: i32, height: i32) -> A11yTree {
    let layout = velox_dom::layout::compute_layout(vnode, width, height);
    let mut next_id = 1;
    let root = build_a11y_tree_with_layout(vnode, &layout, &mut next_id);
    A11yTree { root }
}

/// Minimal renderer trait. Backends implement this to expose a consistent API.
pub trait Renderer {
    fn backend_name(&self) -> &'static str;
    fn mount(&self, vnode: &VNode) -> Result<RenderTree, String>;
}

// Real Skia backend only when `skia-native` is enabled.
#[cfg(feature = "skia-native")]
pub mod skia_backend {
    use crate::HmrRenderer;
    use crate::VeloxRenderer;
    #[cfg(feature = "skia-native")]
    use crate::skia_gl;
    #[cfg(feature = "skia-native")]
    use crate::skia_surface;
    #[cfg(feature = "skia-native")]
    use raw_window_handle::HasRawWindowHandle;
    use velox_dom::VNode;

    pub fn init() -> Result<(), String> {
        match skia_gl::create_context() {
            Ok(gl_ctx) => match gl_ctx.into_direct_context() {
                Some(_dctx) => {
                    log::info!("skia backend: init OK (DirectContext created)");
                    Ok(())
                }
                None => Err("skia backend: init failed: couldn't create DirectContext".to_string()),
            },
            Err(e) => Err(format!("skia backend: init failed: {}", e)),
        }
    }

    pub struct SkiaRenderer {
        pub surface: Option<skia_surface::SkiaSurface>,
        pub vnode: Option<VNode>,
    }

    impl SkiaRenderer {
        pub fn with_window(
            window: &impl HasRawWindowHandle,
            width: i32,
            height: i32,
        ) -> Result<Self, String> {
            match skia_surface::create_window_surface_from_handle(window, width, height) {
                Ok(s) => Ok(SkiaRenderer {
                    surface: Some(s),
                    vnode: None,
                }),
                Err(e) => Err(e),
            }
        }

        pub fn present(&mut self) -> Result<(), String> {
            if let Some(s) = &mut self.surface {
                s.present()
            } else {
                Ok(())
            }
        }

        pub fn resize(&mut self, width: i32, height: i32) -> Result<(), String> {
            if let Some(s) = &mut self.surface {
                s.resize(width, height)
            } else {
                Ok(())
            }
        }
    }

    impl crate::Renderer for SkiaRenderer {
        fn backend_name(&self) -> &'static str {
            "skia"
        }
        fn mount(&self, vnode: &velox_dom::VNode) -> Result<crate::RenderTree, String> {
            Ok(crate::build_render_tree(vnode))
        }
    }

    impl HmrRenderer for SkiaRenderer {
        fn init() -> Result<(), String> {
            init()
        }

        fn mount(&mut self, vnode: VNode) -> Result<(), String> {
            self.vnode = Some(vnode);
            Ok(())
        }

        fn hot_update(&mut self, new_vnode: VNode) -> Result<(), String> {
            self.vnode = Some(new_vnode);
            Ok(())
        }

        fn get_window_handle(&self) -> *mut std::ffi::c_void {
            std::ptr::null_mut()
        }
    }

    impl VeloxRenderer for SkiaRenderer {
        fn new() -> Result<Self, String> {
            Ok(SkiaRenderer {
                surface: None,
                vnode: None,
            })
        }

        fn mount(&mut self, vnode: VNode) -> Result<(), String> {
            self.vnode = Some(vnode);
            Ok(())
        }

        fn hot_update(&mut self, new_vnode: VNode) -> Result<(), String> {
            self.vnode = Some(new_vnode);
            Ok(())
        }
    }
}

// Skia stub backend to allow compiling with `--features skia` without native deps.
#[cfg(all(feature = "skia", not(feature = "skia-native")))]
pub mod skia_backend {
    pub fn init() -> Result<(), String> {
        Ok(())
    }

    pub struct SkiaRenderer;
    impl crate::Renderer for SkiaRenderer {
        fn backend_name(&self) -> &'static str {
            "skia"
        }
        fn mount(&self, vnode: &velox_dom::VNode) -> Result<crate::RenderTree, String> {
            Ok(crate::build_render_tree(vnode))
        }
    }
    impl crate::HmrRenderer for SkiaRenderer {
        fn init() -> Result<(), String> {
            Ok(())
        }
        fn mount(&mut self, _vnode: velox_dom::VNode) -> Result<(), String> {
            Ok(())
        }
        fn hot_update(&mut self, _new_vnode: velox_dom::VNode) -> Result<(), String> {
            Ok(())
        }
        fn get_window_handle(&self) -> *mut std::ffi::c_void {
            std::ptr::null_mut()
        }
    }
    impl crate::VeloxRenderer for SkiaRenderer {
        fn new() -> Result<Self, String> {
            Ok(SkiaRenderer)
        }
        fn mount(&mut self, _vnode: velox_dom::VNode) -> Result<(), String> {
            Ok(())
        }
        fn hot_update(&mut self, _new_vnode: velox_dom::VNode) -> Result<(), String> {
            Ok(())
        }
    }
}

/// Stub init used when no backend features are enabled.
#[cfg(not(feature = "skia"))]
pub fn init() -> Result<(), String> {
    // Intentionally empty — no backend enabled
    Ok(())
}

// Simple identifier of the selected backend, useful for tests.
#[cfg(feature = "skia")]
pub const BACKEND: &str = "skia";
#[cfg(not(feature = "skia"))]
pub const BACKEND: &str = "stub";

pub fn backend_name() -> &'static str {
    BACKEND
}

/// Feature-selected renderer type and constructor for tests and examples.
#[cfg(any(feature = "skia", feature = "skia-native"))]
pub type SelectedRenderer = skia_backend::SkiaRenderer;
#[cfg(not(feature = "skia"))]
pub struct StubRenderer;
#[cfg(not(feature = "skia"))]
pub type SelectedRenderer = StubRenderer;
#[cfg(not(feature = "skia"))]
impl Renderer for StubRenderer {
    fn backend_name(&self) -> &'static str {
        "stub"
    }
    fn mount(&self, vnode: &VNode) -> Result<RenderTree, String> {
        Ok(build_render_tree(vnode))
    }
}
#[cfg(not(feature = "skia"))]
impl HmrRenderer for StubRenderer {
    fn init() -> Result<(), String> {
        Ok(())
    }
    fn mount(&mut self, _vnode: VNode) -> Result<(), String> {
        Ok(())
    }
    fn hot_update(&mut self, _new_vnode: VNode) -> Result<(), String> {
        Ok(())
    }
    fn get_window_handle(&self) -> *mut std::ffi::c_void {
        std::ptr::null_mut()
    }
}
#[cfg(not(feature = "skia"))]
impl VeloxRenderer for StubRenderer {
    fn new() -> Result<Self, String> {
        Ok(StubRenderer)
    }
    fn mount(&mut self, _vnode: VNode) -> Result<(), String> {
        Ok(())
    }
    fn hot_update(&mut self, _new_vnode: VNode) -> Result<(), String> {
        Ok(())
    }
}

/// Construct the feature-selected renderer.
pub fn new_selected_renderer() -> SelectedRenderer {
    #[cfg(feature = "skia-native")]
    {
        // Construct SkiaRenderer with no surface for the default selected renderer.
        skia_backend::SkiaRenderer {
            surface: None,
            vnode: None,
        }
    }
    #[cfg(all(feature = "skia", not(feature = "skia-native")))]
    {
        skia_backend::SkiaRenderer
    }
    #[cfg(not(feature = "skia"))]
    {
        StubRenderer
    }
}

pub use events::Runtime as EventRuntime;

/// Test helper: exercise a small Skia draw path (native-only).
#[cfg(all(feature = "skia-native", unix))]
pub fn skia_draw_test_frame() -> Result<(), String> {
    crate::skia_gl::draw_gpu_test_frame(256, 256)
}

/// Convenience wrapper to create a Skia `DirectContext` from the crate root.
///
/// Returns the owning `GlDirectContext` pair, which holds the headless EGL
/// context alongside the `DirectContext`: handing back a bare `DirectContext`
/// would return a handle whose GL context had already been destroyed.
#[cfg(all(feature = "skia-native", unix))]
pub fn create_direct_context() -> Result<crate::skia_gl::GlDirectContext, String> {
    crate::skia_gl::create_direct_context()
}

/// Extracts the human-readable message from a caught panic payload
/// (`panic!("literal")` stores `&'static str`, `format!`-based panics store
/// `String`). Used so compositor failures caught by `catch_unwind` are
/// surfaced instead of silently discarded (CX-13 / F-23).
#[cfg(feature = "skia-native")]
fn panic_detail(payload: Box<dyn std::any::Any + Send>) -> String {
    if let Some(s) = payload.downcast_ref::<&'static str>() {
        (*s).to_string()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic payload".to_string()
    }
}

// ---------------------------------------------------------------------------
// Shared window-event arms (Task 5.6b)
// ---------------------------------------------------------------------------
//
// `run_window_vnode_skia` and `run_window_vnode_skia_with_hmr` are the same loop
// written twice, and six `WindowEvent` arms were copy-pasted between them. Two
// copies means every fix has to be made twice, and this repo has already paid
// for that: the HMR keyboard arm shipped as a bare `_ => {}` stub, and the HMR
// loop had no `ReceivedCharacter` arm at all, so typing silently did nothing
// under HMR. Each function below is the single implementation of one arm, and
// both loops call it.
//
// Two rules, both load-bearing:
//
//   * These functions never touch `ControlFlow`. The loops keep every
//     `*control_flow = ...` assignment, because parking on `Wait` (not `Poll`,
//     not `WaitUntil`) is right for a non-game application: `Poll` would burn a
//     core while idle and `WaitUntil` would swallow the events these arms
//     handle. `tests/event_loop_arms.rs` pins that, and it is easier to keep
//     pinned when the control flow never leaves the loop.
//   * Shared state is passed as arguments instead of moving into a struct, so
//     the three arms that are *not* here keep reading the loop's own locals
//     under their own names — see the note on why those three stayed behind.
//
// Why six of the nine, and not nine:
//
//   * Extracted: `CloseRequested`, `Resized`, `ScaleFactorChanged`,
//     `CursorMoved`, `ModifiersChanged`, `MouseWheel`.
//   * Left in place: the left-click, `KeyboardInput` and `ReceivedCharacter`
//     arms. `tests/event_loop_arms.rs` pins their bodies as *literal source
//     text* inside each loop — `apply_click_focus(`, `&mut focused_input`,
//     `hit_test_click`, `edit_action_for_key(keycode, shift_held)`,
//     `arm_blink_deadline(&mut blink_deadline)`, `EditAction::Insert(c)` — and
//     `the_duplicated_arms_of_both_loops_make_the_same_calls` compares their
//     callee sequences so a second divergence cannot appear beside the one
//     known HMR-only `last_vnode` republish. Moving the bodies out of the
//     loops deletes that guard along with the duplicate: the drift test would
//     compare two identical one-line call sites and never see the arms again.
//     Those three are the arms the caret and typing regressions both lived in,
//     so they keep a live drift test instead of a second copy. Task 5.6 step 3
//     is what actually finishes the job — see the report for why it needs
//     production-code change before it can exist.

/// `WindowEvent::CloseRequested` — shared by both loops.
///
/// Returns `true` so the *caller* performs the exit. `ControlFlow` belongs to
/// the loop, and keeping the assignment at the call site keeps it visible to
/// the structural test.
#[cfg(feature = "skia-native")]
fn window_close_requested() -> bool {
    velox_core::lifecycle::run_all_destroy_hooks();
    true
}

/// `WindowEvent::Resized` — shared by both loops.
///
/// R-L3: coalesce. A drag produces many `Resized` events and only the last one
/// per frame may materialise, so this records the pending size and asks for a
/// redraw. It must not touch the raster surface; surface recreation belongs to
/// `RedrawRequested`.
#[cfg(feature = "skia-native")]
fn window_resized(
    resize_state: &mut ResizeState,
    window_opt: &Option<winit::window::Window>,
    size: (u32, u32),
) {
    // `ResizeState::queue` is the production `pending_resize = Some(..)` path.
    resize_state.queue(size);
    if let Some(w) = window_opt.as_ref() {
        w.request_redraw();
    }
}

/// `WindowEvent::ScaleFactorChanged` — shared by both loops.
///
/// R-M1: the physical cursor must not move when the scale factor changes, so
/// the logical `mouse_pos` is rescaled by `old / new` in the same step that
/// adopts the new factor. R-L3: the pending resize and the surface scale are
/// updated here, but nothing is recreated — layout and hit-test refresh wait
/// for `RedrawRequested` (single layout/frame, R-H5).
#[cfg(feature = "skia-native")]
fn window_scale_factor_changed(
    scale_factor: &mut f32,
    mouse_pos: &mut (f32, f32),
    resize_state: &mut ResizeState,
    surface: &mut Option<crate::skia_surface::SkiaSurface>,
    window_opt: &Option<winit::window::Window>,
    new_scale: f64,
    new_inner_size: (u32, u32),
) {
    let old_scale = *scale_factor;
    *scale_factor = new_scale as f32;
    if old_scale.is_finite() && old_scale > 0.0 && scale_factor.is_finite() && *scale_factor > 0.0 {
        mouse_pos.0 = mouse_pos.0 * old_scale / *scale_factor;
        mouse_pos.1 = mouse_pos.1 * old_scale / *scale_factor;
    }
    resize_state.queue(new_inner_size);
    if let Some(s) = surface.as_mut() {
        s.set_scale_factor(*scale_factor);
    }
    if let Some(w) = window_opt.as_ref() {
        w.request_redraw();
    }
}

/// `WindowEvent::CursorMoved` — shared by both loops.
///
/// winit reports physical pixels while hit-testing and layout are logical, so
/// the position is divided by the scale factor. Only a *change* of hover asks
/// for a redraw: a cursor move within the same target paints identically.
#[cfg(feature = "skia-native")]
fn window_cursor_moved(
    scale_factor: f32,
    mouse_pos: &mut (f32, f32),
    hover_targets: &[crate::events::HoverTarget],
    hovered_id: &mut Option<u32>,
    window_opt: &Option<winit::window::Window>,
    position: (f32, f32),
) {
    *mouse_pos = (position.0 / scale_factor, position.1 / scale_factor);
    let now_hovered = crate::events::hit_test_hover(hover_targets, mouse_pos.0, mouse_pos.1);
    if now_hovered != *hovered_id {
        *hovered_id = now_hovered;
        if let Some(w) = window_opt.as_ref() {
            w.request_redraw();
        }
    }
}

/// `WindowEvent::ModifiersChanged` — shared by both loops.
///
/// Latches Shift for Shift-extends-selection. winit 0.28 deprecates
/// `KeyboardInput::modifiers` in favour of this event, so the caret reads the
/// latched value instead of the deprecated per-key field.
#[cfg(feature = "skia-native")]
fn window_modifiers_changed(shift_held: &mut bool, shift: bool) {
    *shift_held = shift;
}

/// Convert a winit scroll delta into logical pixels, negated so that wheel-down
/// increases the scroll offset and reveals content below.
///
/// winit reports positive `y` for wheel-up; one line is 40 logical px, and
/// `PixelDelta` is physical so it needs the scale factor.
#[cfg(feature = "skia-native")]
fn window_wheel_delta_y(delta: winit::event::MouseScrollDelta, scale_factor: f32) -> f32 {
    match delta {
        winit::event::MouseScrollDelta::LineDelta(_, y) => -y * 40.0,
        winit::event::MouseScrollDelta::PixelDelta(pos) => -(pos.y as f32) / scale_factor,
    }
}

/// `WindowEvent::MouseWheel` — shared by both loops.
///
/// Scrollable overflow: the deepest scrollable under the cursor, clamped by
/// `apply_wheel_scroll`, which returns whether the offset actually moved. A
/// wheel event that arrives before the first frame has no layout to scroll and
/// must be a no-op rather than a panic.
#[cfg(feature = "skia-native")]
fn window_mouse_wheel(
    scale_factor: f32,
    mouse_pos: (f32, f32),
    last_layout: &Option<velox_dom::layout::LayoutNode>,
    scroll_offsets: &mut std::collections::HashMap<Vec<usize>, f32>,
    window_opt: &Option<winit::window::Window>,
    delta: winit::event::MouseScrollDelta,
) {
    let delta_y = window_wheel_delta_y(delta, scale_factor);
    if let Some(layout) = last_layout.as_ref()
        && crate::events::apply_wheel_scroll(
            layout,
            mouse_pos.0,
            mouse_pos.1,
            scroll_offsets,
            delta_y,
        )
        && let Some(w) = window_opt.as_ref()
    {
        w.request_redraw();
    }
}

// Behavioural tests for the shared arms.
//
// The loops themselves can only run inside a live winit window, and winit is an
// optional dependency rather than a dev-dependency, so nothing under `tests/`
// can name a `WindowEvent` and reach these functions. `tests/event_loop_arms.rs`
// pins the *source text* of what is left in the loops, which catches the two
// copies drifting apart from each other but says nothing about whether either
// one is correct. These tests are that missing check: each one states an
// observable property of a shared arm, so deleting or breaking the shared
// implementation turns them red.
//
// They run under `cargo test --features velox-renderer/skia-native`; a plain
// `cargo test -p velox-renderer` does not enable `skia-native` and does not
// compile the loops or these tests at all.
#[cfg(all(test, feature = "skia-native"))]
mod window_event_shared_tests {
    use super::*;
    use std::collections::HashMap;
    use winit::dpi::PhysicalPosition;
    use winit::event::MouseScrollDelta;

    /// Stand-in for the loop's `window_opt`. A `None` window is the case that
    /// matters for these assertions: every shared arm must still do its state
    /// work, and must simply skip the redraw request.
    fn no_window() -> Option<winit::window::Window> {
        None
    }

    fn hover_target(x: i32, y: i32, w: i32, h: i32, id: u32) -> crate::events::HoverTarget {
        crate::events::HoverTarget {
            rect: velox_dom::layout::Rect { x, y, w, h },
            id,
            z_index: 0,
            order: 0,
            clip: None,
            sc: crate::events::StackCtx::ROOT,
        }
    }

    #[test]
    fn close_requested_tells_the_caller_to_exit() {
        // `ControlFlow` is the loop's to own, so the shared arm signals instead
        // of setting it. A false here would leave the window running.
        assert!(window_close_requested());
    }

    #[test]
    fn resized_keeps_only_the_last_size_of_a_drag() {
        // R-L3 coalescing: a drag emits many `Resized` events and only the
        // final one may be committed, so a resize storm cannot queue a backlog.
        let mut state = ResizeState::new();
        let window = no_window();
        window_resized(&mut state, &window, (800, 600));
        window_resized(&mut state, &window, (1024, 768));
        assert_eq!(state.take_pending(), Some((1024, 768)));
        assert_eq!(state.take_pending(), None);
    }

    #[test]
    fn scale_factor_change_rescales_the_cursor_so_the_physical_point_is_stable() {
        // R-M1: the physical cursor does not move when the scale factor does,
        // so the logical position has to be divided by the same ratio.
        let mut state = ResizeState::new();
        let window = no_window();
        let mut surface: Option<crate::skia_surface::SkiaSurface> = None;
        let mut scale_factor = 1.0f32;
        let mut mouse_pos = (100.0f32, 200.0f32);

        window_scale_factor_changed(
            &mut scale_factor,
            &mut mouse_pos,
            &mut state,
            &mut surface,
            &window,
            2.0,
            (1920, 1080),
        );

        assert_eq!(scale_factor, 2.0);
        assert_eq!(mouse_pos, (50.0, 100.0));
        // The pending resize is queued by the same arm (R-L3).
        assert_eq!(state.take_pending(), Some((1920, 1080)));
    }

    #[test]
    fn scale_factor_change_never_divides_by_a_degenerate_old_scale() {
        // A 0, negative or NaN old scale cannot produce a meaningful ratio.
        // Rescaling by it anyway would poison `mouse_pos` with NaN or infinity,
        // after which every hover hit-test silently misses forever.
        for degenerate in [0.0f32, -1.0, f32::NAN, f32::INFINITY] {
            let mut state = ResizeState::new();
            let window = no_window();
            let mut surface: Option<crate::skia_surface::SkiaSurface> = None;
            let mut scale_factor = degenerate;
            let mut mouse_pos = (10.0f32, 20.0f32);

            window_scale_factor_changed(
                &mut scale_factor,
                &mut mouse_pos,
                &mut state,
                &mut surface,
                &window,
                2.0,
                (800, 600),
            );

            assert_eq!(
                scale_factor, 2.0,
                "old_scale={degenerate}: new scale adopted"
            );
            assert_eq!(
                mouse_pos,
                (10.0, 20.0),
                "old_scale={degenerate}: cursor left alone"
            );
            // The pending resize is not conditional on the cursor arithmetic.
            assert_eq!(state.take_pending(), Some((800, 600)));
        }
    }

    #[test]
    fn cursor_moved_converts_physical_pixels_to_logical_units() {
        // winit reports physical pixels; layout and hit-testing are logical.
        // Skipping this division puts the cursor half a screen away at 2x.
        let window = no_window();
        let mut mouse_pos = (0.0f32, 0.0f32);
        let mut hovered_id: Option<u32> = None;

        window_cursor_moved(
            2.0,
            &mut mouse_pos,
            &[],
            &mut hovered_id,
            &window,
            (300.0, 200.0),
        );

        assert_eq!(mouse_pos, (150.0, 100.0));
    }

    #[test]
    fn cursor_moved_latches_and_clears_the_hover_target_under_the_logical_cursor() {
        let window = no_window();
        let targets = [hover_target(0, 0, 200, 200, 7)];
        let mut mouse_pos = (0.0f32, 0.0f32);
        let mut hovered_id: Option<u32> = None;

        // 300 physical px at 2.0 is 150 logical, inside the 0..200 target.
        window_cursor_moved(
            2.0,
            &mut mouse_pos,
            &targets,
            &mut hovered_id,
            &window,
            (300.0, 200.0),
        );
        assert_eq!(hovered_id, Some(7));

        // Leaving the target has to clear the latch, or the hover style sticks.
        window_cursor_moved(
            2.0,
            &mut mouse_pos,
            &targets,
            &mut hovered_id,
            &window,
            (900.0, 800.0),
        );
        assert_eq!(hovered_id, None);
    }

    #[test]
    fn modifiers_changed_latches_the_shift_state_the_caret_reads() {
        // winit 0.28 deprecated the per-key `KeyboardInput::modifiers` field, so
        // Shift-extends-selection depends on this latch being the only writer.
        let mut shift_held = false;
        window_modifiers_changed(&mut shift_held, true);
        assert!(shift_held);
        window_modifiers_changed(&mut shift_held, false);
        assert!(!shift_held);
    }

    #[test]
    fn wheel_deltas_become_logical_pixels_in_the_natural_direction() {
        // winit reports positive y for wheel-up; the offset must grow when the
        // wheel is pushed down, and one line is 40 logical px.
        assert_eq!(
            window_wheel_delta_y(MouseScrollDelta::LineDelta(0.0, 1.0), 1.0),
            -40.0
        );
        assert_eq!(
            window_wheel_delta_y(MouseScrollDelta::LineDelta(0.0, -1.0), 1.0),
            40.0
        );
        // The horizontal component is not a vertical scroll.
        assert_eq!(
            window_wheel_delta_y(MouseScrollDelta::LineDelta(7.0, 1.0), 1.0),
            -40.0
        );
        // `PixelDelta` is physical, so it needs the scale factor.
        assert_eq!(
            window_wheel_delta_y(
                MouseScrollDelta::PixelDelta(PhysicalPosition::new(0.0, -100.0)),
                2.0,
            ),
            50.0
        );
    }

    #[test]
    fn a_wheel_event_before_the_first_frame_is_a_no_op() {
        // A wheel can arrive before any `RedrawRequested`, when there is no
        // layout to scroll. That must be inert, not a panic.
        let window = no_window();
        let mut scroll_offsets: HashMap<Vec<usize>, f32> = HashMap::new();
        window_mouse_wheel(
            1.0,
            (10.0, 10.0),
            &None,
            &mut scroll_offsets,
            &window,
            MouseScrollDelta::LineDelta(0.0, 3.0),
        );
        assert!(scroll_offsets.is_empty());
    }
}

/// Run a Skia window whose contents are produced by `make_view`.
///
/// # Viewport contract (1A / X-H1) — Viewport Root Normalization (CX-04)
///
/// `make_view` is `FnMut(w: u32, h: u32) -> (VNode, Stylesheet)` where
/// `(w, h)` are **logical viewport dimensions** — `Viewport::from_i32(physical, scale).logical_size()`.
/// The renderer calls it:
/// * once on startup,
/// * on every `RedrawRequested` / resize / DPI change with the *current* logical `w,h`.
///   Templates must not ignore `(w,h)` (no `|_w, _h|`). The canonical
///   responsive pattern is a viewport-filling root:
///   `width: 100%; min-height: 100vh` on `.app` (see `veloxc/templates/project/src/App.vx`).
///   With `width:100%` and `min-height:100vh`, `compute_layout(vnode, w as i32, h as i32)`
///   reflows visibly on every window resize — no element hidden when it should be visible
///   (Flutter invariant). Callers may also thread `(w,h)` into style/layout decisions if needed.
///
/// ## Root normalization
///
/// `velox_dom::layout::root_is_viewport_filling` ensures the *first* VNode (index 0 / `None`)
/// always fills the logical viewport — even without explicit `width:100%`. The expanded
/// predicate `is_viewport_filling(style, is_root_index)` additionally treats `100% | 100vw | 100dvw | 100vh | 100dvh | min-height:100%|vh|dvh`
/// as viewport-filling, validated via `compute_layout` percent chains (`height:100%` fills
/// when parent is definite) and `vw/vh/dvh` units that resolve against `Viewport::logical_size`.
#[cfg(feature = "skia-native")]
pub fn run_window_vnode_skia<F, G, H>(
    title: &str,
    mut make_view: F,
    mut on_event: G,
    mut get_title: H,
) -> Result<(), String>
where
    F: FnMut(u32, u32) -> (velox_dom::VNode, Stylesheet) + 'static,
    G: FnMut(&str, Option<&str>) + 'static,
    H: FnMut() -> String + 'static,
{
    use winit::dpi::PhysicalSize;
    use winit::event::{ElementState, Event, MouseButton, StartCause, WindowEvent};
    use winit::event_loop::{ControlFlow, EventLoop};
    use winit::window::WindowBuilder;

    // Headless mode: when no compositor is available (CI, containers, SSH)
    // we still create the window + run the event loop but skip softbuffer
    // presentation, rendering offscreen only. Enable with VELOX_HEADLESS=1
    // or it is auto-detected via presenter::is_compositor_available().
    let headless_env = std::env::var("VELOX_HEADLESS").as_deref() == Ok("1")
        || !crate::presenter::is_compositor_available();

    let mut last_vnode: Option<velox_dom::VNode> = None;
    let mut _hmr_pending = false;

    // Prepare the winit backend: force X11 if Wayland socket is stale to
    // avoid winit's Wayland backend calling process::exit() on EPIPE.
    let _headless_check = crate::presenter::prepare_backend();

    // Try to create a winit event loop and window. In headless mode or when
    // no compositor is available, both can fail (winit may panic instead of
    // returning Err) — we catch this and proceed with headless rendering.
    //
    // A NON-display failure is not headless-eligible: it is returned as a
    // typed `VeloxError::Window`, never panicked. The old `panic!` here was
    // caught by the `catch_unwind` below and silently converted into the same
    // headless fallback as a broken pipe, which masked real configuration
    // errors (bad size, closed display fd) as "running headless".
    // Factored out of the `let` below: clippy::type_complexity fires on the
    // inline annotation. Behaviour-identical alias.
    type WindowOutcome = Result<
        (
            Option<winit::event_loop::EventLoop<()>>,
            Option<winit::window::Window>,
            PhysicalSize<u32>,
            f32,
        ),
        String,
    >;
    let window_outcome: WindowOutcome =
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let event_loop = EventLoop::new();
            let window_result = WindowBuilder::new()
                .with_title(title)
                .with_inner_size(PhysicalSize::new(800, 600))
                .build(&event_loop);
            match window_result {
                Ok(w) => {
                    let size = w.inner_size();
                    let sf = w.scale_factor() as f32;
                    Ok((Some(event_loop), Some(w), size, sf))
                }
                Err(e) => {
                    let msg = e.to_string();
                    let lower = msg.to_ascii_lowercase();
                    let is_display_err = lower.contains("broken pipe")
                        || lower.contains("os error 32")
                        || lower.contains("no compositor")
                        || lower.contains("no display server")
                        || lower.contains("failed to connect");
                    if headless_env || is_display_err {
                        log::warn!("window creation failed — continuing in headless mode: {msg}");
                        Ok((Some(event_loop), None, PhysicalSize::new(800, 600), 1.0))
                    } else {
                        Err(
                            velox_dom::VeloxError::Window(format!("failed to create window: {e}"))
                                .to_string(),
                        )
                    }
                }
            }
        }))
        .unwrap_or_else(|payload| {
            // Surface the panic payload (usually the compositor error, e.g.
            // broken pipe) instead of silently masking it — log::warn is
            // invisible without an initialized logger (CX-13 / F-23).
            eprintln!(
                "[velox] window/event loop creation panicked — continuing in headless mode: {}",
                panic_detail(payload)
            );
            Ok((None, None, PhysicalSize::new(800, 600), 1.0))
        });
    let (event_loop_opt, window, window_size, scale_factor) = window_outcome?;

    let window_opt: Option<winit::window::Window> = window;
    let mut renderer = match crate::skia_surface::SkiaSurface::new_raster(
        window_size.width as i32,
        window_size.height as i32,
    ) {
        Ok(surface) => skia_backend::SkiaRenderer {
            surface: Some(surface),
            vnode: None,
        },
        Err(e) => {
            return Err(format!("failed to create SkiaSurface: {e}"));
        }
    };
    let mut presenter: Option<crate::presenter::SoftbufferPresenter> = None;
    if let Some(w) = window_opt.as_ref() {
        // softbuffer::Context::new() can panic when the display server is
        // unreachable even though DISPLAY/WAYLAND_DISPLAY are set (broken pipe).
        // Catch such panics and degrade to headless rendering.
        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            crate::presenter::SoftbufferPresenter::new(w, window_size.width, window_size.height)
        })) {
            Ok(Ok(p)) => presenter = Some(p),
            Ok(Err(e)) => {
                if headless_env {
                    log::warn!(
                        "softbuffer presenter unavailable — continuing in headless mode: {e}"
                    );
                } else {
                    return Err(format!("failed to create softbuffer presenter: {e}"));
                }
            }
            Err(payload) => {
                // Surface the panic payload (softbuffer panics with a
                // broken pipe when the display is unreachable) instead of
                // silently masking it (CX-13 / F-23).
                eprintln!(
                    "[velox] softbuffer presenter creation panicked — continuing in headless mode: {}",
                    panic_detail(payload)
                );
            }
        }
    }
    let mut scale_factor = scale_factor;
    let mut mouse_pos = (0.0f32, 0.0f32);
    let mut hovered_id: Option<u32> = None;
    let mut click_targets: Vec<crate::events::ClickTarget> = Vec::new();
    let mut hover_targets: Vec<crate::events::HoverTarget> = Vec::new();
    let mut input_targets: Vec<crate::events::InputTarget> = Vec::new();
    // Path (child source indices) to the focused text input, if any.
    let mut focused_input: Option<Vec<usize>> = None;
    // Instant before which the caret must stay solid regardless of tick
    // timing. Armed by every editing key and by focus changes.
    let mut blink_deadline: Option<std::time::Instant> = None;
    // Shift state, latched by the shared `window_modifiers_changed` below.
    // winit 0.28 deprecates `KeyboardInput::modifiers` in favour of the
    // `ModifiersChanged` event, so the caret reads this latched value instead
    // of the deprecated per-key field.
    let mut shift_held = false;
    // Scrollable overflow model: wheel clamping + deepest hit_test
    let mut scroll_offsets: std::collections::HashMap<Vec<usize>, f32> =
        std::collections::HashMap::new();
    let mut last_layout: Option<velox_dom::layout::LayoutNode> = None;
    // Lifecycle: ensure on_mounted fires once on first RedrawRequested and
    // on_unmounted/before_destroy fire on CloseRequested or drop.
    let _lifecycle_guard = LifecycleCleanupGuard;
    let mut did_mount = false;
    // R-L3: coalesce rapid resize drags — only last size per frame materializes.
    // Surface recreation (raster_n32_premul) is deferred to RedrawRequested.
    let mut resize_state = ResizeState::new();

    // Render first frame immediately before entering the event loop.
    // This ensures the window has content even on platforms where
    // request_redraw() from NewEvents(StartCause::Init) may not trigger
    // a RedrawRequested event (e.g. certain Wayland/X11 compositors).

    if let Some(s) = &mut renderer.surface {
        s.set_scale_factor(scale_factor);
        let (vw, vh) = resize_state.record_initial(s.width, s.height, scale_factor);
        let (vnode_raw, sheet) = make_view(vw, vh);
        let mut next_id = 1u32;
        let vnode_tagged = with_hover_ids(&vnode_raw, &mut next_id);
        let vnode = crate::style_vnode_with_hover(&vnode_tagged, &sheet, &|_tag, props| {
            props
                .attrs
                .get("data-hover-id")
                .and_then(|v| v.parse::<u32>().ok())
                .map(|id| Some(id) == hovered_id)
                .unwrap_or(false)
        });
        // First frame: no input can be focused yet, so every text input gets
        // the unfocused defaults. Injected anyway so the attr contract holds on
        // frame one and paint never has to special-case absence.
        let vnode = crate::inject_input_caret_attrs(&vnode, None);
        // Publish the pre-loop frame so a click or keystroke that arrives before
        // the first RedrawRequested is handled against real layout/value data
        // rather than an empty `last_vnode`. Without this, `apply_click_focus`
        // and `apply_edit_to_focused` see `None` and either drop the edit or put
        // the caret at 0 — the regression the HMR loop already guards against
        // by assigning `last_vnode` here.
        last_vnode = Some(vnode.clone());
        let mut layout = velox_dom::layout::compute_layout(&vnode, vw as i32, vh as i32);
        {
            let mut path = Vec::new();
            crate::events::apply_scroll_offsets(&mut layout, &scroll_offsets, &mut path);
        }
        last_layout = Some(layout.clone());
        recompute_targets(
            &vnode,
            &layout,
            &mut click_targets,
            &mut hover_targets,
            &mut input_targets,
        );
        // Render and present the initial frame so the window has immediate content.
        if let Err(e) = crate::skia_render::skia_impl::render_frame(s, &vnode, &layout, &sheet) {
            log::error!("skia initial render error: {}", e);
        }
        if let Some(presenter) = presenter.as_mut()
            && let Err(e) = presenter.present(s)
        {
            log::error!("skia initial present error: {}", e);
        }
    }

    if let Some(event_loop) = event_loop_opt {
        // The event loop can panic if the display server becomes unreachable
        // (e.g. "Io error: Broken pipe") — catch that and degrade gracefully.
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            // Caret blink clock. `EventLoop::new()` is an alias for
            // `EventLoopBuilder::new().build()`, and that constructor calls
            // `with_user_event()`, so the user-event channel is already enabled
            // here and `create_proxy()` needs no builder change. Held in a local
            // inside the unwind closure so its `Drop` joins the thread when the
            // loop ends.
            let _blink_ticker = crate::CaretBlinkTicker::start(event_loop.create_proxy(), ());
            event_loop.run(move |event, _, control_flow| {
                *control_flow = ControlFlow::Wait;
                match event {
                    Event::NewEvents(StartCause::Init) => {
                        if let Some(w) = window_opt.as_ref() {
                            w.request_redraw();
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::CloseRequested,
                        ..
                    } => {
                        // Destroy hooks run inside the shared arm; the exit stays
                        // here so `ControlFlow` never leaves the loop.
                        if window_close_requested() {
                            *control_flow = ControlFlow::Exit;
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::Resized(new_size),
                        ..
                    } => {
                        window_resized(
                            &mut resize_state,
                            &window_opt,
                            (new_size.width, new_size.height),
                        );
                    }
                    Event::WindowEvent {
                        event:
                            WindowEvent::ScaleFactorChanged {
                                scale_factor: new_scale,
                                new_inner_size,
                                ..
                            },
                        ..
                    } => {
                        window_scale_factor_changed(
                            &mut scale_factor,
                            &mut mouse_pos,
                            &mut resize_state,
                            &mut renderer.surface,
                            &window_opt,
                            new_scale,
                            (new_inner_size.width, new_inner_size.height),
                        );
                    }
                    Event::WindowEvent {
                        event: WindowEvent::CursorMoved { position, .. },
                        ..
                    } => {
                        window_cursor_moved(
                            scale_factor,
                            &mut mouse_pos,
                            &hover_targets,
                            &mut hovered_id,
                            &window_opt,
                            (position.x as f32, position.y as f32),
                        );
                    }
                    Event::WindowEvent {
                        event:
                            WindowEvent::MouseInput {
                                state: ElementState::Pressed,
                                button: MouseButton::Left,
                                ..
                            },
                        ..
                    } => {
                        // Text-input focus: clicking a text field focuses it and
                        // places the caret; clicking anywhere else drops focus and
                        // clears the selection. This runs BEFORE the click-handler
                        // test and is deliberately independent of it — see the
                        // redraw hoist at the bottom of this arm.
                        crate::apply_click_focus(
                            &mut input_targets,
                            &last_vnode,
                            &mut focused_input,
                            mouse_pos.0,
                            mouse_pos.1,
                            scale_factor,
                            surface_logical_viewport(&renderer, scale_factor),
                        );
                        let mut handled_click = false;
                        if let Some((handler, payload_opt)) =
                            crate::events::hit_test_click(&click_targets, mouse_pos.0, mouse_pos.1)
                        {
                            let payload_owned =
                                payload_opt.map(|p| p.to_string()).unwrap_or_else(|| {
                                    format!("{{\"x\":{},\"y\":{}}}", mouse_pos.0, mouse_pos.1)
                                });
                            on_event(handler, Some(&payload_owned));
                            velox_core::lifecycle::run_all_updated_hooks();
                            if let Some(s) = &mut renderer.surface {
                                let (vw, vh) = logical_size(s.width, s.height, scale_factor);
                                let (vnode_raw, sheet) = make_view(vw, vh);
                                let mut next_id = 1u32;
                                let vnode_tagged = with_hover_ids(&vnode_raw, &mut next_id);
                                let vnode = crate::style_vnode_with_hover(
                                    &vnode_tagged,
                                    &sheet,
                                    &|_tag, props| {
                                        props
                                            .attrs
                                            .get("data-hover-id")
                                            .and_then(|v| v.parse::<u32>().ok())
                                            .map(|id| Some(id) == hovered_id)
                                            .unwrap_or(false)
                                    },
                                );
                                let vnode = crate::inject_input_caret_attrs(
                                    &vnode,
                                    crate::events::focused_input_index(&input_targets)
                                        .and_then(|i| input_targets.get(i)),
                                );
                                let mut layout =
                                    velox_dom::layout::compute_layout(&vnode, vw as i32, vh as i32);
                                {
                                    let mut path = Vec::new();
                                    crate::events::apply_scroll_offsets(
                                        &mut layout,
                                        &scroll_offsets,
                                        &mut path,
                                    );
                                }
                                last_layout = Some(layout.clone());
                                recompute_targets(
                                    &vnode,
                                    &layout,
                                    &mut click_targets,
                                    &mut hover_targets,
                                    &mut input_targets,
                                );
                            }
                            handled_click = true;
                        }
                        if let Some(w) = window_opt.as_ref() {
                            if handled_click {
                                w.set_title(&get_title());
                            }
                            // HOISTED OUT of the `hit_test_click` arm on purpose.
                            // This used to live inside it, so a click that hit
                            // empty space changed focus and then never repainted:
                            // the focus ring and caret were stuck at their old
                            // values. Focus is now state the frame depends on, so
                            // any change to it must schedule a redraw.
                            w.request_redraw();
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::ModifiersChanged(mods),
                        ..
                    } => {
                        window_modifiers_changed(&mut shift_held, mods.shift());
                    }
                    Event::WindowEvent {
                        event: WindowEvent::KeyboardInput { input, .. },
                        ..
                    } => {
                        // Handle keyboard shortcuts and text-input editing keys.
                        use winit::event::VirtualKeyCode;
                        if let Some(keycode) = input.virtual_keycode
                            && input.state == ElementState::Pressed
                        {
                            // `@keydown` bindings first, and additively: this
                            // grants focus and calls handlers, it never
                            // consumes the key, so every branch below still
                            // runs exactly as it did before any keydown
                            // binding existed.
                            if crate::dispatch_keydown(
                                keycode,
                                &mut input_targets,
                                &last_vnode,
                                &mut focused_input,
                                &mut on_event,
                            ) {
                                arm_blink_deadline(&mut blink_deadline);
                                velox_core::lifecycle::run_all_updated_hooks();
                                if let Some(w) = window_opt.as_ref() {
                                    w.request_redraw();
                                }
                            }
                            match keycode {
                                // Reload (app exits, dev server restarts it) and quit.
                                // Both are withheld while a text field has focus: with a
                                // field focused these keys are *text*, so an unguarded
                                // shortcut means typing "r" into a search box kills the
                                // application. With nothing focused they are the only way
                                // out of the window. When the guard fails the key falls
                                // through to the editor below, which is what lets the
                                // character still reach the field.
                                VirtualKeyCode::R | VirtualKeyCode::Q
                                    if !crate::events::any_input_focused(&input_targets) =>
                                {
                                    velox_core::lifecycle::run_all_destroy_hooks();
                                    *control_flow = ControlFlow::Exit;
                                }
                                _ => {
                                    // Every remaining editing key routes through the
                                    // one shared call, so the HMR loop cannot drift
                                    // from this one again.
                                    if let Some(action) =
                                        crate::edit_action_for_key(keycode, shift_held)
                                    {
                                        let changed = crate::apply_edit_to_focused(
                                            &mut input_targets,
                                            action,
                                            &last_vnode,
                                            &mut focused_input,
                                            &mut on_event,
                                        );
                                        if changed {
                                            // Caret goes solid while you type.
                                            arm_blink_deadline(&mut blink_deadline);
                                            velox_core::lifecycle::run_all_updated_hooks();
                                            if let Some(w) = window_opt.as_ref() {
                                                w.request_redraw();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Event::UserEvent(()) => {
                        // Caret blink tick from `CaretBlinkTicker`. See that
                        // type for why a thread is involved and why it is not a
                        // shared-state race.
                        if crate::on_caret_blink_tick(&mut input_targets, &mut blink_deadline)
                            && let Some(w) = window_opt.as_ref()
                        {
                            w.request_redraw();
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::ReceivedCharacter(c),
                        ..
                    } => {
                        // Printable characters go to the focused text input.
                        if !c.is_control()
                            && c != '\u{7f}'
                            && crate::apply_edit_to_focused(
                                &mut input_targets,
                                crate::events::EditAction::Insert(c),
                                &last_vnode,
                                &mut focused_input,
                                &mut on_event,
                            )
                        {
                            // Caret goes solid while you type.
                            arm_blink_deadline(&mut blink_deadline);
                            velox_core::lifecycle::run_all_updated_hooks();
                            if let Some(w) = window_opt.as_ref() {
                                w.request_redraw();
                            }
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::MouseWheel { delta, .. },
                        ..
                    } => {
                        window_mouse_wheel(
                            scale_factor,
                            mouse_pos,
                            &last_layout,
                            &mut scroll_offsets,
                            &window_opt,
                            delta,
                        );
                    }
                    Event::RedrawRequested(_) => {
                        // R-L3: materialize any coalesced resize exactly once per frame.
                        let mut committed_resize = false;
                        if let Some((pw, ph)) = resize_state.take_pending() {
                            // `ResizeState::take_pending` is the production `pending_resize.take()` path.
                            match renderer.resize(pw as i32, ph as i32) {
                                Ok(()) => committed_resize = true,
                                Err(e) => {
                                    log::warn!("renderer resize failed ({}x{}): {}", pw, ph, e);
                                }
                            }
                            if let Some(presenter) = presenter.as_mut()
                                && let Err(e) = presenter.resize(pw, ph)
                            {
                                log::warn!("presenter resize failed: {}", e);
                            }
                        }
                        // First mount: fire on_mounted once.
                        ensure_mounted(&mut did_mount);
                        // Render VNode -> Skia frame and present.
                        if let Some(s) = &mut renderer.surface {
                            s.set_scale_factor(scale_factor);
                            let (vw, vh) = resize_state.frame_logical_size(
                                s.width,
                                s.height,
                                scale_factor,
                                committed_resize,
                            );
                            let (vnode_raw, sheet) = make_view(vw, vh);
                            let mut next_id = 1u32;
                            let vnode_tagged = with_hover_ids(&vnode_raw, &mut next_id);
                            let vnode = crate::style_vnode_with_hover(
                                &vnode_tagged,
                                &sheet,
                                &|_tag, props| {
                                    props
                                        .attrs
                                        .get("data-hover-id")
                                        .and_then(|v| v.parse::<u32>().ok())
                                        .map(|id| Some(id) == hovered_id)
                                        .unwrap_or(false)
                                },
                            );
                            // Caret/selection/focus contract for the paint lane.
                            // After the style cascade, before layout: it adds no
                            // second cascade and no second rounding site.
                            let vnode = crate::inject_input_caret_attrs(
                                &vnode,
                                crate::events::focused_input_index(&input_targets)
                                    .and_then(|i| input_targets.get(i)),
                            );
                            last_vnode = Some(vnode.clone());
                            let mut layout =
                                velox_dom::layout::compute_layout(&vnode, vw as i32, vh as i32);
                            {
                                let mut path = Vec::new();
                                crate::events::apply_scroll_offsets(
                                    &mut layout,
                                    &scroll_offsets,
                                    &mut path,
                                );
                            }
                            last_layout = Some(layout.clone());
                            recompute_targets(
                                &vnode,
                                &layout,
                                &mut click_targets,
                                &mut hover_targets,
                                &mut input_targets,
                            );
                            if let Err(e) = crate::skia_render::skia_impl::render_frame(
                                s, &vnode, &layout, &sheet,
                            ) {
                                log::error!("skia render error: {}", e);
                            }
                            if let Some(presenter) = presenter.as_mut()
                                && let Err(e) = presenter.present(s)
                            {
                                log::error!("skia present error: {}", e);
                            }
                        }
                    }
                    _ => {}
                }
            });
        }));
    } else {
        // Headless mode — no event loop, just run the initial render and return.
        log::info!("running in headless mode (no event loop)");
        velox_core::lifecycle::run_all_destroy_hooks();
    }
    Ok(())
}

/// What the caught window/loop construction yields: the event loop and its HMR
/// proxy (both survive even when the window does not), the window itself, its
/// physical size, and the DPI scale factor.
#[cfg(feature = "skia-native")]
type WindowBootstrap = (
    Option<winit::event_loop::EventLoop<HmrMessage>>,
    Option<winit::event_loop::EventLoopProxy<HmrMessage>>,
    Option<winit::window::Window>,
    winit::dpi::PhysicalSize<u32>,
    f32,
);

/// HMR variant — same viewport contract as [`run_window_vnode_skia`] (see its docs).
/// `make_view` is called with logical `(w, h)` on every frame/resize; templates use
/// `width:100%` / `min-height:100vh` so the viewport change is visibly reflected.
#[cfg(feature = "skia-native")]
pub fn run_window_vnode_skia_with_hmr<F, G, H>(
    title: &str,
    mut make_view: F,
    mut on_event: G,
    mut get_title: H,
    hmr_rx: std::sync::Arc<std::sync::Mutex<std::sync::mpsc::Receiver<HmrMessage>>>,
) -> Result<(), String>
where
    F: FnMut(u32, u32) -> (velox_dom::VNode, Stylesheet) + 'static,
    G: FnMut(&str, Option<&str>) + 'static,
    H: FnMut() -> String + 'static,
{
    use winit::dpi::PhysicalSize;
    use winit::event::{ElementState, Event, MouseButton, StartCause, WindowEvent};
    use winit::event_loop::{ControlFlow, EventLoopBuilder};
    use winit::window::WindowBuilder;

    let headless_env_hmr = std::env::var("VELOX_HEADLESS").as_deref() == Ok("1")
        || !crate::presenter::is_compositor_available();

    // Prepare the winit backend: force X11 if Wayland socket is stale to
    // avoid winit's Wayland backend calling process::exit() on EPIPE.
    let _headless_check_hmr = crate::presenter::prepare_backend();

    // Try to create a winit event loop and window. In headless mode or when
    // no compositor is available, both can fail (winit may panic instead of
    // returning Err) — we catch this and proceed with headless rendering.
    // Use EventLoop<HmrMessage> so the HMR thread can forward messages
    // directly via EventLoopProxy::send_event(HmrMessage) without any
    // shared Mutex<Receiver>.
    // Same contract as the plain loop above: a non-display window failure is
    // a typed `VeloxError::Window` returned as `Err`, never a `panic!` the
    // `catch_unwind` would launder into headless mode.
    let window_outcome_hmr: Result<WindowBootstrap, String> =
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let event_loop = EventLoopBuilder::<HmrMessage>::with_user_event().build();
            let proxy = event_loop.create_proxy();
            let window_result = WindowBuilder::new()
                .with_title(title)
                .with_inner_size(PhysicalSize::new(800, 600))
                .build(&event_loop);
            match window_result {
                Ok(w) => {
                    let size = w.inner_size();
                    let sf = w.scale_factor() as f32;
                    Ok((Some(event_loop), Some(proxy), Some(w), size, sf))
                }
                Err(e) => {
                    let msg = e.to_string();
                    let lower = msg.to_ascii_lowercase();
                    let is_display_err = lower.contains("broken pipe")
                        || lower.contains("os error 32")
                        || lower.contains("no compositor")
                        || lower.contains("no display server")
                        || lower.contains("failed to connect");
                    if headless_env_hmr || is_display_err {
                        log::warn!("window creation failed — continuing in headless mode: {msg}");
                        Ok((
                            Some(event_loop),
                            Some(proxy),
                            None,
                            PhysicalSize::new(800, 600),
                            1.0,
                        ))
                    } else {
                        Err(
                            velox_dom::VeloxError::Window(format!("failed to create window: {e}"))
                                .to_string(),
                        )
                    }
                }
            }
        }))
        .unwrap_or_else(|payload| {
            // Surface the panic payload (usually the compositor error, e.g.
            // broken pipe) instead of silently masking it — log::warn is
            // invisible without an initialized logger (CX-13 / F-23).
            eprintln!(
                "[velox] window/event loop creation panicked — continuing in headless mode: {}",
                panic_detail(payload)
            );
            Ok((None, None, None, PhysicalSize::new(800, 600), 1.0))
        });
    let (event_loop_opt, proxy_opt, window, window_size, scale_factor) = window_outcome_hmr?;

    // Spawn the HMR forwarding thread. It takes sole ownership of the
    // Receiver (moved out of the Arc<Mutex>) and forwards each HmrMessage
    // directly via EventLoopProxy::send_event(HmrMessage). No Mutex is
    // held across blocking recv(). Wrap in catch_unwind so HMR panics
    // never bring down the app (acceptance: catch_unwind around HMR loop).
    if let Some(proxy) = proxy_opt {
        match std::sync::Arc::try_unwrap(hmr_rx) {
            Ok(mutex) => {
                // `into_inner`, never `expect`: a poisoned mutex still owns a
                // valid `Receiver`, and panicking here would kill the app over
                // a previous panic's side effect. The receiver is taken as-is.
                let rx = mutex
                    .into_inner()
                    .unwrap_or_else(|poisoned| poisoned.into_inner());
                std::thread::spawn(move || {
                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        while let Ok(msg) = rx.recv() {
                            if proxy.send_event(msg).is_err() {
                                break;
                            }
                        }
                    }));
                });
            }
            Err(shared) => {
                // Fallback: another Arc clone exists (unusual). Poll without
                // holding the lock across blocking recv.
                std::thread::spawn(move || {
                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        loop {
                            let res = {
                                // `into_inner`, never `expect`: poisoning must
                                // not panic the HMR thread (which would kill
                                // forwarding silently). The guard is dropped
                                // before `recv` either way — no lock is held
                                // across the blocking call.
                                let guard = shared
                                    .lock()
                                    .unwrap_or_else(|poisoned| poisoned.into_inner());
                                guard.try_recv()
                            };
                            match res {
                                Ok(msg) => {
                                    if proxy.send_event(msg).is_err() {
                                        break;
                                    }
                                }
                                Err(std::sync::mpsc::TryRecvError::Empty) => {
                                    std::thread::sleep(std::time::Duration::from_millis(16));
                                }
                                Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
                            }
                        }
                    }));
                });
            }
        }
    }
    // NOTE: hmr_rx has been moved into the forwarding thread. The event loop
    // now receives HmrMessage via Event::UserEvent(msg) without any Mutex.

    let window_opt: Option<winit::window::Window> = window;
    let mut scale_factor = scale_factor;
    let mut renderer = match crate::skia_surface::SkiaSurface::new_raster(
        window_size.width as i32,
        window_size.height as i32,
    ) {
        Ok(surface) => skia_backend::SkiaRenderer {
            surface: Some(surface),
            vnode: None,
        },
        Err(e) => {
            return Err(format!("failed to create SkiaSurface: {e}"));
        }
    };
    let mut presenter: Option<crate::presenter::SoftbufferPresenter> = None;
    if let Some(w) = window_opt.as_ref() {
        // softbuffer::Context::new() can panic when the display server is
        // unreachable even though DISPLAY/WAYLAND_DISPLAY are set (broken pipe).
        // Catch such panics and degrade to headless rendering.
        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            crate::presenter::SoftbufferPresenter::new(w, window_size.width, window_size.height)
        })) {
            Ok(Ok(p)) => presenter = Some(p),
            Ok(Err(e)) => {
                if headless_env_hmr || !crate::presenter::is_compositor_available() {
                    log::warn!(
                        "softbuffer presenter unavailable — continuing in headless mode: {e}"
                    );
                } else {
                    return Err(format!("failed to create softbuffer presenter: {e}"));
                }
            }
            Err(payload) => {
                // Surface the panic payload (softbuffer panics with a
                // broken pipe when the display is unreachable) instead of
                // silently masking it (CX-13 / F-23).
                eprintln!(
                    "[velox] softbuffer presenter creation panicked — continuing in headless mode: {}",
                    panic_detail(payload)
                );
            }
        }
    }
    let mut mouse_pos = (0.0f32, 0.0f32);
    let mut hovered_id: Option<u32> = None;
    let mut click_targets: Vec<crate::events::ClickTarget> = Vec::new();
    let mut hover_targets: Vec<crate::events::HoverTarget> = Vec::new();
    let mut input_targets: Vec<crate::events::InputTarget> = Vec::new();
    // Was `_last_vnode` until 5cc4a4f, which renamed it and made it live. The
    // earlier HMR-deadlock fix (7585674) introduced this binding *unused*, so
    // typing, Backspace and Return stayed dead under HMR; 5cc4a4f is what
    // actually fixed them, by giving the value a real name and wiring it into
    // the ported input handling.
    let mut last_vnode: Option<velox_dom::VNode> = None;
    // Path (child source indices) to the focused text input, if any.
    // Mirrors the plain loop's state so the two loops stay behaviourally equal.
    let mut focused_input: Option<Vec<usize>> = None;
    // Instant before which the caret must stay solid regardless of tick timing.
    let mut blink_deadline: Option<std::time::Instant> = None;
    // Shift state, latched by the shared `window_modifiers_changed` below —
    // see the plain loop for why the per-key `modifiers` field is not used.
    let mut shift_held = false;
    let mut scroll_offsets_hmr: std::collections::HashMap<Vec<usize>, f32> =
        std::collections::HashMap::new();
    let mut last_layout_hmr: Option<velox_dom::layout::LayoutNode> = None;
    let _lifecycle_guard_hmr = LifecycleCleanupGuard;
    let mut did_mount_hmr = false;
    // R-L3: coalesce rapid resize drags in HMR loop too (only last size per frame).
    let mut resize_state = ResizeState::new();

    // Render first frame immediately before entering the event loop.
    // This ensures the window has content even on platforms where
    // request_redraw() from NewEvents(StartCause::Init) may not trigger
    // a RedrawRequested event (e.g. certain Wayland/X11 compositors).
    if let Some(s) = &mut renderer.surface {
        s.set_scale_factor(scale_factor);
        let (vw, vh) = resize_state.record_initial(s.width, s.height, scale_factor);
        let (vnode_raw, sheet) = make_view(vw, vh);
        let mut next_id = 1u32;
        let vnode_tagged = with_hover_ids(&vnode_raw, &mut next_id);
        let vnode = crate::style_vnode_with_hover(&vnode_tagged, &sheet, &|_tag, props| {
            props
                .attrs
                .get("data-hover-id")
                .and_then(|v| v.parse::<u32>().ok())
                .map(|id| Some(id) == hovered_id)
                .unwrap_or(false)
        });
        // First frame: no input can be focused yet, so every text input gets the
        // unfocused defaults.
        let vnode = crate::inject_input_caret_attrs(&vnode, None);
        last_vnode = Some(vnode.clone());
        let mut layout = velox_dom::layout::compute_layout(&vnode, vw as i32, vh as i32);
        {
            let mut path = Vec::new();
            crate::events::apply_scroll_offsets(&mut layout, &scroll_offsets_hmr, &mut path);
        }
        last_layout_hmr = Some(layout.clone());
        recompute_targets(
            &vnode,
            &layout,
            &mut click_targets,
            &mut hover_targets,
            &mut input_targets,
        );
        // Render and present the initial frame so the window has immediate content.
        if let Err(e) = crate::skia_render::skia_impl::render_frame(s, &vnode, &layout, &sheet) {
            log::error!("skia initial render error: {}", e);
        }
        if let Some(presenter) = presenter.as_mut()
            && let Err(e) = presenter.present(s)
        {
            log::error!("skia initial present error: {}", e);
        }
    }

    if let Some(event_loop) = event_loop_opt {
        // The event loop can panic if the display server becomes unreachable
        // (e.g. "Io error: Broken pipe") — catch that and degrade gracefully.
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            // Caret blink clock for the HMR loop. `EventLoop::run` consumes
            // `self`, so the proxy has to be made before the call. This loop's
            // channel is typed `HmrMessage`, so the tick rides
            // `HmrMessage::KeepWindow` — see that arm for why.
            let _blink_ticker =
                crate::CaretBlinkTicker::start(event_loop.create_proxy(), HmrMessage::KeepWindow);
            event_loop.run(move |event, _, control_flow| {
                *control_flow = ControlFlow::Wait;
                match event {
                    Event::UserEvent(msg) => match msg {
                        HmrMessage::FullReload => {
                            velox_core::lifecycle::run_all_destroy_hooks();
                            *control_flow = ControlFlow::Exit;
                        }
                        HmrMessage::HotReload { module_path: _ } => {
                            // Rebuild view and refresh all hit-test targets including
                            // input_targets, then request a redraw so the new VNode
                            // is painted on the next frame.
                            if let Some(s) = renderer.surface.as_ref() {
                                let (vw, vh) = logical_size(s.width, s.height, scale_factor);
                                let (vnode_raw, _) = make_view(vw, vh);
                                if let Err(e) = HmrRenderer::hot_update(&mut renderer, vnode_raw) {
                                    log::error!("hot_update failed: {}", e);
                                }
                                // Recompute all targets from the updated view so
                                // input focus / hit-test stays in sync after HMR.
                                if let Some(s2) = renderer.surface.as_ref() {
                                    let (vw2, vh2) =
                                        logical_size(s2.width, s2.height, scale_factor);
                                    let (vnode2_raw, sheet2) = make_view(vw2, vh2);
                                    let mut nid = 1u32;
                                    let tagged = with_hover_ids(&vnode2_raw, &mut nid);
                                    let vnode2 = crate::style_vnode_with_hover(
                                        &tagged,
                                        &sheet2,
                                        &|_tag, props| {
                                            props
                                                .attrs
                                                .get("data-hover-id")
                                                .and_then(|v| v.parse::<u32>().ok())
                                                .map(|id| Some(id) == hovered_id)
                                                .unwrap_or(false)
                                        },
                                    );
                                    // Caret attrs survive a hot reload: the
                                    // focused path is matched by tree path, and
                                    // `recompute_targets` below re-applies the
                                    // edit state onto the new targets.
                                    let vnode2 = crate::inject_input_caret_attrs(
                                        &vnode2,
                                        crate::events::focused_input_index(&input_targets)
                                            .and_then(|i| input_targets.get(i)),
                                    );
                                    last_vnode = Some(vnode2.clone());
                                    let mut layout = velox_dom::layout::compute_layout(
                                        &vnode2, vw2 as i32, vh2 as i32,
                                    );
                                    {
                                        let mut path = Vec::new();
                                        crate::events::apply_scroll_offsets(
                                            &mut layout,
                                            &scroll_offsets_hmr,
                                            &mut path,
                                        );
                                    }
                                    last_layout_hmr = Some(layout.clone());
                                    recompute_targets(
                                        &vnode2,
                                        &layout,
                                        &mut click_targets,
                                        &mut hover_targets,
                                        &mut input_targets,
                                    );
                                }
                            }
                            if let Some(w) = window_opt.as_ref() {
                                w.request_redraw();
                            }
                        }
                        // `KeepWindow` is overloaded as the HMR loop's caret
                        // blink tick. The HMR channel is typed `HmrMessage`, and
                        // winit 0.28 has no timer API, so the ticker posts a
                        // no-op HMR message on the same channel rather than
                        // forcing the loop to be untyped. The dev server's real
                        // keep-alives land here too, and both are no-ops, so
                        // overloading costs nothing.
                        HmrMessage::KeepWindow => {
                            if crate::on_caret_blink_tick(&mut input_targets, &mut blink_deadline)
                                && let Some(w) = window_opt.as_ref()
                            {
                                w.request_redraw();
                            }
                        }
                    },
                    Event::NewEvents(StartCause::Init) => {
                        if let Some(w) = window_opt.as_ref() {
                            w.request_redraw();
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::CloseRequested,
                        ..
                    } => {
                        // Destroy hooks run inside the shared arm; the exit stays
                        // here so `ControlFlow` never leaves the loop.
                        if window_close_requested() {
                            *control_flow = ControlFlow::Exit;
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::Resized(new_size),
                        ..
                    } => {
                        window_resized(
                            &mut resize_state,
                            &window_opt,
                            (new_size.width, new_size.height),
                        );
                    }
                    Event::WindowEvent {
                        event:
                            WindowEvent::ScaleFactorChanged {
                                scale_factor: new_scale,
                                new_inner_size,
                                ..
                            },
                        ..
                    } => {
                        window_scale_factor_changed(
                            &mut scale_factor,
                            &mut mouse_pos,
                            &mut resize_state,
                            &mut renderer.surface,
                            &window_opt,
                            new_scale,
                            (new_inner_size.width, new_inner_size.height),
                        );
                    }
                    Event::WindowEvent {
                        event: WindowEvent::CursorMoved { position, .. },
                        ..
                    } => {
                        window_cursor_moved(
                            scale_factor,
                            &mut mouse_pos,
                            &hover_targets,
                            &mut hovered_id,
                            &window_opt,
                            (position.x as f32, position.y as f32),
                        );
                    }
                    Event::WindowEvent {
                        event:
                            WindowEvent::MouseInput {
                                state: ElementState::Pressed,
                                button: MouseButton::Left,
                                ..
                            },
                        ..
                    } => {
                        // Text-input focus: identical to the plain loop, and now
                        // actually present. This arm previously had NO focus
                        // handling at all, which is why the whole caret was
                        // unreachable under HMR.
                        crate::apply_click_focus(
                            &mut input_targets,
                            &last_vnode,
                            &mut focused_input,
                            mouse_pos.0,
                            mouse_pos.1,
                            scale_factor,
                            surface_logical_viewport(&renderer, scale_factor),
                        );
                        let mut handled_click = false;
                        if let Some((handler, payload_opt)) =
                            crate::events::hit_test_click(&click_targets, mouse_pos.0, mouse_pos.1)
                        {
                            let payload_owned =
                                payload_opt.map(|p| p.to_string()).unwrap_or_else(|| {
                                    format!("{{\"x\":{},\"y\":{}}}", mouse_pos.0, mouse_pos.1)
                                });
                            on_event(handler, Some(&payload_owned));
                            velox_core::lifecycle::run_all_updated_hooks();
                            if let Some(s) = &mut renderer.surface {
                                let (vw, vh) = logical_size(s.width, s.height, scale_factor);
                                let (vnode_raw, sheet) = make_view(vw, vh);
                                let mut next_id = 1u32;
                                let vnode_tagged = with_hover_ids(&vnode_raw, &mut next_id);
                                let vnode = crate::style_vnode_with_hover(
                                    &vnode_tagged,
                                    &sheet,
                                    &|_tag, props| {
                                        props
                                            .attrs
                                            .get("data-hover-id")
                                            .and_then(|v| v.parse::<u32>().ok())
                                            .map(|id| Some(id) == hovered_id)
                                            .unwrap_or(false)
                                    },
                                );
                                let vnode = crate::inject_input_caret_attrs(
                                    &vnode,
                                    crate::events::focused_input_index(&input_targets)
                                        .and_then(|i| input_targets.get(i)),
                                );
                                last_vnode = Some(vnode.clone());
                                let mut layout =
                                    velox_dom::layout::compute_layout(&vnode, vw as i32, vh as i32);
                                {
                                    let mut path = Vec::new();
                                    crate::events::apply_scroll_offsets(
                                        &mut layout,
                                        &scroll_offsets_hmr,
                                        &mut path,
                                    );
                                }
                                last_layout_hmr = Some(layout.clone());
                                recompute_targets(
                                    &vnode,
                                    &layout,
                                    &mut click_targets,
                                    &mut hover_targets,
                                    &mut input_targets,
                                );
                            }
                            handled_click = true;
                        }
                        if let Some(w) = window_opt.as_ref() {
                            if handled_click {
                                w.set_title(&get_title());
                            }
                            // HOISTED OUT of the `hit_test_click` arm, for the
                            // same reason as the plain loop: this arm had the
                            // identical nesting bug, so a click on empty space
                            // changed focus and never repainted.
                            w.request_redraw();
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::ModifiersChanged(mods),
                        ..
                    } => {
                        window_modifiers_changed(&mut shift_held, mods.shift());
                    }
                    Event::WindowEvent {
                        event: WindowEvent::KeyboardInput { input, .. },
                        ..
                    } => {
                        // Keyboard shortcuts and text-input editing keys.
                        use winit::event::VirtualKeyCode;
                        if let Some(keycode) = input.virtual_keycode
                            && input.state == ElementState::Pressed
                        {
                            // `@keydown` bindings, identical to the plain
                            // loop's — including the additive contract, which
                            // is what stops an HMR session from losing F2-focus
                            // the moment a rebuild is watched.
                            if crate::dispatch_keydown(
                                keycode,
                                &mut input_targets,
                                &last_vnode,
                                &mut focused_input,
                                &mut on_event,
                            ) {
                                crate::arm_blink_deadline(&mut blink_deadline);
                                velox_core::lifecycle::run_all_updated_hooks();
                                if let Some(w) = window_opt.as_ref() {
                                    w.request_redraw();
                                }
                            }
                            match keycode {
                                // Reload / quit. Identical to the plain loop's arm
                                // including the focus guard — an unguarded shortcut
                                // here would mean typing "r" into a field exits the
                                // process under HMR only, which is the kind of drift
                                // that survives review because it is "the other loop".
                                VirtualKeyCode::R | VirtualKeyCode::Q
                                    if !crate::events::any_input_focused(&input_targets) =>
                                {
                                    velox_core::lifecycle::run_all_destroy_hooks();
                                    *control_flow = ControlFlow::Exit;
                                }
                                // Ported from the plain loop. This arm used to be
                                // a bare `_ => {}` stub with no `focused_input` in
                                // scope at all, so typing did nothing under HMR.
                                _ => {
                                    if let Some(action) =
                                        crate::edit_action_for_key(keycode, shift_held)
                                    {
                                        let changed = crate::apply_edit_to_focused(
                                            &mut input_targets,
                                            action,
                                            &last_vnode,
                                            &mut focused_input,
                                            &mut on_event,
                                        );
                                        if changed {
                                            // Caret goes solid while you type.
                                            crate::arm_blink_deadline(&mut blink_deadline);
                                            velox_core::lifecycle::run_all_updated_hooks();
                                            if let Some(w) = window_opt.as_ref() {
                                                w.request_redraw();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::ReceivedCharacter(c),
                        ..
                    } => {
                        // Printable characters go to the focused text input.
                        // Ported from the plain loop; there was no
                        // `ReceivedCharacter` arm anywhere in this loop, so
                        // typing inserted nothing under HMR.
                        if !c.is_control()
                            && c != '\u{7f}'
                            && crate::apply_edit_to_focused(
                                &mut input_targets,
                                crate::events::EditAction::Insert(c),
                                &last_vnode,
                                &mut focused_input,
                                &mut on_event,
                            )
                        {
                            // Caret goes solid while you type.
                            crate::arm_blink_deadline(&mut blink_deadline);
                            velox_core::lifecycle::run_all_updated_hooks();
                            if let Some(w) = window_opt.as_ref() {
                                w.request_redraw();
                            }
                        }
                    }
                    Event::WindowEvent {
                        event: WindowEvent::MouseWheel { delta, .. },
                        ..
                    } => {
                        window_mouse_wheel(
                            scale_factor,
                            mouse_pos,
                            &last_layout_hmr,
                            &mut scroll_offsets_hmr,
                            &window_opt,
                            delta,
                        );
                    }
                    Event::RedrawRequested(_) => {
                        // R-L3: materialize any coalesced resize exactly once per frame.
                        let mut committed_resize = false;
                        if let Some((pw, ph)) = resize_state.take_pending() {
                            // `ResizeState::take_pending` is the production `pending_resize.take()` path.
                            match renderer.resize(pw as i32, ph as i32) {
                                Ok(()) => committed_resize = true,
                                Err(e) => {
                                    log::warn!("renderer resize failed ({}x{}): {}", pw, ph, e);
                                }
                            }
                            if let Some(presenter) = presenter.as_mut()
                                && let Err(e) = presenter.resize(pw, ph)
                            {
                                log::warn!("presenter resize failed: {}", e);
                            }
                        }
                        ensure_mounted(&mut did_mount_hmr);
                        // Render VNode -> Skia frame and present.
                        if let Some(s) = &mut renderer.surface {
                            s.set_scale_factor(scale_factor);
                            let (vw, vh) = resize_state.frame_logical_size(
                                s.width,
                                s.height,
                                scale_factor,
                                committed_resize,
                            );
                            let (vnode_raw, sheet) = make_view(vw, vh);
                            let mut next_id = 1u32;
                            let vnode_tagged = with_hover_ids(&vnode_raw, &mut next_id);
                            let vnode = crate::style_vnode_with_hover(
                                &vnode_tagged,
                                &sheet,
                                &|_tag, props| {
                                    props
                                        .attrs
                                        .get("data-hover-id")
                                        .and_then(|v| v.parse::<u32>().ok())
                                        .map(|id| Some(id) == hovered_id)
                                        .unwrap_or(false)
                                },
                            );
                            // Caret/selection/focus contract for the paint lane.
                            let vnode = crate::inject_input_caret_attrs(
                                &vnode,
                                crate::events::focused_input_index(&input_targets)
                                    .and_then(|i| input_targets.get(i)),
                            );
                            last_vnode = Some(vnode.clone());
                            let mut layout =
                                velox_dom::layout::compute_layout(&vnode, vw as i32, vh as i32);
                            {
                                let mut path = Vec::new();
                                crate::events::apply_scroll_offsets(
                                    &mut layout,
                                    &scroll_offsets_hmr,
                                    &mut path,
                                );
                            }
                            last_layout_hmr = Some(layout.clone());
                            recompute_targets(
                                &vnode,
                                &layout,
                                &mut click_targets,
                                &mut hover_targets,
                                &mut input_targets,
                            );
                            if let Err(e) = crate::skia_render::skia_impl::render_frame(
                                s, &vnode, &layout, &sheet,
                            ) {
                                log::error!("skia render error: {}", e);
                            }
                            if let Some(presenter) = presenter.as_mut()
                                && let Err(e) = presenter.present(s)
                            {
                                log::error!("softbuffer present error: {}", e);
                            }
                        }
                    }
                    _ => {}
                }
            });
        }));
    } else {
        // Headless mode — no event loop, just run the initial render and return.
        log::info!("running in headless mode (no event loop)");
        velox_core::lifecycle::run_all_destroy_hooks();
    }
    Ok(())
}

#[cfg(test)]
mod resize_state_tests {
    use super::ResizeState;
    use std::cell::RefCell;
    use std::rc::Rc;
    use std::sync::{Mutex, MutexGuard, OnceLock};
    use velox_core::lifecycle::{
        cleanup_component, clear_current_component, generate_component_id, on_resize,
        set_current_component,
    };
    use velox_core::signal::Signal;

    fn resize_test_guard() -> MutexGuard<'static, ()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn register_recorder(calls: Rc<RefCell<Vec<(u32, u32)>>>) -> usize {
        let id = generate_component_id();
        set_current_component(id);
        on_resize(move |width, height| calls.borrow_mut().push((width, height)));
        clear_current_component();
        id
    }

    #[test]
    fn renderer_resize_state_coalesces_raw_events_and_dispatches_once() {
        let _guard = resize_test_guard();
        let calls = Rc::new(RefCell::new(Vec::new()));
        let id = register_recorder(calls.clone());
        let mut state = ResizeState::new();

        assert_eq!(state.record_initial(640, 480, 1.0), (640, 480));
        state.queue((800, 600));
        state.queue((900, 700));
        // Raw events only update the pending size; they do not dispatch hooks.
        assert!(calls.borrow().is_empty());
        assert_eq!(state.take_pending(), Some((900, 700)));
        assert_eq!(state.frame_logical_size(900, 700, 1.0, true), (900, 700));
        assert_eq!(state.take_pending(), None);
        assert_eq!(state.frame_logical_size(900, 700, 1.0, true), (900, 700));

        assert_eq!(&*calls.borrow(), &[(900, 700)]);
        cleanup_component(id);
    }

    #[test]
    fn renderer_resize_state_initial_logical_size_suppresses_notification() {
        let _guard = resize_test_guard();
        let calls = Rc::new(RefCell::new(Vec::new()));
        let id = register_recorder(calls.clone());
        let mut state = ResizeState::new();

        assert_eq!(state.record_initial(800, 600, 1.0), (800, 600));
        assert_eq!(state.frame_logical_size(800, 600, 1.0, true), (800, 600));
        assert!(calls.borrow().is_empty());
        cleanup_component(id);
    }

    #[test]
    fn renderer_resize_state_uses_viewport_logical_pixels_for_dpi() {
        let _guard = resize_test_guard();
        let calls = Rc::new(RefCell::new(Vec::new()));
        let id = register_recorder(calls.clone());
        let mut state = ResizeState::new();

        assert_eq!(state.record_initial(1600, 1200, 2.0), (800, 600));
        state.queue((2000, 1000));
        assert_eq!(state.take_pending(), Some((2000, 1000)));
        assert_eq!(state.frame_logical_size(2000, 1000, 2.0, true), (1000, 500));
        assert_eq!(&*calls.borrow(), &[(1000, 500)]);
        cleanup_component(id);
    }

    #[test]
    fn two_windows_with_equal_committed_sizes_both_dispatch() {
        let _guard = resize_test_guard();
        let calls = Rc::new(RefCell::new(Vec::new()));
        let id = register_recorder(calls.clone());
        let mut first_window = ResizeState::new();
        let mut second_window = ResizeState::new();

        // Each window owns its baseline; both legitimately commit 900x600.
        first_window.record_initial(800, 600, 1.0);
        second_window.record_initial(700, 600, 1.0);
        first_window.queue((900, 600));
        second_window.queue((900, 600));

        first_window.frame_logical_size(900, 600, 1.0, true);
        second_window.frame_logical_size(900, 600, 1.0, true);

        assert_eq!(&*calls.borrow(), &[(900, 600), (900, 600)]);
        cleanup_component(id);
    }

    #[test]
    fn renderer_resize_state_runs_all_hooks_and_allows_signal_mutation() {
        let _guard = resize_test_guard();
        let first_calls = Rc::new(RefCell::new(Vec::new()));
        let second_calls = Rc::new(RefCell::new(Vec::new()));
        let signal = Rc::new(Signal::new(0u32));
        let id = generate_component_id();

        set_current_component(id);
        {
            let calls = first_calls.clone();
            on_resize(move |width, height| calls.borrow_mut().push((width, height)));
        }
        {
            let calls = second_calls.clone();
            let signal = signal.clone();
            on_resize(move |width, height| {
                calls.borrow_mut().push((width, height));
                signal.set(width + height);
            });
        }
        clear_current_component();

        let mut state = ResizeState::new();
        state.record_initial(100, 100, 1.0);
        state.queue((200, 150));
        assert_eq!(state.take_pending(), Some((200, 150)));
        assert_eq!(state.frame_logical_size(200, 150, 1.0, true), (200, 150));

        assert_eq!(&*first_calls.borrow(), &[(200, 150)]);
        assert_eq!(&*second_calls.borrow(), &[(200, 150)]);
        assert_eq!(signal.get(), 350);
        cleanup_component(id);
    }

    #[test]
    fn cleanup_component_removes_only_its_resize_hook() {
        let _guard = resize_test_guard();
        let removed_calls = Rc::new(RefCell::new(Vec::new()));
        let retained_calls = Rc::new(RefCell::new(Vec::new()));
        let removed_id = register_recorder(removed_calls.clone());
        let retained_id = register_recorder(retained_calls.clone());

        cleanup_component(removed_id);
        let mut state = ResizeState::new();
        state.record_initial(100, 100, 1.0);
        state.frame_logical_size(200, 150, 1.0, true);

        assert!(removed_calls.borrow().is_empty());
        assert_eq!(&*retained_calls.borrow(), &[(200, 150)]);
        cleanup_component(retained_id);
    }
}

// ---------------------------------------------------------------------------
// Task 5.6a — characterisation tests for the text-input edit and focus path.
//
// `apply_click_focus`, `apply_edit_to_focused` and `edit_action_for_key` are the
// three functions both copies of the event loop call into, and until this
// module landed none of them had any test coverage at all. A dedup that dropped
// or re-pointed an arm would have shipped silently, which is the failure mode
// these tests exist to prevent.
//
// They live here rather than in `tests/` because all three are *private* `fn`s
// behind `#[cfg(feature = "skia-native")]`; an integration test can only reach
// the crate's public API.
#[cfg(all(test, feature = "skia-native"))]
mod edit_focus_tests {
    use super::{
        apply_click_focus, apply_edit_to_focused, edit_action_for_key, inject_input_caret_attrs,
        recompute_targets, style_vnode_with_hover,
    };
    use crate::events::{EditAction, InputTarget};
    use velox_dom::{Props, VNode};
    use winit::event::VirtualKeyCode as K;

    const W: i32 = 400;
    const H: i32 = 300;
    /// Absolutely positioned so the field's rect is known exactly: the click
    /// tests below use literal coordinates and must not depend on layout order.
    const FIELD_STYLE: &str = "position:absolute;left:20px;top:20px;width:200px;height:40px;font-size:15px;padding-left:2px";
    const VALUE: &str = "hello";
    const HANDLER: &str = "set_value";
    /// The field spans x 20..220, y 20..60; its text starts at x 20 + 2px padding.
    const TEXT_X: f32 = 22.0;
    const TEXT_Y: f32 = 40.0;
    const EMPTY_X: f32 = 350.0;
    const EMPTY_Y: f32 = 250.0;

    /// `(handler, value)` pairs handed to the app, in dispatch order.
    type Dispatches = Vec<(String, Option<String>)>;

    /// One text input on a page, built through the frame order the loops use:
    /// style cascade, caret-attr injection, layout, then target collection.
    /// Going through the real pipeline is the point — a hand-assembled target
    /// vector would not exercise the `path`/`rect` plumbing these functions read.
    struct Scene {
        /// `None` models the window before the first `RedrawRequested`, when the
        /// loop has painted a frame but has not published it as `last_vnode`.
        vnode: Option<VNode>,
        inputs: Vec<InputTarget>,
        /// The loops' index-free mirror of "which input is focused". It is
        /// asserted on below, because after Esc it has to follow the blur
        /// rather than keep naming a field that is no longer focused.
        focused: Option<Vec<usize>>,
    }

    fn scene(attrs: &[(&str, &str)]) -> Scene {
        let mut p = Props::new()
            .set("type", "text")
            .set("style", FIELD_STYLE)
            .set("value", VALUE)
            .set("on:input", HANDLER);
        for (k, v) in attrs.iter().copied() {
            p = p.set(k, v);
        }
        let raw = VNode::Element {
            tag: "div".into(),
            props: Props::new().set("style", "background:#000000"),
            children: vec![VNode::Element {
                tag: "input".into(),
                props: p,
                children: vec![],
            }],
        };
        let sheet = velox_style::Stylesheet::default();
        let styled = style_vnode_with_hover(&raw, &sheet, &|_tag: &str, _p: &Props| false);
        let vnode = inject_input_caret_attrs(&styled, None);
        let layout = velox_dom::layout::compute_layout(&vnode, W, H);
        let mut clicks: Vec<crate::events::ClickTarget> = Vec::new();
        let mut hovers: Vec<crate::events::HoverTarget> = Vec::new();
        let mut inputs: Vec<InputTarget> = Vec::new();
        recompute_targets(&vnode, &layout, &mut clicks, &mut hovers, &mut inputs);
        assert_eq!(inputs.len(), 1, "fixture must yield exactly one text input");
        Scene {
            vnode: Some(vnode),
            inputs,
            focused: None,
        }
    }

    impl Scene {
        /// Focus the field with the caret `cursor` chars in.
        fn focused_at(mut self, cursor: usize) -> Self {
            self.inputs[0].focused = true;
            self.inputs[0].cursor = cursor;
            self
        }
    }

    /// Run one edit, returning whether the caller must repaint and everything
    /// dispatched to the app. Asserting on the dispatch log, not just the
    /// caret, is the point: a caret that moves while the handler is never
    /// called is precisely the silent-typing failure this suite must not miss.
    fn run_edit(s: &mut Scene, action: EditAction) -> (bool, Dispatches) {
        let mut log: Dispatches = Vec::new();
        let repaint = {
            let mut sink = |name: &str, data: Option<&str>| {
                log.push((name.to_string(), data.map(str::to_string)))
            };
            apply_edit_to_focused(&mut s.inputs, action, &s.vnode, &mut s.focused, &mut sink)
        };
        (repaint, log)
    }

    /// Click at (x, y), returning whether the caller must repaint. `focused` is
    /// the loop's own mirror of the focus flag, kept in `Scene` so the blur tests
    /// can assert it alongside the flag itself.
    fn run_click(s: &mut Scene, x: f32, y: f32) -> bool {
        // The viewport the loops pass is the live surface's logical size; this
        // module has no surface, so it passes the page it laid out against
        // (`W` x `H`) at scale 1. Only viewport-unit lengths (`vw`/`vh`) can
        // tell the two apart, and none of the fixtures below declare one.
        apply_click_focus(
            &mut s.inputs,
            &s.vnode,
            &mut s.focused,
            x,
            y,
            1.0,
            (W as f32, H as f32),
        )
    }

    // -- apply_edit_to_focused ------------------------------------------------

    #[test]
    fn insert_at_caret_dispatches_new_value_and_advances_caret() {
        let mut s = scene(&[]).focused_at(5);
        let (repaint, log) = run_edit(&mut s, EditAction::Insert('X'));
        assert!(repaint, "an inserted char must repaint");
        assert_eq!(log, vec![(HANDLER.to_string(), Some("helloX".into()))]);
        assert_eq!(s.inputs[0].cursor, 6);
    }

    #[test]
    fn insert_lands_at_the_caret_not_at_the_end() {
        let mut s = scene(&[]).focused_at(0);
        let (repaint, log) = run_edit(&mut s, EditAction::Insert('X'));
        assert!(repaint);
        assert_eq!(log, vec![(HANDLER.to_string(), Some("Xhello".into()))]);
        assert_eq!(s.inputs[0].cursor, 1);
    }

    #[test]
    fn backspace_removes_the_char_before_the_caret() {
        let mut s = scene(&[]).focused_at(5);
        let (repaint, log) = run_edit(&mut s, EditAction::Backspace);
        assert!(repaint);
        assert_eq!(log, vec![(HANDLER.to_string(), Some("hell".into()))]);
        assert_eq!(s.inputs[0].cursor, 4);
    }

    #[test]
    fn submit_dispatches_the_unchanged_value() {
        let mut s = scene(&[]).focused_at(5);
        let (repaint, log) = run_edit(&mut s, EditAction::Submit);
        assert!(
            repaint,
            "submit must repaint even though the text is unchanged"
        );
        assert_eq!(
            log,
            vec![(HANDLER.to_string(), Some("hello".into()))],
            "a submit with no selection must still reach the handler"
        );
        assert_eq!(s.inputs[0].cursor, 5);
    }

    #[test]
    fn caret_move_repaints_without_announcing_a_text_change() {
        let mut s = scene(&[]).focused_at(3);
        let (repaint, log) = run_edit(&mut s, EditAction::MoveLeft { shift: false });
        assert!(repaint, "a caret move is a visual change and must repaint");
        assert!(
            log.is_empty(),
            "a caret move must not dispatch a value change"
        );
        assert_eq!(s.inputs[0].cursor, 2);
    }

    #[test]
    fn shift_caret_move_anchors_a_selection() {
        let mut s = scene(&[]).focused_at(3);
        let (repaint, log) = run_edit(&mut s, EditAction::MoveLeft { shift: true });
        assert!(repaint);
        assert!(log.is_empty());
        assert_eq!(s.inputs[0].cursor, 2);
        assert_eq!(
            s.inputs[0].anchor,
            Some(3),
            "a shift-move must anchor at the caret's old position"
        );
    }

    #[test]
    fn no_focused_input_is_a_no_op() {
        let mut s = scene(&[]);
        assert!(!s.inputs[0].focused);
        let (repaint, log) = run_edit(&mut s, EditAction::Insert('X'));
        assert!(!repaint, "an edit with nothing focused must not repaint");
        assert!(log.is_empty());
    }

    #[test]
    fn backspace_at_caret_zero_changes_nothing() {
        let mut s = scene(&[]).focused_at(0);
        let (repaint, log) = run_edit(&mut s, EditAction::Backspace);
        assert!(!repaint, "backspace at index 0 is a no-op, not a repaint");
        assert!(log.is_empty(), "backspace at index 0 must not dispatch");
        assert_eq!(s.inputs[0].cursor, 0);
    }

    /// The target holds no value of its own — the tree does. This is the coupling
    /// that makes an unpublished frame (below) a correctness problem rather than
    /// a cosmetic one.
    #[test]
    fn dispatch_uses_the_value_in_the_tree_not_the_target() {
        let mut s = scene(&[("value", "world")]).focused_at(5);
        let (repaint, log) = run_edit(&mut s, EditAction::Backspace);
        assert!(repaint);
        assert_eq!(log, vec![(HANDLER.to_string(), Some("worl".into()))]);
    }

    // -- edit_action_for_key --------------------------------------------------

    /// Every key the two loops route to the editor. This is the mapping a dedup
    /// could silently transpose, and `Back`/`Delete`/`Return` are exactly the
    /// keys whose mis-wiring stays invisible until someone types.
    #[test]
    fn editing_keys_map_to_their_actions() {
        use EditAction::*;
        let cases: &[(K, bool, EditAction)] = &[
            (K::Left, false, MoveLeft { shift: false }),
            (K::Left, true, MoveLeft { shift: true }),
            (K::Right, false, MoveRight { shift: false }),
            (K::Right, true, MoveRight { shift: true }),
            (K::Home, false, Home { shift: false }),
            (K::Home, true, Home { shift: true }),
            (K::End, false, End { shift: false }),
            (K::End, true, End { shift: true }),
            (K::Back, false, Backspace),
            (K::Delete, false, Delete),
            (K::Return, false, Submit),
            // Esc is an editing key even though it changes no text: it is the
            // only way out of a field, and the match has no fallthrough to user
            // code, so anything absent here simply cannot happen.
            (K::Escape, false, Blur),
        ];
        for (key, shift, want) in cases {
            assert_eq!(
                edit_action_for_key(*key, *shift),
                Some(*want),
                "{key:?} with shift={shift}"
            );
        }
    }

    /// A printable key must map to `None`: characters reach the editor through
    /// `ReceivedCharacter`, so claiming one here would insert it twice.
    ///
    /// `Escape` is deliberately *not* in this list. It used to be, and that
    /// assertion was what pinned the bug: with Esc mapping to `None` and no
    /// other code handling it, the key was inert and a focused field could not
    /// be left. Esc maps to [`EditAction::Blur`] and the blur behaviour is
    /// asserted below.
    #[test]
    fn non_editing_keys_produce_no_action() {
        for key in [K::A, K::R, K::Key1, K::Space, K::Tab, K::Up, K::Down] {
            assert_eq!(
                edit_action_for_key(key, false),
                None,
                "{key:?} is not an editing key"
            );
        }
    }

    // -- Esc unfocuses --------------------------------------------------------

    /// Esc on a focused field drops focus, the selection and the caret, and
    /// leaves the text alone.
    ///
    /// The caret goes because Esc is an explicit "I am done here" rather than a
    /// click that wandered off — that is the difference from the empty-space
    /// blur above, which deliberately keeps the caret. The value must not
    /// change: Esc is not an edit, so the app must not be woken with an
    /// `on:input` it did not cause.
    #[test]
    fn escape_on_a_focused_field_blurs_it_and_drops_its_caret_and_selection() {
        let mut s = scene(&[]).focused_at(4);
        s.inputs[0].anchor = Some(1);
        assert_eq!(s.inputs[0].selection(), Some((1, 4)));

        let (repaint, log) = run_edit(&mut s, EditAction::Blur);

        assert!(
            repaint,
            "the focus ring and highlight disappear, so it repaints"
        );
        assert!(!s.inputs[0].focused, "Esc must leave the field");
        assert_eq!(
            s.inputs[0].anchor, None,
            "a selection cannot outlive the focus"
        );
        assert_eq!(s.inputs[0].cursor, 0, "Esc clears the caret");
        assert!(
            s.inputs[0].blink_on,
            "the caret comes back solid, not blinking"
        );
        assert!(
            log.is_empty(),
            "Esc changes no text, so nothing is dispatched"
        );
        assert_eq!(
            s.focused, None,
            "the loop's mirror of the focus must follow the blur, or it names a \
             field that is no longer focused"
        );
    }

    /// Esc with nothing focused is free — no repaint, no dispatch.
    ///
    /// Same contract as every other no-op keypress: the loops branch on
    /// `needs_repaint()`, and a wake-up here would repaint for nothing.
    #[test]
    fn escape_with_nothing_focused_is_a_no_op() {
        let mut s = scene(&[]);
        assert!(!s.inputs[0].focused);
        let (repaint, log) = run_edit(&mut s, EditAction::Blur);
        assert!(
            !repaint,
            "there was no focus to drop, so there is nothing to redraw"
        );
        assert!(log.is_empty());
        assert_eq!(s.focused, None);
    }

    /// Esc reaches the editor at all only because the key map claims it, so pin
    /// the mapping through the same call the loops make.
    #[test]
    fn escape_is_routed_to_the_blur_action() {
        assert_eq!(
            edit_action_for_key(K::Escape, false),
            Some(EditAction::Blur)
        );
        assert_eq!(
            edit_action_for_key(K::Escape, true),
            Some(EditAction::Blur),
            "Shift does not change what Esc means"
        );
    }

    // -- apply_click_focus ----------------------------------------------------

    #[test]
    fn focus_gain_puts_the_caret_at_the_end_of_the_value() {
        let mut s = scene(&[]);
        assert_eq!(s.inputs[0].cursor, 0);
        assert!(run_click(&mut s, TEXT_X + 1.0, TEXT_Y));
        assert!(s.inputs[0].focused);
        assert_eq!(
            s.inputs[0].cursor, 5,
            "focus gain must put the caret at the end, so typing appends"
        );
    }

    #[test]
    fn click_into_a_focused_field_repositions_the_caret() {
        let mut s = scene(&[]).focused_at(5);
        assert!(run_click(&mut s, TEXT_X + 1.0, TEXT_Y));
        assert!(s.inputs[0].focused);
        assert_eq!(
            s.inputs[0].cursor, 0,
            "clicking the first glyph must move the caret there, not leave it at the end"
        );
    }

    /// The regression this lane had: the origin was computed from a lookup of
    /// the literal key `padding-left`, which the cascade never writes for an
    /// authored shorthand. `padding: 6px 30px` therefore resolved to
    /// `rect.x + 0` while the painter drew the first glyph at `rect.x + 30`, so
    /// every caret sat 30px left of the glyph it claimed to be on. With the
    /// field focused, a click on the *first* glyph was measured 30px further
    /// right than it is and landed past the end of the value.
    #[test]
    fn shorthand_padding_places_the_caret_on_the_painted_glyph() {
        const SHORTHAND_STYLE: &str = "position:absolute;left:20px;top:20px;width:200px;height:40px;font-size:15px;padding:6px 30px";
        let mut s = scene(&[("style", SHORTHAND_STYLE)]).focused_at(5);
        let rect = s.inputs[0].rect;
        assert_eq!(rect.x, 20, "fixture must stay absolutely positioned");
        let text_left = rect.x as f32 + 30.0;

        assert!(run_click(&mut s, text_left + 1.0, TEXT_Y));
        assert_eq!(
            s.inputs[0].cursor, 0,
            "a click on the first glyph must put the caret before it, whatever \
             syntax the author used for the padding"
        );
    }

    /// The origin is not merely "shifted": it must equal the painter's
    /// `text_left` for every spelling of the same declaration, because both
    /// lanes now read the same computed value out of
    /// `input_metrics::input_text_metrics`.
    #[test]
    fn text_origin_agrees_with_the_paint_authority_for_every_padding_spelling() {
        use velox_dom::Props;
        let rect = velox_dom::layout::Rect {
            x: 20,
            y: 20,
            w: 200,
            h: 40,
        };
        let viewport = (W as f32, H as f32);
        let authored = [
            "padding: 6px 30px",
            "padding-left: 30px",
            "padding: 6px 30px; padding-left: 30px",
            "padding-left: 30px; padding: 6px 30px",
            "padding: 30px 6px 6px 30px",
        ];
        for decl in authored {
            let props = Props::new().set("style", decl);
            assert_eq!(
                super::resolve_text_metrics(&props, rect, viewport).text_left,
                50.0,
                "`{decl}` must resolve the same first-glyph x as the paint lane"
            );
            // …and the authority itself, not a local copy of it.
            let authority = crate::input_metrics::input_text_metrics(
                props.attrs.get("style").map(|s| s.as_str()),
                rect,
                viewport,
                velox_dom::layout::DEFAULT_ROOT_FONT_SIZE,
            );
            assert_eq!(
                super::resolve_text_metrics(&props, rect, viewport).text_left,
                authority.text_left,
                "`{decl}`: the hit-test lane must not re-derive what paint computed"
            );
        }
        // A viewport-unit left padding must resolve against the viewport the
        // caller threaded in — the same one paint resolves `vw` against.
        let props = Props::new().set("style", "padding-left: 5vw");
        assert_eq!(
            super::resolve_text_metrics(&props, rect, viewport).text_left,
            rect.x as f32 + 0.05 * W as f32
        );
    }

    /// The caret index a click at `click_x` leaves on a field styled `style`.
    ///
    /// The field is pre-focused on purpose: `apply_click_focus` sends the caret
    /// to the END of the value on focus gain, so a never-focused fixture would
    /// report "end of value" for every click x and any comparison built on it
    /// would pass without ever running the code under test.
    ///
    /// Overriding `style` and `value` on top of `FIELD_STYLE` matters for the
    /// same reason: `FIELD_STYLE` pins `font-size:15px`, and every fixture that
    /// inherits it silently opts out of the undeclared-font-size case these
    /// tests exist to cover.
    fn caret_from_click(style: &str, value: &str, click_x: f32) -> usize {
        let mut s = scene(&[("style", style), ("value", value)]).focused_at(0);
        assert!(
            run_click(&mut s, click_x, TEXT_Y),
            "the click at x={click_x} must land on the field, not on empty space"
        );
        s.inputs[0].cursor
    }

    /// Assert that two styles describing visually identical fields answer
    /// identically at every click x across the field, and that the answers are
    /// non-degenerate.
    ///
    /// `equal_windows` sweeps the whole field rather than probing one x on
    /// purpose. A single probe can land on a char boundary where two disagreeing
    /// advances happen to round to the same index, and the test would pass with
    /// the defect still in place; sweeping makes that unfalsifiable at one lucky
    /// coordinate.
    fn assert_carets_agree_across_field(equal: (&str, &str), value: &str) {
        let (a, b) = equal;
        // Collect the WHOLE profile before asserting, so a failure reports how
        // far apart the two lanes end up rather than only the first coordinate
        // where they parted.
        let mut profile: Vec<(f32, usize, usize)> = Vec::new();
        let mut indices: Vec<usize> = Vec::new();
        let mut x = 20.0;
        while x <= 219.0 {
            let ca = caret_from_click(a, value, x);
            let cb = caret_from_click(b, value, x);
            if ca != cb {
                profile.push((x, ca, cb));
            }
            indices.push(ca);
            x += 1.0;
        }
        let worst = profile
            .iter()
            .map(|&(_, u, v)| (u as i64 - v as i64).abs())
            .max()
            .unwrap_or(0);
        assert!(
            profile.is_empty(),
            "`{a}` and `{b}` paint identically, so the caret must land on the same \
             glyph at every click x. They disagree at {} of 200 coordinates, by up \
             to {worst} character(s); first divergence: {:?}",
            profile.len(),
            profile.first()
        );
        // Anti-vacuity: a lane that ignored the click entirely, or that always
        // answered "end of value", would satisfy the equality above trivially.
        let len = value.chars().count();
        assert!(
            indices.iter().any(|&i| i > 0 && i < len),
            "every click resolved to an end-of-value caret, so this compared \
             nothing: {indices:?}"
        );
    }

    /// The click-to-caret lane must measure advances at the size the PAINT lane
    /// draws them at, and must not hold a second answer to "how big is this
    /// field".
    ///
    /// The proof is differential and needs no font metric, no geometry constant
    /// and no knowledge of which face is bundled: an input that declares no
    /// `font-size` paints at the painter's root size — that is what "declares
    /// none" means — which is by definition the same size an input declaring
    /// that size *explicitly* paints at. The two fixtures are therefore
    /// identical on screen, so a click at the same x must leave the caret on
    /// the same glyph, whatever each lane measured with.
    ///
    /// This is exactly the shipped-boilerplate-shaped hole: the UA sheet
    /// declares no `font-size` for `input`, so a field that never says it
    /// inherits 14px from the painter's root `TextStyle` while the hit-test lane
    /// fell back to its own 16px. Every advance came out `16/14` wide, so a
    /// click at the far end of the value landed the caret roughly one character
    /// short for every seven clicked.
    #[test]
    fn the_caret_lane_measures_at_the_size_an_undeclared_font_size_paints_at() {
        // Wide glyphs, and enough of them that a 14%-wide advance error cannot
        // hide inside one character's slack over the 200px field.
        assert_carets_agree_across_field(
            (
                "position:absolute;left:20px;top:20px;width:200px;height:40px",
                "position:absolute;left:20px;top:20px;width:200px;height:40px;font-size:14px",
            ),
            &"M".repeat(20),
        );
    }

    /// The origin half of the same defect, which survived after the origin was
    /// first routed through the shared authority: an `em` padding resolves
    /// against the ELEMENT's font size, so an element that inherits its size has
    /// to resolve `4em` against the inherited size in *both* lanes. The hit-test
    /// lane passed its own 16px where paint inherits 14px, so the caret sat a
    /// whole `4em` — 16px — to the right of the glyph it claimed to be on.
    #[test]
    fn em_padding_resolves_against_the_same_inherited_size_in_both_lanes() {
        // Vertical padding stays 0 so the only thing under test is the
        // horizontal origin, and the field's box cannot move out from under the
        // literal click coordinates the sweep uses.
        assert_carets_agree_across_field(
            (
                "position:absolute;left:20px;top:20px;width:200px;height:40px;padding:0 4em",
                "position:absolute;left:20px;top:20px;width:200px;height:40px;padding:0 4em;font-size:14px",
            ),
            &"M".repeat(20),
        );
    }

    /// A relative `font-size` is resolved against the inherited size by the
    /// cascade, so `2em` on a field that inherits 14px paints at 28px — and
    /// nothing about that declaration contains a `px` suffix for a lane-local
    /// literal parser to find.
    #[test]
    fn a_relative_font_size_reaches_the_caret_lane_at_its_resolved_size() {
        assert_carets_agree_across_field(
            (
                "position:absolute;left:20px;top:20px;width:200px;height:40px;font-size:2em",
                "position:absolute;left:20px;top:20px;width:200px;height:40px;font-size:28px",
            ),
            &"M".repeat(20),
        );
    }

    #[test]
    fn clicking_empty_space_blurs_clears_the_selection_and_keeps_the_caret() {
        let mut s = scene(&[]).focused_at(5);
        s.inputs[0].anchor = Some(1);
        assert!(
            run_click(&mut s, EMPTY_X, EMPTY_Y),
            "a blur is a visual change"
        );
        assert!(!s.inputs[0].focused);
        assert_eq!(
            s.inputs[0].anchor, None,
            "a stale highlight must not survive a blur"
        );
        assert_eq!(
            s.inputs[0].cursor, 5,
            "blur keeps the caret, so re-entering the field restores position"
        );
    }

    #[test]
    fn clicking_empty_space_with_nothing_focused_changes_nothing() {
        let mut s = scene(&[]);
        assert!(
            !run_click(&mut s, EMPTY_X, EMPTY_Y),
            "a click on empty space with nothing focused is not a change"
        );
    }

    // -- the `last_vnode` window ----------------------------------------------
    //
    // Both loops declare `last_vnode` as `None` and only assign it on
    // `RedrawRequested`, so before the loop's first redraw it is empty. The HMR
    // loop additionally publishes its pre-loop frame; these tests pin what the
    // plain loop must do to match, and what happens if it does not.

    /// With no published frame there is nothing to measure or to read a value
    /// from, so focus gain leaves the caret at 0 — which turns "click a field
    /// and type" into a *prepend*.
    #[test]
    fn focus_gain_with_no_published_frame_puts_the_caret_at_zero() {
        let mut s = scene(&[]);
        s.vnode = None;
        assert!(run_click(&mut s, TEXT_X + 1.0, TEXT_Y));
        assert!(s.inputs[0].focused);
        assert_eq!(
            s.inputs[0].cursor, 0,
            "with no frame to measure, focus gain leaves the caret at 0 and typing prepends"
        );
    }

    /// The other half of the same window: the edit mutates the caret, reports
    /// "repaint", and reaches the app not at all. The keystroke is lost and the
    /// caret is left corrupted — the value reads as `""`, so the caret is
    /// clamped to 0 before the insert and lands at 1 rather than 6.
    #[test]
    fn insert_with_no_published_frame_is_silently_dropped() {
        let mut s = scene(&[]).focused_at(5);
        s.vnode = None;
        let (repaint, log) = run_edit(&mut s, EditAction::Insert('X'));
        assert!(
            repaint,
            "the edit still reports a repaint, so the loop schedules a frame for nothing"
        );
        assert!(
            log.is_empty(),
            "no dispatch at all: the app never sees the keystroke, yet the caret moved"
        );
        assert_eq!(
            s.inputs[0].cursor, 1,
            "the caret is clamped to an empty value and corrupted, not advanced to 6"
        );
    }

    /// `last_vnode` is what the two functions above read, so both loops must
    /// publish the frame they render *before* they start dispatching input, not
    /// only once the first `RedrawRequested` arrives. Structural — the loops need
    /// a live window — but it is the only thing that binds the requirement to the
    /// loops themselves rather than to one call site.
    #[test]
    fn both_loops_publish_their_pre_loop_frame_before_they_start() {
        let src = include_str!("lib.rs");
        // Assembled from two halves on purpose: `include_str!` reads this test
        // module too, and a needle written out in full would match its own
        // source and look like a third loop.
        let decl = format!("last_vnode: Option<{}::VNode> = None;", "velox_dom");
        let mut loops = 0usize;
        let mut rest = src;
        while let Some(at) = rest.find(decl.as_str()) {
            loops += 1;
            let body = &rest[at..];
            let run_at = body
                .find("event_loop.run(")
                .unwrap_or_else(|| panic!("loop {loops} has no `event_loop.run(`"));
            assert!(
                body[..run_at].contains("last_vnode = Some("),
                "loop {loops} must assign last_vnode in its pre-loop frame; until it does, every \
                 click and keystroke before the first redraw is handled against an empty value"
            );
            rest = &body[run_at..];
        }
        assert_eq!(loops, 2, "expected the plain loop and the HMR loop");
    }
}