retroglyph-window 0.5.0

Shared winit windowing layer for retroglyph's windowed backends
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
//! The winit event loop and the windowed app drivers.
//!
//! [`run_windowed`] drives a raw `FnMut(&mut Terminal<..>)` closure;
//! [`run_app`] drives an [`App`](retroglyph_core::app::App). This is the inverted
//! driver: winit owns the loop and calls back into the app on each redraw,
//! so it cannot be core's generic
//! [`run_blocking`](retroglyph_core::app::run_blocking), which owns its own
//! `while` loop.

use super::translate::{
    translate_ime, translate_key, translate_modifiers, translate_mouse_button,
    translate_physical_pos,
};
#[cfg(target_arch = "wasm32")]
use super::web;
use crate::backend::WindowBackend;
use crate::presenter::Presenter;
use retroglyph_core::backend::{Input, Output};
use retroglyph_core::event::{
    Event, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, PhysicalPos,
};
use retroglyph_core::grid::HasSize;
use retroglyph_core::terminal::Terminal;
use std::cell::Cell;
use std::fmt;
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::window::{Window, WindowId};

/// A thread-safe handle for injecting application-defined events into a running windowed event
/// loop from another thread (network, audio, timer, ...).
///
/// Obtained via the `on_proxy` callback passed to [`run_windowed_with_proxy`]/
/// [`run_app_with_proxy`] (payload fixed to `u64`, delivered as [`Event::Custom`]) or
/// [`run_windowed_with_typed_proxy`]/[`run_app_with_typed_proxy`] (any `T: Send + 'static`,
/// delivered to a caller-supplied handler), invoked synchronously right after the event loop
/// (and this proxy) is created, before the loop starts blocking the calling thread. Clone it
/// freely to hand a copy to each worker thread that needs to wake the loop; wraps winit's own
/// [`EventLoopProxy`](winit::event_loop::EventLoopProxy), which is `Send + Sync` for any
/// `T: Send + 'static` payload.
///
/// `T` defaults to `u64` (the payload [`Event::Custom`] itself carries), so existing code
/// naming the bare `EventProxy` type (from before this type became generic) keeps compiling
/// unchanged.
pub struct EventProxy<T: Send + 'static = u64>(winit::event_loop::EventLoopProxy<T>);

// Hand-written rather than `#[derive(Clone, Debug)]`: a derive would add `T: Clone`/`T: Debug`
// bounds to the impl, but `winit::event_loop::EventLoopProxy<T>` itself needs neither: cloning
// or formatting the proxy handle never touches a buffered `T` value (there isn't one; `T` is
// only ever a transient argument to `send_event`).
impl<T: Send + 'static> Clone for EventProxy<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T: Send + 'static> fmt::Debug for EventProxy<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("EventProxy").field(&self.0).finish()
    }
}

impl<T: Send + 'static> EventProxy<T> {
    /// Injects `payload` into the event loop's queue, waking it if it's asleep.
    ///
    /// With the default `T = u64` (via [`run_windowed_with_proxy`]/[`run_app_with_proxy`]), the
    /// payload surfaces through the app's normal `poll_event`/frame loop as
    /// [`Event::Custom(payload)`](Event::Custom), like any other [`Event`]. With a custom `T`
    /// (via [`run_windowed_with_typed_proxy`]/[`run_app_with_typed_proxy`]), the payload is
    /// handed directly to that call's `on_custom_event` handler instead: it never becomes an
    /// [`Event`], since [`Event::Custom`] is fixed to `u64`.
    ///
    /// # Errors
    ///
    /// Returns [`EventProxyClosed`] if the event loop has already exited.
    pub fn send_event(&self, payload: T) -> Result<(), EventProxyClosed<T>> {
        self.0
            .send_event(payload)
            .map_err(|e| EventProxyClosed(e.0))
    }
}

/// Error returned by [`EventProxy::send_event`] when the event loop it targets has already
/// exited.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EventProxyClosed<T = u64>(T);

impl<T> EventProxyClosed<T> {
    /// The payload that could not be delivered.
    #[must_use]
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> fmt::Display for EventProxyClosed<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "event loop closed")
    }
}

impl<T: fmt::Debug> std::error::Error for EventProxyClosed<T> {}

/// Window configuration for [`run_windowed`] / [`run_app`].
///
/// Renderer-agnostic: pixel dimensions, not grid/font/scale.
/// Use [`fit`](Self::fit) to derive the pixel size from a presenter's own
/// cell geometry.
///
/// Several builder methods below ([`resizable`](Self::resizable), [`decorations`](Self::decorations),
/// [`transparency`](Self::transparency), [`fullscreen`](Self::fullscreen)) target an OS-level
/// window control that a `wasm32` canvas doesn't have; on that target winit's web backend either
/// ignores the value outright or can't reliably apply it (see each method for which, and why).
/// The value is still applied for source-level parity with native either way, so the same call
/// chain compiles and runs on both targets, it just may not visibly do anything in the browser.
// Five independent window attribute toggles (`fill_viewport`, `resizable`, `decorations`,
// `fullscreen`, `transparency`), not a state machine in disguise: each maps to one winit
// `WindowAttributes` builder call and is meaningful on its own.
#[allow(clippy::struct_excessive_bools)]
pub struct WindowConfig {
    title: String,
    width: u32,
    height: u32,
    target_fps: Option<u32>,
    event_driven: bool,
    fill_viewport: bool,
    resizable: bool,
    decorations: bool,
    min_size: Option<(u32, u32)>,
    max_size: Option<(u32, u32)>,
    initial_position: Option<(i32, i32)>,
    fullscreen: bool,
    transparency: bool,
}

impl WindowConfig {
    /// Size the window to exactly fit `presenter`'s grid:
    /// `cols x cell_w` by `rows x cell_h` physical pixels.
    ///
    /// This is why renderer crates don't need their own windowing code: the
    /// grid/cell geometry already lives behind
    /// [`Output::size`] and
    /// [`Presenter::cell_size`].
    ///
    /// `target_fps` and `event_driven` are independent controls, on native and `wasm32` alike:
    ///
    /// - `target_fps` is the frame-rate cap applied whenever a frame is actually rendered: `None`
    ///   is uncapped (render as fast as the loop reaches a redraw), `Some(fps)` paces redraws to
    ///   no more than `fps` per second.
    /// - `event_driven` picks between the two redraw-triggering modes:
    ///   - `true` is **redraw-on-demand**: a frame is rendered only after something happened (an
    ///     input or window event, an injected [`Event::Custom`], window creation), and the loop
    ///     sleeps otherwise. Right for event-driven retro/terminal UIs, which are idle most of
    ///     the time; wrong for anything that animates from
    ///     [`Frame::delta`](retroglyph_core::app::Frame::delta), which will render one frame and then
    ///     sit still until the next stray event.
    ///   - `false` is **continuous**: a frame is rendered every tick whether or not anything
    ///     happened, which is what a `retroglyph_ui::Tween`/
    ///     [`FrameClock`](retroglyph_core::frames::FrameClock)-driven app needs.
    ///
    /// The two combine independently: `(Some(fps), false)` is the common capped-animation shape
    /// (see [`Self::animated`] for a shorthand), `(None, true)` is the common idle-UI shape, and
    /// `(None, false)` (render every tick, uncapped) is the one combination that was
    /// previously inexpressible, useful for e.g. measuring a render loop's raw throughput.
    ///
    /// On `wasm32` the browser owns frame pacing: winit's web backend delivers each requested
    /// redraw on the next `requestAnimationFrame`, so an uncapped or `event_driven: false` loop
    /// still runs at the display refresh rate and `target_fps`'s specific number is advisory
    /// (there is no way to render faster than `requestAnimationFrame`, and rendering slower would
    /// mean discarding frames the browser already scheduled). Only the `event_driven` choice
    /// carries across unaffected.
    #[must_use]
    pub fn fit<P: Presenter>(
        presenter: &P,
        title: impl Into<String>,
        target_fps: Option<u32>,
        event_driven: bool,
    ) -> Self {
        let grid = presenter.size();
        let (cell_w, cell_h) = presenter.cell_size();
        Self {
            title: title.into(),
            width: u32::from(grid.width()) * cell_w,
            height: u32::from(grid.height()) * cell_h,
            target_fps,
            event_driven,
            fill_viewport: false,
            resizable: true,
            decorations: true,
            min_size: None,
            max_size: None,
            initial_position: None,
            fullscreen: false,
            transparency: false,
        }
    }

    /// The window title, as set by [`fit`](Self::fit).
    #[must_use]
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Initial inner width in physical pixels, as computed by [`fit`](Self::fit).
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Initial inner height in physical pixels, as computed by [`fit`](Self::fit).
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// Shorthand for [`fit`](Self::fit) with continuous, non-event-driven, `fps`-capped
    /// redraws: the shape most animated apps want. Equivalent to
    /// `Self::fit(presenter, title, Some(fps), false)`.
    #[must_use]
    pub fn animated<P: Presenter>(presenter: &P, title: impl Into<String>, fps: u32) -> Self {
        Self::fit(presenter, title, Some(fps), false)
    }

    /// The frame-rate cap passed to [`fit`](Self::fit); see its doc comment for what `None` vs.
    /// `Some(fps)` means and how it combines with [`event_driven`](Self::event_driven).
    #[must_use]
    pub const fn target_fps(&self) -> Option<u32> {
        self.target_fps
    }

    /// The redraw-triggering mode passed to [`fit`](Self::fit); see its doc comment for what
    /// `true` vs. `false` means and how it combines with [`target_fps`](Self::target_fps).
    #[must_use]
    pub const fn event_driven(&self) -> bool {
        self.event_driven
    }

    /// Sets whether to size (and keep resizing) the canvas to fill the browser viewport on
    /// `wasm32`, instead of the pixel size [`fit`](Self::fit) computed: a full-screen,
    /// mobile-web-app feel for games that want it. Has no effect on native, where the OS window
    /// is already sized by [`fit`](Self::fit) and the window manager owns further resizing
    /// either way.
    ///
    /// Defaults to `false`: most demos/examples should render at their natural grid size
    /// (`cols x cell_w` by `rows x cell_h`) wherever they land on the page, not stretch to fill
    /// whatever viewport happens to be hosting them. Opt in explicitly for an app-like,
    /// full-screen game.
    #[must_use]
    pub const fn fill_viewport(mut self, fill_viewport: bool) -> Self {
        self.fill_viewport = fill_viewport;
        self
    }

    /// Sets whether the window can be resized by the user/window manager after creation.
    ///
    /// Defaults to `true` (winit's own default). Set to `false` for fixed-size retro windows
    /// where the grid is meant to stay put: resizing a pseudo-graphic UI usually means picking
    /// a new grid size, not stretching cells, and most callers that care already size the window
    /// to their content via [`fit`](Self::fit).
    ///
    /// On `wasm32`, winit's web backend ignores this: there is no OS-level resize grip on a
    /// canvas.
    #[must_use]
    pub const fn resizable(mut self, resizable: bool) -> Self {
        self.resizable = resizable;
        self
    }

    /// Sets whether the window has OS chrome: title bar, borders, close/minimize/maximize
    /// buttons.
    ///
    /// Defaults to `true` (winit's own default). Set to `false` for a borderless window
    /// (custom-drawn title bars, retro full-bleed layouts).
    ///
    /// On `wasm32`, winit's web backend ignores this: a canvas has no OS chrome to begin with.
    #[must_use]
    pub const fn decorations(mut self, decorations: bool) -> Self {
        self.decorations = decorations;
        self
    }

    /// Sets the minimum inner (content) size in physical pixels.
    ///
    /// Defaults to no minimum.
    #[must_use]
    pub const fn min_size(mut self, width: u32, height: u32) -> Self {
        self.min_size = Some((width, height));
        self
    }

    /// Sets the maximum inner (content) size in physical pixels.
    ///
    /// Defaults to no maximum.
    #[must_use]
    pub const fn max_size(mut self, width: u32, height: u32) -> Self {
        self.max_size = Some((width, height));
        self
    }

    /// Sets the desired initial outer window position in physical pixels.
    ///
    /// Defaults to letting the platform choose.
    ///
    /// On `wasm32`, winit's web backend maps this to the canvas's `position: absolute`
    /// left/top, which only does anything if the page's CSS has already opted the canvas into
    /// absolute/relative positioning; otherwise normal document flow overrides it.
    #[must_use]
    pub const fn initial_position(mut self, x: i32, y: i32) -> Self {
        self.initial_position = Some((x, y));
        self
    }

    /// Sets whether to request borderless fullscreen (on the window's current monitor) at
    /// creation.
    ///
    /// Defaults to `false`. This only exposes borderless fullscreen, not winit's
    /// exclusive-fullscreen video-mode API: retro/terminal-style apps render a fixed cell grid,
    /// not a resolution-dependent 3D scene, so there is no benefit to an exclusive video-mode
    /// switch, only extra platform-specific complexity (enumerating
    /// [`VideoModeHandle`](winit::monitor::VideoModeHandle)s) for a mode real games would rarely
    /// want here.
    ///
    /// On `wasm32`, winit's web backend maps this to the browser's Fullscreen API
    /// (`Element.requestFullscreen`), which most browsers refuse to grant without a user
    /// gesture; requesting it unconditionally at window-creation time (before any gesture) is
    /// liable to silently fail there.
    #[must_use]
    pub const fn fullscreen(mut self, fullscreen: bool) -> Self {
        self.fullscreen = fullscreen;
        self
    }

    /// Sets whether the window's background supports transparency (alpha blending with whatever
    /// is behind it).
    ///
    /// Defaults to `false` (winit's own default).
    ///
    /// On `wasm32`, winit's web backend ignores this: a canvas is already alpha-blended with the
    /// page behind it via normal CSS compositing.
    #[must_use]
    pub const fn transparency(mut self, transparency: bool) -> Self {
        self.transparency = transparency;
        self
    }
}

/// Open a window and drive `app_loop` from the winit event loop.
///
/// On native this blocks the calling thread until the loop exits; on wasm it
/// returns immediately and the loop continues on `requestAnimationFrame`.
///
/// The closure receives `&mut Terminal<WindowBackend<P>>` and is called on
/// every frame tick. Window close pushes [`Event::Close`] into the event
/// queue rather than exiting: the game decides when to terminate.
///
/// # Presenting is automatic
///
/// Unlike [`run_blocking`](retroglyph_core::app::run_blocking), this driver calls
/// [`Terminal::present`] for you, once, right after `app_loop` returns each frame: you no longer
/// need to (and, for a stale-content bug fixed by this behavior, should not rely on remembering
/// to) call it yourself inside `app_loop`. Calling it yourself is still supported and has no ill
/// effect (the driver detects it already ran and skips its own call), for example if you also want
/// to call [`Terminal::present`] to observe its `Result` directly.
///
/// # Errors
///
/// Returns [`winit::error::EventLoopError`] if the event loop cannot be
/// created or fails while running.
pub fn run_windowed<P, F>(
    config: WindowConfig,
    presenter: P,
    app_loop: F,
) -> Result<(), winit::error::EventLoopError>
where
    P: Presenter + 'static,
    F: FnMut(&mut Terminal<WindowBackend<P>>) + 'static,
{
    run_windowed_with_proxy(config, presenter, app_loop, |_proxy| {})
}

/// Same as [`run_windowed`], but also hands `on_proxy` an [`EventProxy`] for injecting
/// cross-thread events.
///
/// `on_proxy` is called synchronously right after the event loop (and the proxy) is created,
/// before this function starts blocking the calling thread on native. Use this over
/// [`run_windowed`] whenever another thread (network, audio, timer, ...) needs to wake the event
/// loop and deliver an [`Event::Custom`] to the app; `on_proxy` is the hook to hand a clone of the
/// proxy off to that thread before the loop takes over the calling thread.
///
/// The injected payload is always a `u64`, delivered as [`Event::Custom`] through the app's
/// normal `poll_event`/frame loop; see [`run_windowed_with_typed_proxy`] if a worker thread
/// needs to hand back a real payload (a loaded asset, a network response) instead of a
/// correlation id into a side table.
///
/// See [`run_windowed`]'s "Presenting is automatic" section: this function shares the same
/// automatic-present behavior; `app_loop` no longer needs to call [`Terminal::present`] itself.
///
/// # Examples
///
/// ```no_run
/// use retroglyph_core::event::Event;
/// use retroglyph_software::SoftwareBackendBuilder;
/// use retroglyph_window::winit::{WindowConfig, run_windowed_with_proxy};
/// use std::time::Duration;
///
/// let renderer = SoftwareBackendBuilder::new()
///     .grid_size(80, 25)
///     .scale(2)
///     .build()
///     .expect("backend init failed")
///     .into_renderer()
///     .expect("renderer init failed");
/// let config = WindowConfig::fit(&renderer, "My Game", None, true);
///
/// run_windowed_with_proxy(
///     config,
///     renderer,
///     move |term| {
///         if let Some(Event::Custom(id)) = term.poll(Duration::from_millis(16)) {
///             // Handle the tick/network/audio result tagged `id`.
///             println!("got custom event {id}");
///         }
///     },
///     |proxy| {
///         // Runs before the blocking call below starts, so the proxy can be
///         // handed off to a worker thread up front.
///         std::thread::spawn(move || loop {
///             std::thread::sleep(Duration::from_secs(1));
///             if proxy.send_event(1).is_err() {
///                 break; // The window closed; stop ticking.
///             }
///         });
///     },
/// )
/// .expect("event loop failed");
/// ```
///
/// # Errors
///
/// Returns [`winit::error::EventLoopError`] if the event loop cannot be
/// created or fails while running.
pub fn run_windowed_with_proxy<P, F, O>(
    config: WindowConfig,
    presenter: P,
    app_loop: F,
    on_proxy: O,
) -> Result<(), winit::error::EventLoopError>
where
    P: Presenter + 'static,
    F: FnMut(&mut Terminal<WindowBackend<P>>) + 'static,
    O: FnOnce(EventProxy),
{
    run_windowed_with_typed_proxy_and_exit_flag(
        config,
        presenter,
        app_loop,
        on_proxy,
        push_custom_event,
        Rc::new(Cell::new(false)),
        Rc::new(Cell::new(false)),
    )
}

/// Same as [`run_windowed_with_proxy`], but the injected payload can be any `T: Send + 'static`
/// instead of a fixed `u64`.
///
/// A `T` payload never becomes a [`retroglyph_core::event::Event`]: [`Event::Custom`] is fixed to
/// `u64` (see its doc comment for why), so genericizing it would be a breaking change to
/// [`retroglyph_core`] far larger than this API needs. Instead, each injected `T` is handed
/// directly to `on_custom_event`, called synchronously from winit's `user_event` callback with
/// the same `&mut Terminal<WindowBackend<P>>` `app_loop` receives on redraw, so a handler that
/// wants the result to affect the next frame just needs to record it in state the closures
/// share, or push its own backend-agnostic event/marker for `app_loop` to notice.
///
/// See [`run_windowed`]'s "Presenting is automatic" section: this function shares the same
/// automatic-present behavior; `app_loop` no longer needs to call [`Terminal::present`] itself.
///
/// This delivery is a side channel, not a queued [`Event`]: `on_custom_event` runs as soon as
/// winit dispatches the `user_event`, which can be before `app_loop` next drains earlier-queued
/// window/input events via [`poll`](retroglyph_core::terminal::Terminal::poll). Don't assume a `T` arrives
/// interleaved with the `poll()` stream in send order relative to those events; if that matters,
/// use [`run_windowed_with_proxy`]'s plain `u64`/[`Event::Custom`] path instead, which does
/// interleave on the backend's own FIFO.
///
/// # Examples
///
/// ```no_run
/// use retroglyph_software::SoftwareBackendBuilder;
/// use retroglyph_window::winit::{WindowConfig, run_windowed_with_typed_proxy};
/// use std::time::Duration;
///
/// enum WorkerResult {
///     AssetLoaded { name: String, bytes: Vec<u8> },
/// }
///
/// let renderer = SoftwareBackendBuilder::new()
///     .grid_size(80, 25)
///     .scale(2)
///     .build()
///     .expect("backend init failed")
///     .into_renderer()
///     .expect("renderer init failed");
/// let config = WindowConfig::fit(&renderer, "My Game", None, true);
///
/// run_windowed_with_typed_proxy(
///     config,
///     renderer,
///     move |term| {
///         let _ = term.poll(Duration::from_millis(16));
///     },
///     |proxy| {
///         std::thread::spawn(move || {
///             let bytes = std::fs::read("asset.bin").unwrap_or_default();
///             let _ = proxy.send_event(WorkerResult::AssetLoaded {
///                 name: "asset.bin".into(),
///                 bytes,
///             });
///         });
///     },
///     |result: WorkerResult, _term| match result {
///         WorkerResult::AssetLoaded { name, bytes } => {
///             println!("loaded {name}: {} bytes", bytes.len());
///         }
///     },
/// )
/// .expect("event loop failed");
/// ```
///
/// # Errors
///
/// Returns [`winit::error::EventLoopError`] if the event loop cannot be
/// created or fails while running.
pub fn run_windowed_with_typed_proxy<T, P, F, O, D>(
    config: WindowConfig,
    presenter: P,
    app_loop: F,
    on_proxy: O,
    on_custom_event: D,
) -> Result<(), winit::error::EventLoopError>
where
    T: Send + 'static,
    P: Presenter + 'static,
    F: FnMut(&mut Terminal<WindowBackend<P>>) + 'static,
    O: FnOnce(EventProxy<T>),
    D: FnMut(T, &mut Terminal<WindowBackend<P>>) + 'static,
{
    run_windowed_with_typed_proxy_and_exit_flag(
        config,
        presenter,
        app_loop,
        on_proxy,
        on_custom_event,
        Rc::new(Cell::new(false)),
        Rc::new(Cell::new(false)),
    )
}

/// Delivers a `u64` payload injected through [`EventProxy::send_event`] as
/// [`Event::Custom`]: the fixed `on_custom_event` behind [`run_windowed_with_proxy`]/
/// [`run_app_with_proxy`], preserving the pre-generic behavior exactly.
fn push_custom_event<P: Presenter>(id: u64, term: &mut Terminal<WindowBackend<P>>) {
    term.backend_mut().push_event(Event::Custom(id));
}

/// Shared implementation behind [`run_windowed_with_proxy`], [`run_windowed_with_typed_proxy`],
/// [`run_app_with_proxy`], and [`run_app_with_typed_proxy`].
///
/// `exit_requested` is checked after every [`WindowEvent::RedrawRequested`] and, when set, drives
/// [`ActiveEventLoop::exit`] so the loop unwinds normally (see [`WindowApp::exit_requested`]'s doc
/// comment for why this can't be plumbed through `app_loop`'s return value instead).
/// [`run_windowed_with_proxy`]/[`run_windowed_with_typed_proxy`] pass flags nobody ever sets (a
/// plain `FnMut(&mut Terminal<..>)` closure has no way to reach them); [`run_app_with_proxy`]/
/// [`run_app_with_typed_proxy`] share both with the closure they build around `app_loop`: it sets
/// `exit_requested` on [`Flow::Exit`](retroglyph_core::app::Flow::Exit) and `skip_present` on
/// [`Flow::Idle`](retroglyph_core::app::Flow::Idle).
fn run_windowed_with_typed_proxy_and_exit_flag<T, P, F, O, D>(
    config: WindowConfig,
    presenter: P,
    app_loop: F,
    on_proxy: O,
    on_custom_event: D,
    exit_requested: Rc<Cell<bool>>,
    skip_present: Rc<Cell<bool>>,
) -> Result<(), winit::error::EventLoopError>
where
    T: Send + 'static,
    P: Presenter + 'static,
    F: FnMut(&mut Terminal<WindowBackend<P>>) + 'static,
    O: FnOnce(EventProxy<T>),
    D: FnMut(T, &mut Terminal<WindowBackend<P>>) + 'static,
{
    let terminal = Terminal::new(WindowBackend::new(presenter));
    let event_loop = EventLoop::<T>::with_user_event().build()?;
    on_proxy(EventProxy(event_loop.create_proxy()));

    // `Some(0)` has no finite pacing interval to express, so it falls back to uncapped rather
    // than computing `Duration::from_secs_f64(f64::INFINITY)` (which panics).
    let frame_interval = config
        .target_fps
        .filter(|&fps| fps != 0)
        .map(|fps| Duration::from_secs_f64(1.0 / f64::from(fps)));

    let attrs = WindowAttrs::from(&config);
    let app = WindowApp {
        terminal: Some(terminal),
        app_loop,
        on_custom_event,
        window: None,
        title: config.title,
        init_size: InitWindowSize {
            width: config.width,
            height: config.height,
        },
        attrs,
        #[cfg(target_arch = "wasm32")]
        fill_viewport: config.fill_viewport,
        current_modifiers: KeyModifiers::NONE,
        cursor_px: (0.0, 0.0),
        active_touch: None,
        held_buttons: 0,
        frame_interval,
        event_driven: config.event_driven,
        #[cfg(not(target_arch = "wasm32"))]
        next_frame: std::time::Instant::now(),
        exit_requested,
        skip_present,
        needs_redraw: true,
        consecutive_present_errors: 0,
        _user_event: PhantomData,
    };

    #[cfg(not(target_arch = "wasm32"))]
    {
        let mut app = app;
        event_loop.run_app(&mut app)
    }

    #[cfg(target_arch = "wasm32")]
    {
        use winit::platform::web::EventLoopExtWebSys;
        event_loop.spawn_app(app);
        Ok(())
    }
}

/// Drive an [`App`](retroglyph_core::app::App) from the windowed event loop.
///
/// This is the inverted driver: winit owns the event loop and calls back
/// into the app on each redraw, rather than the app owning a `while` loop.
///
/// Each frame builds a [`Frame`](retroglyph_core::app::Frame) with a wall-clock
/// `dt` measured via [`web_time::Instant`]: a plain [`std::time::Instant`]
/// re-export on native, backed by the browser's `Performance.now()` on
/// `wasm32` (where `std::time::Instant` itself is unavailable). Calls
/// [`App::update`](retroglyph_core::app::App::update).
///
/// On [`Flow::Exit`](retroglyph_core::app::Flow) the event loop exits gracefully
/// (via [`ActiveEventLoop::exit`]) instead of force-exiting the process, so
/// the stack unwinds normally and `Drop` impls up the call chain (unflushed
/// writes, GPU/surface teardown, app-level RAII) run before the process
/// exits. This works the same on wasm: winit's web backend implements
/// `ActiveEventLoop::exit` by stopping its `requestAnimationFrame`-driven
/// runner rather than leaving it a no-op.
///
/// See [`run_windowed`]'s "Presenting is automatic" section: the app's
/// [`update`](retroglyph_core::app::App::update) implementation no longer needs to call
/// [`Terminal::present`] itself here either, this driver presents automatically after each call,
/// except on [`Flow::Idle`](retroglyph_core::app::Flow::Idle), where the present is skipped entirely
/// and the previous frame stays on screen.
///
/// # Resizing is not automatic
///
/// This driver does not resize the [`Terminal`] itself. On every window resize it pushes
/// [`Event::Resize`] with the new cell dimensions; the app must poll that event and call
/// [`Terminal::resize`] to resize the terminal's own grid buffers.
///
/// # Errors
///
/// Returns [`winit::error::EventLoopError`] if the event loop cannot be
/// created or fails while running.
pub fn run_app<P, A>(
    config: WindowConfig,
    presenter: P,
    app: A,
) -> Result<(), winit::error::EventLoopError>
where
    P: Presenter + 'static,
    A: retroglyph_core::app::App<WindowBackend<P>> + 'static,
{
    run_app_with_proxy(config, presenter, app, |_proxy| {})
}

/// Same as [`run_app`], but also hands `on_proxy` an [`EventProxy`] for injecting cross-thread
/// events.
///
/// See [`run_windowed_with_proxy`] for when/why to use the `_with_proxy` variant over the plain
/// one. The injected payload is always a `u64`, delivered as [`Event::Custom`]; see
/// [`run_app_with_typed_proxy`] for injecting any `T: Send + 'static`.
///
/// See [`run_app`]'s "Presenting is automatic" section: this function shares the same
/// automatic-present behavior.
///
/// # Errors
///
/// Returns [`winit::error::EventLoopError`] if the event loop cannot be
/// created or fails while running.
pub fn run_app_with_proxy<P, A, O>(
    config: WindowConfig,
    presenter: P,
    app: A,
    on_proxy: O,
) -> Result<(), winit::error::EventLoopError>
where
    P: Presenter + 'static,
    A: retroglyph_core::app::App<WindowBackend<P>> + 'static,
    O: FnOnce(EventProxy),
{
    run_app_with_typed_proxy(config, presenter, app, on_proxy, push_custom_event)
}

/// Same as [`run_app_with_proxy`], but the injected payload can be any `T: Send + 'static`
/// instead of a fixed `u64`.
///
/// See [`run_windowed_with_typed_proxy`] for the same generalization on the raw closure-based
/// driver, including why a non-`u64` payload bypasses [`retroglyph_core::event::Event`] entirely
/// and goes straight to `on_custom_event`.
///
/// See [`run_app`]'s "Presenting is automatic" section: this function shares the same
/// automatic-present behavior.
///
/// # Errors
///
/// Returns [`winit::error::EventLoopError`] if the event loop cannot be
/// created or fails while running.
pub fn run_app_with_typed_proxy<T, P, A, O, D>(
    config: WindowConfig,
    presenter: P,
    mut app: A,
    on_proxy: O,
    on_custom_event: D,
) -> Result<(), winit::error::EventLoopError>
where
    T: Send + 'static,
    P: Presenter + 'static,
    A: retroglyph_core::app::App<WindowBackend<P>> + 'static,
    O: FnOnce(EventProxy<T>),
    D: FnMut(T, &mut Terminal<WindowBackend<P>>) + 'static,
{
    let mut frame_count = 0u64;
    let mut last = web_time::Instant::now();
    let exit_requested = Rc::new(Cell::new(false));
    let exit_requested_in_loop = exit_requested.clone();
    let skip_present = Rc::new(Cell::new(false));
    let skip_present_in_loop = skip_present.clone();
    run_windowed_with_typed_proxy_and_exit_flag(
        config,
        presenter,
        move |term| {
            let now = web_time::Instant::now();
            let delta = now.duration_since(last);
            last = now;
            let frame = retroglyph_core::app::Frame {
                delta,
                frame: frame_count,
            };
            frame_count = frame_count.wrapping_add(1);
            match app.update(term, &frame) {
                retroglyph_core::app::Flow::Exit => exit_requested_in_loop.set(true),
                // Nothing changed: tell `handle_redraw_requested` to skip its automatic present
                // for this frame. `Terminal::present` always presents unconditionally, so this
                // flag is the only thing standing between an idle frame and an unwanted redraw.
                retroglyph_core::app::Flow::Idle => skip_present_in_loop.set(true),
                // `Flow` is `#[non_exhaustive]`; any other variant (including `Continue`) presents
                // as usual via `handle_redraw_requested`'s automatic present.
                _ => {}
            }
        },
        on_proxy,
        on_custom_event,
        exit_requested,
        skip_present,
    )
}

/// Initial window dimensions used before the first Resized event.
struct InitWindowSize {
    width: u32,
    height: u32,
}

/// The subset of [`WindowConfig`]'s builder attributes applied once, up front, to
/// `Window::default_attributes()` in [`create_window_and_surface`](WindowApp::create_window_and_surface).
///
/// Grouped into its own type (rather than six more fields directly on [`WindowApp`]) since
/// they're only ever read in that one place, unlike `fill_viewport`, which also gates per-resize
/// behavior elsewhere.
// See `WindowConfig`'s matching `#[allow]` for why these bools are independent toggles, not a
// state machine.
#[allow(clippy::struct_excessive_bools)]
struct WindowAttrs {
    resizable: bool,
    decorations: bool,
    min_size: Option<(u32, u32)>,
    max_size: Option<(u32, u32)>,
    initial_position: Option<(i32, i32)>,
    fullscreen: bool,
    transparency: bool,
}

impl From<&WindowConfig> for WindowAttrs {
    fn from(config: &WindowConfig) -> Self {
        Self {
            resizable: config.resizable,
            decorations: config.decorations,
            min_size: config.min_size,
            max_size: config.max_size,
            initial_position: config.initial_position,
            fullscreen: config.fullscreen,
            transparency: config.transparency,
        }
    }
}

impl Default for WindowAttrs {
    /// Mirrors [`WindowConfig::fit`]'s defaults, for tests that construct a [`WindowApp`]
    /// directly without going through a [`WindowConfig`].
    fn default() -> Self {
        Self {
            resizable: true,
            decorations: true,
            min_size: None,
            max_size: None,
            initial_position: None,
            fullscreen: false,
            transparency: false,
        }
    }
}

/// Bitmask for [`MouseButton::Left`] in [`WindowApp::held_buttons`].
const BUTTON_MASK_LEFT: u8 = 1 << 0;
/// Bitmask for [`MouseButton::Right`] in [`WindowApp::held_buttons`].
const BUTTON_MASK_RIGHT: u8 = 1 << 1;
/// Bitmask for [`MouseButton::Middle`] in [`WindowApp::held_buttons`].
const BUTTON_MASK_MIDDLE: u8 = 1 << 2;

/// Maps a [`MouseButton`] to its bit in [`WindowApp::held_buttons`].
const fn button_mask(button: MouseButton) -> u8 {
    match button {
        MouseButton::Left => BUTTON_MASK_LEFT,
        MouseButton::Right => BUTTON_MASK_RIGHT,
        MouseButton::Middle => BUTTON_MASK_MIDDLE,
        // `MouseButton` is `#[non_exhaustive]`; treat any future variant as unmasked (never
        // drives a `Drag`) rather than failing to compile when one is added upstream.
        _ => 0,
    }
}

/// The winit `ApplicationHandler`: owns the window, the terminal, and the
/// per-frame closure.
///
/// Generic over the injected user-event payload `T` and its delivery handler `D`, so the same
/// type backs both the `u64`/[`Event::Custom`] path ([`run_windowed_with_proxy`]/
/// [`run_app_with_proxy`], where `T = u64` and `D` is [`push_custom_event`]) and the typed-`T`
/// path ([`run_windowed_with_typed_proxy`]/[`run_app_with_typed_proxy`], where `D` is the
/// caller-supplied `on_custom_event`).
struct WindowApp<P: Presenter, F, T, D> {
    terminal: Option<Terminal<WindowBackend<P>>>,
    app_loop: F,
    /// Delivers one injected `T` payload to the app; see [`handle_user_event`](Self::handle_user_event).
    on_custom_event: D,
    /// `T` only ever appears as `D`'s argument, never stored directly: see [`ApplicationHandler`]
    /// for why `WindowApp` still needs to name it (winit dispatches `user_event` generically over
    /// the event-loop's payload type).
    _user_event: PhantomData<fn(T)>,
    window: Option<Arc<Window>>,
    title: String,
    init_size: InitWindowSize,
    /// See [`WindowConfig`]'s `resizable`/`decorations`/`min_size`/`max_size`/
    /// `initial_position`/`fullscreen`/`transparency` fields; applied once at window creation.
    attrs: WindowAttrs,
    /// See [`WindowConfig::fill_viewport`]. Only meaningful on `wasm32`; not
    /// even stored on native, where it would do nothing.
    #[cfg(target_arch = "wasm32")]
    fill_viewport: bool,
    /// Current modifier key state, updated by `ModifiersChanged` events.
    current_modifiers: KeyModifiers,
    /// Last known cursor position in physical pixels.
    cursor_px: (f64, f64),
    /// The finger currently treated as the pointer, if any.
    ///
    /// Touch input (mobile browsers, touchscreens) arrives as
    /// [`WindowEvent::Touch`], not as `CursorMoved`/`MouseInput`. The first
    /// finger down is adopted as "the pointer" and synthesized into the same
    /// left-button mouse events games already handle; other fingers are
    /// ignored until it lifts, so a stray second finger can't teleport the
    /// cursor mid-drag.
    active_touch: Option<u64>,
    /// Bitmask of currently held mouse buttons, built from [`button_mask`]. Updated by
    /// [`on_mouse_input`](Self::on_mouse_input) and consulted by
    /// [`on_cursor_moved`](Self::on_cursor_moved) to decide between [`MouseEventKind::Moved`] and
    /// [`MouseEventKind::Drag`]. A bitmask (rather than tracking only the most recent button)
    /// because more than one button can be held at once, and each needs its own accurate
    /// press/release accounting.
    held_buttons: u8,
    /// Frame-rate cap derived from [`WindowConfig::target_fps`]: `Some(interval)` paces redraws
    /// to no more than one per `interval`, `None` leaves them uncapped. Independent of
    /// [`event_driven`](Self::event_driven); see [`WindowConfig::fit`].
    ///
    /// Stored on `wasm32` too, where only the `Some`/`None` distinction is used: the browser's
    /// `requestAnimationFrame` already paces the loop, so there is no deadline to sleep until.
    frame_interval: Option<Duration>,
    /// Deadline for the next frame when `frame_interval` is set. Native only: `wasm32` has no
    /// sleeping event loop to schedule against.
    #[cfg(not(target_arch = "wasm32"))]
    next_frame: std::time::Instant,
    /// Whether [`about_to_wait`](ApplicationHandler::about_to_wait) gates redraws on
    /// [`needs_redraw`](Self::needs_redraw) (`true`) or always redraws every tick (`false`),
    /// as passed to [`WindowConfig::fit`]. Independent of
    /// [`frame_interval`](Self::frame_interval): this controls *whether* a tick redraws at all,
    /// the frame-rate cap controls *how often* once it does.
    event_driven: bool,
    /// Set by `app_loop` (specifically [`run_app_with_proxy`]'s closure) to request the event
    /// loop stop, instead of calling `std::process::exit` directly.
    ///
    /// `app_loop` is a plain `FnMut(&mut Terminal<..>)` with no return value and no
    /// [`ActiveEventLoop`] handle, so it can't call `event_loop.exit()` itself; it can only flip
    /// this shared flag. [`handle_window_event`](Self::handle_window_event) (which runs
    /// `app_loop` on [`WindowEvent::RedrawRequested`]) also takes no
    /// [`ActiveEventLoop`], so unit tests can drive it without a live winit loop (see its
    /// doc comment). `ApplicationHandler::window_event`, which does have the `ActiveEventLoop`,
    /// checks this flag right after `handle_window_event` returns and calls `event_loop.exit()`
    /// if it's set, letting the stack unwind normally (`Drop` impls run) instead of
    /// force-terminating the process.
    exit_requested: Rc<Cell<bool>>,
    /// Set by `app_loop` (specifically [`run_app_with_proxy`]'s closure) on
    /// [`Flow::Idle`](retroglyph_core::app::Flow::Idle) to tell
    /// [`handle_redraw_requested`](Self::handle_redraw_requested) to skip its automatic present
    /// for this frame. Cleared at the start of every `handle_redraw_requested` call, so it only
    /// ever reflects the outcome of the `app_loop` call about to run.
    ///
    /// A plain `FnMut(&mut Terminal<..>)` closure (`run_windowed`/`run_windowed_with_proxy`) has
    /// no `Flow` concept and never sets this, the same way it never sets `exit_requested`.
    skip_present: Rc<Cell<bool>>,
    /// Set whenever something happened that the app loop should get a chance to react to:
    /// window creation, an input/window event, or an injected [`Event::Custom`]. Cleared once
    /// [`about_to_wait`](ApplicationHandler::about_to_wait) turns it into a `request_redraw()`
    /// call.
    ///
    /// Retro/terminal-style apps are event-driven, not animation-driven, so "nothing happened"
    /// should mean "render nothing new": see this field's use in `about_to_wait` for why that
    /// keeps the loop asleep (`ControlFlow::Wait`) instead of spinning at ~100% CPU redrawing an
    /// unchanged frame forever.
    ///
    /// Only consulted when [`event_driven`](Self::event_driven) is `true`, i.e. redraw-on-demand
    /// mode. An app that animates over time has no event to point at and would freeze under this
    /// gate, which is what `event_driven: false` (continuous mode) is for; see
    /// [`WindowConfig::fit`].
    needs_redraw: bool,
    /// Count of consecutive `present()` failures, reset to 0 on the next success. Drives
    /// [`present_failure_action`]'s logging-verbosity and surface-recovery decisions in the
    /// `RedrawRequested` arm of [`handle_window_event`](Self::handle_window_event).
    consecutive_present_errors: u32,
}

impl<P: Presenter, F, T, D> WindowApp<P, F, T, D> {
    /// Create the window and initialize the surface.
    ///
    /// Returns `Some(window)` on success, logs and returns `None` on failure.
    fn create_window_and_surface(&mut self, event_loop: &ActiveEventLoop) -> Option<Arc<Window>> {
        // On native, size the window to fit the grid (`WindowConfig::fit`)
        // and let the OS window manager own further resizing. On wasm, if
        // `fill_viewport` is set, there's no OS window to fit into (the
        // canvas *is* the page), so size it to the browser viewport
        // instead, for a full-screen, mobile-web-app feel; otherwise it's
        // sized the same as native (`init_size`, the natural grid size),
        // which is what most demos/examples want; see
        // `WindowConfig::fill_viewport`'s doc comment. winit sets an inline
        // `width`/`height` style on the canvas matching whatever size we
        // request here; it does not derive that size from page CSS, so this
        // has to happen in Rust.
        //
        // Crucially, the viewport-filling size *must* be the viewport size
        // at the real (uncapped) device pixel ratio, not the DPR-capped size
        // used for the software backing store below. winit's wasm backend
        // converts whatever `PhysicalSize` we pass here back to a logical
        // (CSS pixel) size using `window.devicePixelRatio()` (the actual,
        // uncapped ratio) to set the canvas's inline `style.width`/
        // `style.height`. Handing it a DPR-capped physical size makes it
        // divide by a *larger* real DPR than the one used to compute that
        // size, so the resulting CSS size comes out smaller than the
        // viewport (the higher the real DPR above the cap, the more the
        // canvas visibly shrinks, on a phone with DPR 3 and our 1.5 cap,
        // that's 50% of the screen). See `web::web_viewport_surface_physical_size`
        // for the separate, capped size used for the raster backing store.
        // On native, `init_size` is already expressed in true physical
        // pixels; `WindowConfig::fit` derives it from
        // `Presenter::cell_size()`, which is documented to return physical
        // (not logical/DPI-scaled) pixels. Requesting that count directly
        // as a `PhysicalSize` is therefore already correct on a HiDPI
        // display; scaling it again by the monitor's `scale_factor` would
        // double the window size (see retroglyph#701).
        #[cfg(not(target_arch = "wasm32"))]
        let physical_size =
            winit::dpi::PhysicalSize::new(self.init_size.width, self.init_size.height);
        #[cfg(target_arch = "wasm32")]
        let physical_size = if self.fill_viewport {
            web::web_viewport_layout_physical_size().unwrap_or_else(|| {
                winit::dpi::PhysicalSize::new(self.init_size.width, self.init_size.height)
            })
        } else {
            winit::dpi::PhysicalSize::new(self.init_size.width, self.init_size.height)
        };
        #[cfg(target_arch = "wasm32")]
        let surface_physical_size = if self.fill_viewport {
            web::web_viewport_surface_physical_size().unwrap_or(physical_size)
        } else {
            physical_size
        };
        #[cfg(not(target_arch = "wasm32"))]
        let surface_physical_size = physical_size;

        let attrs = Window::default_attributes()
            .with_title(&self.title)
            .with_inner_size(physical_size)
            .with_resizable(self.attrs.resizable)
            .with_decorations(self.attrs.decorations)
            .with_transparent(self.attrs.transparency);
        let attrs = match self.attrs.min_size {
            Some((w, h)) => attrs.with_min_inner_size(winit::dpi::PhysicalSize::new(w, h)),
            None => attrs,
        };
        let attrs = match self.attrs.max_size {
            Some((w, h)) => attrs.with_max_inner_size(winit::dpi::PhysicalSize::new(w, h)),
            None => attrs,
        };
        let attrs = match self.attrs.initial_position {
            Some((x, y)) => attrs.with_position(winit::dpi::PhysicalPosition::new(x, y)),
            None => attrs,
        };
        let attrs = if self.attrs.fullscreen {
            attrs.with_fullscreen(Some(winit::window::Fullscreen::Borderless(None)))
        } else {
            attrs
        };

        #[cfg(target_family = "wasm")]
        let attrs = {
            use winit::platform::web::WindowAttributesExtWebSys;
            attrs.with_append(true)
        };

        let window = Arc::new(match event_loop.create_window(attrs) {
            Ok(w) => w,
            Err(e) => {
                log::error!("window creation failed: {e}");
                event_loop.exit();
                return None;
            }
        });

        // IME composition (`WindowEvent::Ime`) is opt-in per winit's own doc comment on that
        // variant: without this, platform input methods (Pinyin, Kana, dead-key accents, ...)
        // never surface composed text at all, silently limiting windowed-app text input to
        // whatever a bare `KeyboardInput` logical key can express. See `translate::translate_ime`
        // for how a committed composition is turned into an `Event`.
        window.set_ime_allowed(true);

        if let Some(term) = self.terminal.as_mut() {
            // Hand the presenter a windowing-library-agnostic handle (see
            // `Presenter::init_surface`); the winit window stays owned here.
            let handle: Arc<dyn crate::presenter::WindowHandle> = window.clone();
            if let Err(e) = term.backend_mut().presenter_mut().init_surface(handle) {
                log::error!("surface init failed: {e}");
                event_loop.exit();
                return None;
            }
            // Set the initial surface size (required on WASM before first present), using
            // `surface_physical_size`, not `physical_size`: the
            // raster backing store stays DPR-capped for present() cost even
            // though the canvas's CSS size (driven by `physical_size` via
            // winit above) matches the full, uncapped viewport.
            term.backend_mut()
                .presenter_mut()
                .resize_surface(surface_physical_size.width, surface_physical_size.height);
        }

        // Keep the canvas matching the browser viewport as it changes
        // (device rotation, browser window resize, address-bar
        // show/hide): winit only reacts to size changes we ask for
        // ourselves (`request_inner_size`), so a `resize` listener is
        // required to make this genuinely responsive rather than a
        // one-shot fit at startup. Only installed when `fill_viewport` is
        // set, otherwise the canvas should stay at its natural grid size
        // regardless of viewport changes.
        #[cfg(target_arch = "wasm32")]
        if self.fill_viewport {
            web::install_viewport_resize_listener(&window);
        }

        // `WindowEvent::ThemeChanged` (handled in `handle_window_event`)
        // only fires on a *change*, so an app that never sees a system
        // theme change would otherwise never learn the starting one.
        // `Window::theme()` reflects the current system theme both on
        // native and on winit's web target (backed by the
        // `prefers-color-scheme` media query there), so query it once
        // up-front and synthesize the same event a live change would send.
        if let Some(theme) = window.theme()
            && let Some(term) = self.terminal.as_mut()
        {
            term.backend_mut().push_event(system_theme_event(theme));
        }

        Some(window)
    }
}

/// Number of consecutive `present()` failures after which
/// [`handle_window_event`](WindowApp::handle_window_event)'s `RedrawRequested` arm attempts to
/// recover by re-initializing the surface (see [`PresentFailureAction::Recover`]).
///
/// Roughly half a second at 60 FPS: long enough that a single dropped frame (a transient `VSync`
/// hiccup, a momentarily occluded window) never triggers a surface rebuild, but short enough that
/// a genuinely broken surface (context loss, invalidated swapchain) doesn't sit unrecovered for
/// many seconds.
const PRESENT_FAILURE_RECOVERY_THRESHOLD: u32 = 30;

/// What [`handle_window_event`](WindowApp::handle_window_event)'s `RedrawRequested` arm should do
/// in response to the outcome of one `present()` call, given the running count of consecutive
/// failures *before* this call.
///
/// [`Presenter::SurfaceError`] is a generic associated type: the software backend's
/// `SurfaceError` just wraps `softbuffer::SoftBufferError`, a plain `#[non_exhaustive]` enum with
/// no `Lost`/`Outdated`/`Timeout` discrimination the way `wgpu::SurfaceError` has, so most
/// backends can't pattern-match on *why* a present failed to decide whether it's recoverable the
/// way a wgpu-based app would. All they can generally observe is a bare `Display`able error and
/// whether the failure is a one-off or persistent (via the consecutive-failure count), so the
/// recovery strategy here is generic for that case: rate-limit logging so a
/// persistent failure doesn't spam every frame, and after a run of failures long enough to rule
/// out a one-off glitch, attempt the one backend-agnostic recovery available: re-running
/// [`Presenter::init_surface`] to rebuild the surface from scratch, the same call
/// [`create_window_and_surface`](WindowApp::create_window_and_surface) makes at startup.
///
/// [`RecoverableError::is_recoverable`](crate::presenter::RecoverableError::is_recoverable) is
/// the escape hatch for a presenter that *can* categorize its errors: when a failed `present()`
/// reports `is_recoverable() == false`, that decision table is skipped entirely in favor of
/// [`PresentFailureAction::Fatal`]: retrying a failure the presenter itself already knows is
/// unrecoverable can't help, so there's no reason to wait out the consecutive-failure threshold
/// first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PresentFailureAction {
    /// Presenting succeeded; if `was_failing` is `true` the caller should log recovery at `info`
    /// or `warn` level (a prior failure streak just ended).
    Ok { was_failing: bool },
    /// Presenting failed; log at `error!` (first failure in a streak, or the very first ever)
    /// or suppress (a already-logged, ongoing streak below the recovery threshold).
    Log { at_error_level: bool },
    /// Presenting failed and the consecutive-failure count just crossed the recovery threshold:
    /// log at `warn!` and attempt to reinitialize the surface.
    Recover,
    /// Presenting failed with an error the presenter reports as unrecoverable (see
    /// [`RecoverableError::is_recoverable`](crate::presenter::RecoverableError::is_recoverable)):
    /// log at `error!` immediately and skip the consecutive-failure/recovery bookkeeping
    /// entirely: rebuilding the surface via [`Presenter::init_surface`] cannot help a failure
    /// already classified as fatal.
    Fatal,
}

/// Decides the action for one `present()` outcome, given `consecutive_failures` *before* this
/// call (0 if the previous call succeeded or this is the first call) and, for a failed call,
/// whether the presenter reports the error as recoverable (see
/// [`RecoverableError::is_recoverable`](crate::presenter::RecoverableError::is_recoverable);
/// ignored when `succeeded` is `true`).
///
/// Pure decision table, kept separate from the live `RedrawRequested` handling (which needs a
/// real `Terminal`/`Presenter`/`Window`) so the threshold and logging-level logic is unit
/// -testable without any of those, the same reasoning as [`web::dpr_pointer_scale`] above.
const fn present_failure_action(
    consecutive_failures: u32,
    succeeded: bool,
    recoverable: bool,
) -> PresentFailureAction {
    if succeeded {
        return PresentFailureAction::Ok {
            was_failing: consecutive_failures > 0,
        };
    }
    if !recoverable {
        return PresentFailureAction::Fatal;
    }
    // `consecutive_failures` is the count *before* this failure, so the count *including* this
    // one is `consecutive_failures + 1`; recover exactly when that reaches the threshold, and
    // again every full threshold-worth of failures after that (so a failed recovery attempt
    // doesn't get retried on literally the next frame, hot-looping surface rebuilds).
    if (consecutive_failures + 1).is_multiple_of(PRESENT_FAILURE_RECOVERY_THRESHOLD) {
        return PresentFailureAction::Recover;
    }
    PresentFailureAction::Log {
        at_error_level: consecutive_failures == 0,
    }
}

/// Continuous mode's next-frame decision on native: `None` while `now` is still short of
/// `next_frame` (the caller parks the loop on `ControlFlow::WaitUntil(next_frame)`), or
/// `Some(advanced)` once the deadline has passed, where `advanced` is the deadline for the frame
/// after this one.
///
/// `advanced` is `next_frame + interval` clamped to `now`, so a frame that overran its budget (a
/// stalled GPU, a descheduled thread) resumes from the present rather than firing a burst of
/// catch-up renders to "make up" the lost time: there is nothing to make up when every frame
/// renders the current state.
///
/// Pure function of the two instants and the interval, kept separate from the live `about_to_wait`
/// handling (which needs an [`ActiveEventLoop`] no unit test can construct) for the same reason as
/// [`present_failure_action`] above. `wasm32` has no sleeping event loop
/// to schedule against and never calls this; see `about_to_wait`.
#[cfg(not(target_arch = "wasm32"))]
fn next_frame_deadline(
    now: std::time::Instant,
    next_frame: std::time::Instant,
    interval: Duration,
) -> Option<std::time::Instant> {
    if next_frame > now {
        return None;
    }
    Some((next_frame + interval).max(now))
}

/// Maps winit's [`Theme`](winit::window::Theme) to the backend-agnostic
/// [`Event::ThemeChanged`], the only place that conversion needs to happen.
const fn system_theme_event(theme: winit::window::Theme) -> Event {
    use retroglyph_core::event::SystemTheme;
    match theme {
        winit::window::Theme::Light => Event::ThemeChanged(SystemTheme::Light),
        winit::window::Theme::Dark => Event::ThemeChanged(SystemTheme::Dark),
    }
}

impl<P, F, T, D> ApplicationHandler<T> for WindowApp<P, F, T, D>
where
    P: Presenter,
    F: FnMut(&mut Terminal<WindowBackend<P>>) + 'static,
    T: 'static,
    D: FnMut(T, &mut Terminal<WindowBackend<P>>) + 'static,
{
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if let Some(window) = self.create_window_and_surface(event_loop) {
            self.window = Some(window);
        }
        // First frame: nothing has "happened" yet in the input-event sense, but the app still
        // needs an initial render once the window/surface exists.
        self.needs_redraw = true;
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        _window_id: WindowId,
        event: WindowEvent,
    ) {
        self.handle_window_event(event);
        // `app_loop` (run on `RedrawRequested`, inside `handle_window_event`) can only signal
        // exit by setting `exit_requested`; see its doc comment for why. Check it here, where
        // an `ActiveEventLoop` is actually available, and ask winit to exit gracefully instead of
        // the caller force-exiting the process.
        if self.exit_requested.get() {
            event_loop.exit();
        }
    }

    fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: T) {
        self.handle_user_event(event);
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        // `event_driven` (redraw-on-demand): only proceed if something actually happened since
        // the last redraw. Otherwise park the loop at `ControlFlow::Wait` so it sleeps instead of
        // spinning at ~100% CPU re-rendering an unchanged frame every iteration -- retro/terminal-
        // style apps are idle most of the time and event-driven, so "nothing happened" should mean
        // "render nothing new". The reset must be explicit: winit's `ControlFlow` is sticky (a
        // `Cell` that persists across iterations; "Defaults to `Wait`" describes only the value
        // before the loop's first iteration, not a per-iteration reset), so once the paced branch
        // below has parked it at a `WaitUntil` deadline, that deadline stays live -- once it
        // elapses with `ControlFlow` never reset, the loop wakes again immediately, every
        // iteration, forever. See `needs_redraw`'s doc comment. Not `event_driven` (continuous):
        // always proceed, regardless of `needs_redraw`: an app driving a tween off `Frame::delta`
        // has something new to show every tick even though no input event arrived, which is
        // precisely what the `needs_redraw` gate cannot express.
        if self.event_driven && !self.needs_redraw {
            event_loop.set_control_flow(winit::event_loop::ControlFlow::Wait);
            return;
        }

        let Some(interval) = self.frame_interval else {
            // Uncapped: render every tick this point is reached.
            self.needs_redraw = false;
            self.request_redraw();
            return;
        };

        // Capped: pace to `interval`. The two platforms do that differently. Native sleeps until
        // the deadline and then renders, since `request_redraw` is serviced within the same loop
        // iteration. On `wasm32` there is nothing to sleep in: winit's web backend services
        // `request_redraw` on the browser's next `requestAnimationFrame`, roughly one display
        // frame later, so sleeping out a full interval *before* asking would pay that latency on
        // top of it and halve the achieved frame rate. Ask on every iteration instead and let
        // `requestAnimationFrame` do the pacing, which is also what the browser wants, since it
        // already throttles background tabs and matches the compositor's cadence.
        #[cfg(not(target_arch = "wasm32"))]
        match next_frame_deadline(std::time::Instant::now(), self.next_frame, interval) {
            None => {
                event_loop
                    .set_control_flow(winit::event_loop::ControlFlow::WaitUntil(self.next_frame));
                return;
            }
            Some(advanced) => self.next_frame = advanced,
        }
        #[cfg(target_arch = "wasm32")]
        let _ = interval;
        self.needs_redraw = false;
        self.request_redraw();
    }
}

impl<P, F, T, D> WindowApp<P, F, T, D>
where
    P: Presenter,
    F: FnMut(&mut Terminal<WindowBackend<P>>) + 'static,
    D: FnMut(T, &mut Terminal<WindowBackend<P>>) + 'static,
{
    /// Ask winit for a `RedrawRequested`, if the window exists yet.
    ///
    /// Both [`about_to_wait`](ApplicationHandler::about_to_wait) branches end here; the window is
    /// `None` only before `resumed` has run.
    fn request_redraw(&self) {
        if let Some(window) = &self.window {
            window.request_redraw();
        }
    }

    /// Drain one injected user event into `on_custom_event`.
    ///
    /// Extracted from the `ApplicationHandler::user_event` impl for the same reason as
    /// [`handle_window_event`](Self::handle_window_event): so the drain logic can be exercised in
    /// unit tests without a live [`ActiveEventLoop`]. There is only ever one event to drain per
    /// call (winit calls `user_event` once per [`EventProxy::send_event`]), so "drain" here
    /// means "push the one event this call carries", not draining a whole queue at once. For the
    /// `u64`/[`Event::Custom`] path, `on_custom_event` is [`push_custom_event`]; for a typed `T`,
    /// it's the caller-supplied `on_custom_event` handler passed to
    /// [`run_windowed_with_typed_proxy`]/[`run_app_with_typed_proxy`].
    fn handle_user_event(&mut self, event: T) {
        if let Some(term) = self.terminal.as_mut() {
            (self.on_custom_event)(event, term);
        }
        self.needs_redraw = true;
    }

    /// Dispatch a [`WindowEvent`] without requiring an [`ActiveEventLoop`].
    ///
    /// Extracted from the `ApplicationHandler` impl so the translation and
    /// event-buffer logic can be called directly in unit tests, where
    /// [`ActiveEventLoop`] is not constructable.
    fn handle_window_event(&mut self, event: WindowEvent) {
        // Every branch below (other than `RedrawRequested`, which *is* the render this flag
        // exists to gate) represents something the app loop should get a chance to react to on
        // the next frame; see `needs_redraw`'s doc comment for why that matters for idle CPU.
        // Set unconditionally up front rather than per-arm: simpler, and the only event that must
        // *not* set it (`RedrawRequested`) already clears it again in `about_to_wait` right before
        // requesting this same redraw, so a same-tick `RedrawRequested` can't retrigger itself.
        if !matches!(event, WindowEvent::RedrawRequested) {
            self.needs_redraw = true;
        }
        match event {
            WindowEvent::CloseRequested => {
                // Push the event so the game loop can process it (save game,
                // confirm dialog, etc.).  Do not call event_loop.exit() here;
                // the game decides when to terminate.
                if let Some(term) = self.terminal.as_mut() {
                    term.backend_mut().push_event(Event::Close);
                }
            }
            WindowEvent::Resized(size) => self.on_resized(size),
            WindowEvent::CursorMoved { position, .. } => self.on_cursor_moved(position),
            WindowEvent::MouseInput { state, button, .. } => self.on_mouse_input(state, button),
            WindowEvent::MouseWheel { delta, .. } => self.on_mouse_wheel(delta),
            WindowEvent::Touch(touch) => self.on_touch(touch),
            WindowEvent::ModifiersChanged(mods) => {
                self.current_modifiers = translate_modifiers(mods.state());
            }
            WindowEvent::ThemeChanged(theme) => {
                if let Some(term) = self.terminal.as_mut() {
                    term.backend_mut().push_event(system_theme_event(theme));
                }
            }
            WindowEvent::Focused(gained) => self.on_focus_changed(gained),
            WindowEvent::KeyboardInput { event, .. } => {
                if let Some(term) = self.terminal.as_mut()
                    && let Some(e) = translate_key(event, self.current_modifiers)
                {
                    term.backend_mut().push_event(e);
                }
            }
            WindowEvent::Ime(ime) => {
                if let Some(term) = self.terminal.as_mut()
                    && let Some(e) = translate_ime(ime)
                {
                    term.backend_mut().push_event(e);
                }
            }
            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                self.on_scale_factor_changed(scale_factor);
            }

            WindowEvent::RedrawRequested => self.handle_redraw_requested(),

            _ => {}
        }
    }

    /// Runs the app closure, automatically presents the `Terminal` if the app didn't already (and
    /// didn't return [`Flow::Idle`](retroglyph_core::app::Flow::Idle)), and presents the frame to the
    /// surface, tracking consecutive `present()` failures to rate-limit logging and trigger
    /// surface recovery.
    ///
    /// See [`present_failure_action`] for the decision table; this method just runs the `Terminal`
    /// -/`Presenter`-dependent side effects (`app_loop`, `present`, `init_surface`, logging) that
    /// function can't perform itself since it's a pure function of the failure count alone.
    ///
    /// # Automatic `Terminal::present`
    ///
    /// Windowed apps no longer need to call [`Terminal::present`] themselves: this method calls it
    /// once, right after `app_loop` returns, unless [`skip_present`](Self::skip_present) was set
    /// (an [`App`](retroglyph_core::app::App) returned `Flow::Idle`) or
    /// [`Terminal::present_count`] shows `app_loop` already called it. A [`Terminal::present`]
    /// error is logged and does not stop the surface-level present below from running (matching
    /// this function's existing keep-going-on-failure philosophy); it uses a different error type
    /// (`<B as Output>::Error`) than [`Presenter::SurfaceError`], so it is tracked and logged
    /// independently of the consecutive-failure counter below, which is scoped to the surface
    /// present.
    fn handle_redraw_requested(&mut self) {
        let Some(term) = self.terminal.as_mut() else {
            return;
        };
        self.skip_present.set(false);
        let present_count_before = term.present_count();
        (self.app_loop)(term);
        if !self.skip_present.get()
            && term.present_count() == present_count_before
            && let Err(e) = term.present()
        {
            log::error!("automatic terminal present failed: {e}");
        }
        let result = term.backend_mut().presenter_mut().present();
        let succeeded = result.is_ok();
        let recoverable = result
            .as_ref()
            .err()
            .is_none_or(crate::presenter::RecoverableError::is_recoverable);
        match present_failure_action(self.consecutive_present_errors, succeeded, recoverable) {
            PresentFailureAction::Ok { was_failing } => {
                if was_failing {
                    log::info!(
                        "frame present recovered after {} consecutive failures",
                        self.consecutive_present_errors
                    );
                }
                self.consecutive_present_errors = 0;
            }
            PresentFailureAction::Log { at_error_level } => {
                self.consecutive_present_errors += 1;
                let e = result.unwrap_err();
                if at_error_level {
                    log::error!("frame present failed: {e}");
                } else {
                    // Ongoing failure streak below the recovery threshold: already logged at
                    // `error!` when the streak started, so avoid re-logging every single frame
                    // (the log-spam this issue exists to fix) while still keeping the detail
                    // available at `debug!` for anyone investigating a live failure.
                    log::debug!("frame present still failing: {e}");
                }
            }
            PresentFailureAction::Recover => {
                self.consecutive_present_errors += 1;
                let e = result.unwrap_err();
                log::warn!(
                    "frame present failed {} times consecutively ({e}); attempting surface recovery",
                    self.consecutive_present_errors
                );
                self.try_recover_surface();
            }
            PresentFailureAction::Fatal => {
                self.consecutive_present_errors += 1;
                let e = result.unwrap_err();
                log::error!("frame present failed with an unrecoverable error: {e}");
            }
        }
    }

    /// Attempts to recover from a persistent `present()` failure by re-running
    /// [`Presenter::init_surface`], the same call
    /// [`create_window_and_surface`](Self::create_window_and_surface) makes at startup.
    ///
    /// This is the only recovery available generically: [`Presenter::SurfaceError`] carries no
    /// structured "is this recoverable" signal (see [`present_failure_action`]'s doc comment), so
    /// rebuilding the surface from scratch is the one action that's meaningful across every
    /// backend. A no-op if there is no window to rebuild the surface from (headless/pre-`resumed`
    /// states), or if the terminal has already been torn down.
    fn try_recover_surface(&mut self) {
        let Some(window) = self.window.clone() else {
            return;
        };
        let Some(term) = self.terminal.as_mut() else {
            return;
        };
        let handle: Arc<dyn crate::presenter::WindowHandle> = window;
        if let Err(e) = term.backend_mut().presenter_mut().init_surface(handle) {
            log::error!("surface recovery failed: {e}");
        }
    }

    fn on_resized(&mut self, size: winit::dpi::PhysicalSize<u32>) {
        // On wasm with `fill_viewport` set, `size` is whatever (uncapped)
        // physical size we last handed winit for CSS layout purposes, not
        // the backing store size. Recompute the DPR-capped surface size
        // independently so the raster buffer doesn't silently lose its cap
        // on every resize. Without `fill_viewport`, the canvas never resizes
        // on its own (no listener installed above), so `size` here is
        // already the natural grid size and needs no such override.
        #[cfg(target_arch = "wasm32")]
        let size = if self.fill_viewport {
            web::web_viewport_surface_physical_size().unwrap_or(size)
        } else {
            size
        };
        self.resize_to(size);
    }

    /// React to a scale-factor (DPI) change: notify the presenter, then
    /// realign the surface and grid to the window's new physical size.
    ///
    /// Every modern `HiDPI` display is scaled, so without this the surface
    /// silently keeps rendering at the old (pre-change) physical size --
    /// e.g. half the true resolution after moving to a 2x-scale display --
    /// until (if ever) an independent `Resized` event happens to arrive.
    /// Reusing [`resize_to`](Self::resize_to) here mirrors
    /// [`on_resized`](Self::on_resized), so both paths clamp/align the
    /// surface to whole cells the same way.
    fn on_scale_factor_changed(&mut self, scale_factor: f64) {
        if let Some(term) = self.terminal.as_mut() {
            term.backend_mut()
                .presenter_mut()
                .scale_factor_changed(scale_factor);
        }
        let Some(window) = self.window.clone() else {
            return;
        };
        self.resize_to(window.inner_size());
    }

    /// Recompute the grid size (in cells) from a physical pixel size, resize
    /// the presenter's surface to the whole-cell-aligned pixel size, update
    /// the backend's own reported [`Output::size`], and push [`Event::Resize`] with the new
    /// cell dimensions.
    ///
    /// This keeps `backend.size()` in sync with the surface immediately, but it does not
    /// resize the [`Terminal`]'s own grid buffers: that stays the app's responsibility,
    /// done by calling [`Terminal::resize`] in response to the pushed [`Event::Resize`].
    ///
    /// Shared by [`on_resized`](Self::on_resized) and
    /// [`on_scale_factor_changed`](Self::on_scale_factor_changed): both need
    /// the same clamp-to-cell-grid math, just triggered by different winit
    /// events.
    fn resize_to(&mut self, size: winit::dpi::PhysicalSize<u32>) {
        let Some(term) = self.terminal.as_mut() else {
            return;
        };
        let (cell_w, cell_h) = term.backend().presenter().cell_size();
        // Clamp to at least one cell: a window smaller than one cell in
        // either dimension would otherwise divide down to 0 cols/rows,
        // which in turn asks `resize_surface` for a zero-size surface --
        // softbuffer (and likely other presenters) can't handle that and
        // panics. `Event::Resize` must report the same clamped grid the
        // surface was actually sized to, or callers reading `Event::Resize`
        // and querying the presenter's surface size would disagree.
        //
        // Integer division here also truncates any sub-cell remainder: when
        // `size` isn't an exact multiple of the cell size, `cols`/`rows`
        // round down and the surface below is sized to exactly
        // `cols * cell_w` x `rows * cell_h`, which can be smaller than
        // `size` itself. The OS window stays at the full physical `size`
        // the window manager gave it (retroglyph never resizes the OS
        // window to match), so a non-exact-multiple resize leaves a thin
        // strip at the window's trailing (right/bottom) edge outside the
        // surface entirely. That strip is not cleared or painted by
        // retroglyph; whatever the OS/windowing backend leaves there (old
        // frame content, backdrop color) shows through until the window is
        // resized again to a size the presenter does cover. See
        // `Presenter::resize_surface` for the documented contract.
        let cols = (size.width / cell_w).max(1);
        let rows = (size.height / cell_h).max(1);
        term.backend_mut()
            .presenter_mut()
            .resize_surface(cols * cell_w, rows * cell_h);
        #[allow(clippy::cast_possible_truncation)]
        let (cols, rows) = (cols as u16, rows as u16);
        // Update the backend's own reported size immediately so `backend.size()` agrees with
        // the surface without waiting for the app to react to `Event::Resize` below. This does
        // not touch the `Terminal`'s grid content (see `Terminal::resize`, which additionally
        // resizes/clears both grids): that remains the app's job in response to the event.
        term.backend_mut()
            .resize(retroglyph_core::grid::Size::new(cols, rows));
        term.backend_mut().push_event(Event::Resize(cols, rows));
    }

    fn on_cursor_moved(&mut self, position: winit::dpi::PhysicalPosition<f64>) {
        // winit always reports pointer positions in real-DPR physical
        // pixels; rescale to the (possibly DPR-capped, on wasm) backing-store
        // pixel space that `Presenter::geometry`/`pixel_to_cell` use, so taps land on
        // the cell actually under the finger/cursor instead of drifting
        // south-east of it as the real DPR grows past the cap. `1.0` on
        // native (no such cap exists there) *and* on wasm when
        // `fill_viewport` is off: `create_window_and_surface` only computes
        // a DPR-capped `surface_physical_size` when `fill_viewport` is set
        // (see its branch above); without it, the backing store already
        // matches the real, uncapped DPR 1:1, so applying the cap
        // correction anyway scales every reported position *down* toward
        // the origin for no reason, biasing every tap/click up-and-left of
        // where it actually landed on any real_dpr > 1.5 device (most
        // phones, and Retina/HiDPI desktops).
        #[cfg(target_arch = "wasm32")]
        let scale = if self.fill_viewport {
            web::wasm_pointer_scale()
        } else {
            1.0
        };
        #[cfg(not(target_arch = "wasm32"))]
        let scale = 1.0;
        let (x, y) = (position.x * scale, position.y * scale);
        self.cursor_px = (x, y);
        let px = translate_physical_pos(x, y);
        let Some(term) = self.terminal.as_mut() else {
            return;
        };
        let pos = term.backend().presenter().geometry().pixel_to_cell(x, y);
        // Report a drag (rather than a plain move) while any button is held. Left takes
        // priority over Right over Middle when more than one is held at once: an arbitrary but
        // deterministic choice, matching the order the buttons are declared in `MouseButton`.
        let kind = if self.held_buttons & BUTTON_MASK_LEFT != 0 {
            MouseEventKind::Drag(MouseButton::Left)
        } else if self.held_buttons & BUTTON_MASK_RIGHT != 0 {
            MouseEventKind::Drag(MouseButton::Right)
        } else if self.held_buttons & BUTTON_MASK_MIDDLE != 0 {
            MouseEventKind::Drag(MouseButton::Middle)
        } else {
            MouseEventKind::Moved
        };
        term.backend_mut()
            .push_event(Event::Mouse(MouseEvent::with_pixel_position(
                kind,
                pos,
                self.current_modifiers,
                px,
            )));
    }

    fn on_mouse_input(
        &mut self,
        state: winit::event::ElementState,
        button: winit::event::MouseButton,
    ) {
        let Some(btn) = translate_mouse_button(button) else {
            return;
        };
        let px = self.cursor_physical_pos();
        let Some(term) = self.terminal.as_mut() else {
            return;
        };
        let pos = term
            .backend()
            .presenter()
            .geometry()
            .pixel_to_cell(self.cursor_px.0, self.cursor_px.1);
        let kind = if state.is_pressed() {
            self.held_buttons |= button_mask(btn);
            MouseEventKind::Down(btn)
        } else {
            self.held_buttons &= !button_mask(btn);
            MouseEventKind::Up(btn)
        };
        term.backend_mut()
            .push_event(Event::Mouse(MouseEvent::with_pixel_position(
                kind,
                pos,
                self.current_modifiers,
                px,
            )));
    }

    fn on_mouse_wheel(&mut self, delta: winit::event::MouseScrollDelta) {
        let px = self.cursor_physical_pos();
        let Some(term) = self.terminal.as_mut() else {
            return;
        };
        let pos = term
            .backend()
            .presenter()
            .geometry()
            .pixel_to_cell(self.cursor_px.0, self.cursor_px.1);
        let (scroll_x, scroll_y) = match delta {
            winit::event::MouseScrollDelta::LineDelta(x, y) => (f64::from(x), f64::from(y)),
            winit::event::MouseScrollDelta::PixelDelta(p) => (p.x, p.y),
        };
        // A delta of exactly zero on both axes emits nothing (retroglyph#293's original
        // reasoning for not synthesizing a spurious event still applies).
        if scroll_x == 0.0 && scroll_y == 0.0 {
            return;
        }
        #[allow(clippy::cast_possible_truncation)]
        let kind = MouseEventKind::Scroll {
            dx: scroll_x as f32,
            dy: scroll_y as f32,
        };
        term.backend_mut()
            .push_event(Event::Mouse(MouseEvent::with_pixel_position(
                kind,
                pos,
                self.current_modifiers,
                px,
            )));
    }

    /// Synthesize mouse events from a touch so tap/drag work out of the box.
    ///
    /// Mobile browsers (and native touchscreens) deliver touch input as
    /// [`WindowEvent::Touch`], which has no `CursorMoved`/`MouseInput`
    /// counterpart. Games shouldn't need a second input path for it, so the
    /// first finger down becomes the pointer: its start is a `Moved` +
    /// left-button `Down`, its motion is `Moved` (a drag), and its lift is
    /// `Up`. Additional simultaneous fingers are ignored.
    fn on_touch(&mut self, touch: winit::event::Touch) {
        use winit::event::TouchPhase;

        match touch.phase {
            TouchPhase::Started => {
                if self.active_touch.is_some() {
                    return; // a second finger; keep tracking the first
                }
                self.active_touch = Some(touch.id);
                self.on_cursor_moved(touch.location);
                self.on_mouse_input(
                    winit::event::ElementState::Pressed,
                    winit::event::MouseButton::Left,
                );
            }
            TouchPhase::Moved => {
                if self.active_touch == Some(touch.id) {
                    self.on_cursor_moved(touch.location);
                }
            }
            TouchPhase::Ended | TouchPhase::Cancelled => {
                if self.active_touch != Some(touch.id) {
                    return;
                }
                self.active_touch = None;
                self.on_cursor_moved(touch.location);
                self.on_mouse_input(
                    winit::event::ElementState::Released,
                    winit::event::MouseButton::Left,
                );
            }
        }
    }

    /// Convert the cached cursor pixel position to [`PhysicalPos`].
    const fn cursor_physical_pos(&self) -> PhysicalPos {
        translate_physical_pos(self.cursor_px.0, self.cursor_px.1)
    }

    /// Push [`Event::FocusGained`]/[`Event::FocusLost`], and on loss, reset state that only makes
    /// sense while the window is focused.
    ///
    /// Winit keeps delivering `ModifiersChanged` only while focused, so a modifier key held down
    /// when focus is lost (e.g. alt-tabbing away while holding Shift) never generates the release
    /// that would normally clear it: without this, `current_modifiers` stays stuck "held" for
    /// every event after focus returns. Similarly, a finger lifted while the window is
    /// unfocused/backgrounded never delivers `TouchPhase::Ended`/`Cancelled`, so `active_touch`
    /// would otherwise stay set forever, permanently ignoring the next finger down. The stuck
    /// touch is released the same way a real lift is (see [`on_touch`](Self::on_touch)'s
    /// `Ended`/`Cancelled` arm): a left-button `Up` at the last known cursor position, so the app
    /// sees a normal, balanced Down/Up pair instead of a Down with no matching Up. No `Moved` is
    /// synthesized first, unlike a real lift: blur carries no new pointer location, and
    /// `cursor_px` already holds the touch's last reported position from the `Started`/`Moved`
    /// arms that got it there.
    ///
    /// The same problem applies to `held_buttons`: a mouse button released while the window is
    /// unfocused never delivers `MouseInput`, so without this it would stay marked "held" and
    /// every move after refocus would keep reporting a stale `Drag` instead of `Moved`. It's
    /// force-cleared directly (not via a synthesized `Up`, since there's no single button, or
    /// combination of buttons, that unambiguously round-trips through `on_mouse_input`).
    fn on_focus_changed(&mut self, gained: bool) {
        if let Some(term) = self.terminal.as_mut() {
            let event = if gained {
                Event::FocusGained
            } else {
                Event::FocusLost
            };
            term.backend_mut().push_event(event);
        }
        if !gained {
            self.current_modifiers = KeyModifiers::NONE;
            if self.active_touch.take().is_some() {
                self.on_mouse_input(
                    winit::event::ElementState::Released,
                    winit::event::MouseButton::Left,
                );
            }
            self.held_buttons = 0;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use retroglyph_core::backend::DrawCell;
    use retroglyph_core::backend::Output;
    use retroglyph_core::event::{MouseButton, MouseEvent, MouseEventKind};
    use retroglyph_core::grid::{Pos, Size};
    use std::cell::RefCell;
    use std::time::Duration;

    // ── WindowConfig builder chain ───────────────────────────────────────────

    #[test]
    fn fit_defaults_match_winit_defaults() {
        // `fit` should start from the same defaults winit itself uses for a plain
        // `Window::default_attributes()`, so a caller that never touches the new builder
        // methods gets identical behavior to before this API existed.
        let presenter = MockPresenter::default();
        let config = WindowConfig::fit(&presenter, "test", None, true);
        assert!(config.resizable);
        assert!(config.decorations);
        assert_eq!(config.min_size, None);
        assert_eq!(config.max_size, None);
        assert_eq!(config.initial_position, None);
        assert!(!config.fullscreen);
        assert!(!config.transparency);
        assert!(!config.fill_viewport);
    }

    #[test]
    fn fit_width_height_are_physical_pixels_not_rescaled() {
        // Regression test for retroglyph#701: `Presenter::cell_size()` is documented as
        // physical pixels, so `fit()`'s width/height must be exactly `grid * cell_size`,
        // with nothing scaling that by a monitor's DPI factor before it reaches
        // `WindowApp::init_size` and, from there, `create_window_and_surface`.
        let mut presenter = MockPresenter::default();
        presenter.resize(Size::new(80, 25));
        let config = WindowConfig::fit(&presenter, "test", None, true);
        assert_eq!(config.width, 80 * 8);
        assert_eq!(config.height, 25 * 16);
    }

    #[test]
    fn builder_chain_sets_each_attribute() {
        let presenter = MockPresenter::default();
        let config = WindowConfig::fit(&presenter, "test", None, true)
            .resizable(false)
            .decorations(false)
            .min_size(320, 240)
            .max_size(1920, 1080)
            .initial_position(10, 20)
            .fullscreen(true)
            .transparency(true);
        assert!(!config.resizable);
        assert!(!config.decorations);
        assert_eq!(config.min_size, Some((320, 240)));
        assert_eq!(config.max_size, Some((1920, 1080)));
        assert_eq!(config.initial_position, Some((10, 20)));
        assert!(config.fullscreen);
        assert!(config.transparency);
    }

    #[test]
    fn window_attrs_from_config_copies_all_fields() {
        let presenter = MockPresenter::default();
        let config = WindowConfig::fit(&presenter, "test", None, true)
            .resizable(false)
            .decorations(false)
            .min_size(1, 2)
            .max_size(3, 4)
            .initial_position(5, 6)
            .fullscreen(true)
            .transparency(true);
        let attrs = WindowAttrs::from(&config);
        assert!(!attrs.resizable);
        assert!(!attrs.decorations);
        assert_eq!(attrs.min_size, Some((1, 2)));
        assert_eq!(attrs.max_size, Some((3, 4)));
        assert_eq!(attrs.initial_position, Some((5, 6)));
        assert!(attrs.fullscreen);
        assert!(attrs.transparency);
    }

    // ── present_failure_action ───────────────────────────────────────────────

    #[test]
    fn present_success_with_no_prior_failures_is_plain_ok() {
        assert_eq!(
            present_failure_action(0, true, true),
            PresentFailureAction::Ok { was_failing: false }
        );
    }

    #[test]
    fn present_success_after_a_failure_streak_reports_recovery() {
        assert_eq!(
            present_failure_action(5, true, true),
            PresentFailureAction::Ok { was_failing: true }
        );
    }

    #[test]
    fn first_failure_in_a_streak_logs_at_error_level() {
        assert_eq!(
            present_failure_action(0, false, true),
            PresentFailureAction::Log {
                at_error_level: true
            }
        );
    }

    #[test]
    fn subsequent_failures_below_threshold_log_below_error_level() {
        for count in 1..PRESENT_FAILURE_RECOVERY_THRESHOLD - 1 {
            assert_eq!(
                present_failure_action(count, false, true),
                PresentFailureAction::Log {
                    at_error_level: false
                },
                "consecutive_failures = {count}"
            );
        }
    }

    #[test]
    fn failure_crossing_the_threshold_triggers_recovery() {
        // consecutive_failures is the count *before* this call, so
        // `PRESENT_FAILURE_RECOVERY_THRESHOLD - 1` failures already happened; this call is the
        // one that reaches the threshold.
        assert_eq!(
            present_failure_action(PRESENT_FAILURE_RECOVERY_THRESHOLD - 1, false, true),
            PresentFailureAction::Recover
        );
    }

    #[test]
    fn failure_recovers_again_every_full_threshold_after_the_first() {
        // A failed recovery attempt must not be retried on literally the next frame: the next
        // `Recover` only fires after another full threshold's worth of failures.
        assert_eq!(
            present_failure_action(2 * PRESENT_FAILURE_RECOVERY_THRESHOLD - 1, false, true),
            PresentFailureAction::Recover
        );
        for count in
            PRESENT_FAILURE_RECOVERY_THRESHOLD..(2 * PRESENT_FAILURE_RECOVERY_THRESHOLD - 1)
        {
            assert_eq!(
                present_failure_action(count, false, true),
                PresentFailureAction::Log {
                    at_error_level: false
                },
                "consecutive_failures = {count}"
            );
        }
    }

    #[test]
    fn unrecoverable_failure_is_fatal_immediately_regardless_of_streak_length() {
        // A presenter reporting `is_recoverable() == false` should skip straight to `Fatal` on
        // the very first failure, not wait for the consecutive-failure threshold the way the
        // generic (`recoverable == true`) path does.
        assert_eq!(
            present_failure_action(0, false, false),
            PresentFailureAction::Fatal
        );
    }

    #[test]
    fn unrecoverable_failure_stays_fatal_mid_streak() {
        // Whatever the running consecutive-failure count, an unrecoverable error always takes
        // the fatal path rather than the count-dependent `Log`/`Recover` decision.
        assert_eq!(
            present_failure_action(5, false, false),
            PresentFailureAction::Fatal
        );
        assert_eq!(
            present_failure_action(PRESENT_FAILURE_RECOVERY_THRESHOLD - 1, false, false),
            PresentFailureAction::Fatal
        );
    }

    #[test]
    fn recoverable_flag_is_ignored_on_success() {
        // `recoverable` only matters for a failed present; passing `false` alongside
        // `succeeded == true` must not change the outcome.
        assert_eq!(
            present_failure_action(3, true, false),
            PresentFailureAction::Ok { was_failing: true }
        );
    }

    /// A dependency-free [`Presenter`] with fixed 8x16 cells.
    ///
    /// The `WindowApp` tests only exercise event translation, cell math, and the `WindowBackend`
    /// queue: no rasterization or surface is needed.
    struct MockPresenter {
        /// Records the last [`Presenter::scale_factor_changed`] argument, if any.
        last_scale_factor: Cell<Option<f64>>,
        /// The size last reported by [`Output::size`], updated by [`Output::resize`] so tests
        /// can assert that `resize_to` keeps it in sync with the surface immediately, rather
        /// than only via a separate `Terminal::resize` call in response to `Event::Resize`.
        size: Cell<Size>,
    }

    impl Default for MockPresenter {
        fn default() -> Self {
            Self {
                last_scale_factor: Cell::new(None),
                size: Cell::new(Size::new(10, 5)),
            }
        }
    }

    impl Output for MockPresenter {
        type Error = core::convert::Infallible;

        fn draw<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn draw_layers<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn flush(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn size(&self) -> Size {
            self.size.get()
        }

        fn clear(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn resize(&mut self, size: Size) {
            self.size.set(size);
        }
    }

    impl Presenter for MockPresenter {
        type SurfaceError = core::convert::Infallible;

        fn init_surface(
            &mut self,
            _window: Arc<dyn crate::presenter::WindowHandle>,
        ) -> Result<(), Self::SurfaceError> {
            Ok(())
        }

        fn resize_surface(&mut self, _width: u32, _height: u32) {}

        fn present(&mut self) -> Result<(), Self::SurfaceError> {
            Ok(())
        }

        fn cell_size(&self) -> (u32, u32) {
            (8, 16)
        }

        fn scale_factor_changed(&mut self, scale_factor: f64) {
            self.last_scale_factor.set(Some(scale_factor));
        }
    }

    /// A [`Presenter`] that records every `resize_surface` call, so tests
    /// can assert on the pixel dimensions `on_resized` actually requests.
    #[derive(Default)]
    struct RecordingPresenter {
        resize_calls: Rc<RefCell<Vec<(u32, u32)>>>,
    }

    impl Output for RecordingPresenter {
        type Error = core::convert::Infallible;

        fn draw<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn draw_layers<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn flush(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn size(&self) -> Size {
            Size::new(10, 5)
        }

        fn clear(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn resize(&mut self, _size: Size) {}
    }

    impl Presenter for RecordingPresenter {
        type SurfaceError = core::convert::Infallible;

        fn init_surface(
            &mut self,
            _window: Arc<dyn crate::presenter::WindowHandle>,
        ) -> Result<(), Self::SurfaceError> {
            Ok(())
        }

        fn resize_surface(&mut self, width: u32, height: u32) {
            self.resize_calls.borrow_mut().push((width, height));
        }

        fn present(&mut self) -> Result<(), Self::SurfaceError> {
            Ok(())
        }

        fn cell_size(&self) -> (u32, u32) {
            (8, 16)
        }
    }

    /// A [`Presenter`] whose `present()` fails on demand, and which counts `init_surface` calls
    /// so tests can assert whether [`WindowApp::try_recover_surface`] actually ran.
    #[derive(Default)]
    struct FailingPresenter {
        /// `present()` returns `Err` while this is `true`.
        failing: Rc<Cell<bool>>,
        /// Number of `init_surface` calls observed (1 at construction time in real use; extra
        /// calls here are surface-recovery attempts).
        init_surface_calls: Rc<Cell<u32>>,
    }

    impl Output for FailingPresenter {
        type Error = core::convert::Infallible;

        fn draw<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn draw_layers<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn flush(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn size(&self) -> Size {
            Size::new(10, 5)
        }

        fn clear(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn resize(&mut self, _size: Size) {}
    }

    impl Presenter for FailingPresenter {
        type SurfaceError = &'static str;

        fn init_surface(
            &mut self,
            _window: Arc<dyn crate::presenter::WindowHandle>,
        ) -> Result<(), Self::SurfaceError> {
            self.init_surface_calls
                .set(self.init_surface_calls.get() + 1);
            Ok(())
        }

        fn resize_surface(&mut self, _width: u32, _height: u32) {}

        fn present(&mut self) -> Result<(), Self::SurfaceError> {
            if self.failing.get() {
                Err("simulated present failure")
            } else {
                Ok(())
            }
        }

        fn cell_size(&self) -> (u32, u32) {
            (8, 16)
        }
    }

    // `&'static str` inherits the default `is_recoverable() -> true`: `FailingPresenter`'s tests
    // exercise the existing (pre-`RecoverableError`) `Log`/`Recover` behavior, which must stay
    // unchanged now that `Presenter::SurfaceError` is bounded by `RecoverableError` instead of
    // plain `Debug + Display`.
    impl crate::presenter::RecoverableError for &'static str {}

    /// A `present()` error that always reports itself as unrecoverable (overrides
    /// [`RecoverableError::is_recoverable`](crate::presenter::RecoverableError::is_recoverable) to
    /// return `false`), so tests can exercise [`PresentFailureAction::Fatal`] end to end through
    /// [`WindowApp::handle_redraw_requested`].
    #[derive(Debug)]
    struct UnrecoverableError(&'static str);

    impl core::fmt::Display for UnrecoverableError {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            write!(f, "{}", self.0)
        }
    }

    impl crate::presenter::RecoverableError for UnrecoverableError {
        fn is_recoverable(&self) -> bool {
            false
        }
    }

    /// A [`Presenter`] whose `present()` always fails with an [`UnrecoverableError`] on demand,
    /// otherwise identical to [`FailingPresenter`].
    #[derive(Default)]
    struct FatalPresenter {
        /// `present()` returns `Err` while this is `true`.
        failing: Rc<Cell<bool>>,
        /// Number of `init_surface` calls observed.
        init_surface_calls: Rc<Cell<u32>>,
    }

    impl Output for FatalPresenter {
        type Error = core::convert::Infallible;

        fn draw<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn draw_layers<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn flush(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn size(&self) -> Size {
            Size::new(10, 5)
        }

        fn clear(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn resize(&mut self, _size: Size) {}
    }

    impl Presenter for FatalPresenter {
        type SurfaceError = UnrecoverableError;

        fn init_surface(
            &mut self,
            _window: Arc<dyn crate::presenter::WindowHandle>,
        ) -> Result<(), Self::SurfaceError> {
            self.init_surface_calls
                .set(self.init_surface_calls.get() + 1);
            Ok(())
        }

        fn resize_surface(&mut self, _width: u32, _height: u32) {}

        fn present(&mut self) -> Result<(), Self::SurfaceError> {
            if self.failing.get() {
                Err(UnrecoverableError(
                    "simulated unrecoverable present failure",
                ))
            } else {
                Ok(())
            }
        }

        fn cell_size(&self) -> (u32, u32) {
            (8, 16)
        }
    }

    type MockApp = WindowApp<
        MockPresenter,
        fn(&mut Terminal<WindowBackend<MockPresenter>>),
        u64,
        fn(u64, &mut Terminal<WindowBackend<MockPresenter>>),
    >;

    fn test_window_app() -> MockApp {
        let terminal = Terminal::new(WindowBackend::new(MockPresenter::default()));
        WindowApp {
            terminal: Some(terminal),
            app_loop: |_| {},
            on_custom_event: push_custom_event,
            _user_event: PhantomData,
            window: None,
            title: String::new(),
            init_size: InitWindowSize {
                width: 80,
                height: 80,
            },
            attrs: WindowAttrs::default(),
            current_modifiers: KeyModifiers::NONE,
            cursor_px: (0.0, 0.0),
            active_touch: None,
            held_buttons: 0,
            frame_interval: None,
            event_driven: true,
            #[cfg(not(target_arch = "wasm32"))]
            next_frame: std::time::Instant::now(),
            exit_requested: Rc::new(Cell::new(false)),
            skip_present: Rc::new(Cell::new(false)),
            needs_redraw: false,
            consecutive_present_errors: 0,
        }
    }

    fn poll(app: &mut MockApp) -> Option<Event> {
        app.terminal
            .as_mut()
            .unwrap()
            .backend_mut()
            .poll_event(Duration::ZERO)
    }

    // ── WindowBackend queue ───────────────────────────────────────────────────

    #[test]
    fn mouse_event_round_trips_through_event_buffer() {
        let mut backend = WindowBackend::new(MockPresenter::default());
        let ev = Event::Mouse(MouseEvent::new(
            MouseEventKind::Down(MouseButton::Left),
            Pos { x: 3, y: 1 },
            KeyModifiers::NONE,
        ));
        backend.push_event(ev.clone());
        assert_eq!(backend.poll_event(Duration::ZERO), Some(ev));
        assert_eq!(backend.poll_event(Duration::ZERO), None);
    }

    #[test]
    fn multiple_mouse_events_preserve_fifo_order() {
        let mut backend = WindowBackend::new(MockPresenter::default());
        let moved = Event::Mouse(MouseEvent::new(
            MouseEventKind::Moved,
            Pos { x: 1, y: 2 },
            KeyModifiers::NONE,
        ));
        let clicked = Event::Mouse(MouseEvent::new(
            MouseEventKind::Down(MouseButton::Left),
            Pos { x: 1, y: 2 },
            KeyModifiers::NONE,
        ));
        backend.push_event(moved.clone());
        backend.push_event(clicked.clone());
        assert_eq!(backend.poll_event(Duration::ZERO), Some(moved));
        assert_eq!(backend.poll_event(Duration::ZERO), Some(clicked));
    }

    // ── handle_window_event ──────────────────────────────────────────────────

    #[test]
    fn cursor_moved_pushes_moved_event_at_correct_cell() {
        // 8-wide × 16-tall cells; cursor at pixel (20, 32) → col 2, row 2.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(20.0_f64, 32.0_f64),
        });
        assert_eq!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent::with_pixel_position(
                MouseEventKind::Moved,
                Pos { x: 2, y: 2 },
                KeyModifiers::NONE,
                PhysicalPos { x: 20, y: 32 },
            )))
        );
    }

    #[test]
    fn cursor_moved_caches_position_for_subsequent_click() {
        // Move to pixel (16, 16) = col 2, row 1, then click; button event
        // must reuse the cached position.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(16.0_f64, 16.0_f64),
        });
        let _ = poll(&mut app); // discard the Moved event
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Left,
        });
        assert_eq!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent::with_pixel_position(
                MouseEventKind::Down(MouseButton::Left),
                Pos { x: 2, y: 1 },
                KeyModifiers::NONE,
                PhysicalPos { x: 16, y: 16 },
            )))
        );
    }

    #[test]
    fn mouse_button_release_produces_up_event() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Released,
            button: winit::event::MouseButton::Right,
        });
        assert_eq!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent::with_pixel_position(
                MouseEventKind::Up(MouseButton::Right),
                Pos { x: 0, y: 0 },
                KeyModifiers::NONE,
                PhysicalPos { x: 0, y: 0 },
            )))
        );
    }

    #[test]
    fn unknown_mouse_button_produces_no_event() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Other(99),
        });
        assert_eq!(poll(&mut app), None);
    }

    fn touch(id: u64, phase: winit::event::TouchPhase, x: f64, y: f64) -> WindowEvent {
        WindowEvent::Touch(winit::event::Touch {
            device_id: winit::event::DeviceId::dummy(),
            phase,
            location: winit::dpi::PhysicalPosition::new(x, y),
            force: None,
            id,
        })
    }

    #[test]
    fn touch_tap_synthesizes_left_click() {
        use winit::event::TouchPhase;
        let mut app = test_window_app();
        // MockPresenter cells are 8x16 px; a tap at (20, 18) lands on cell (2, 1).
        app.handle_window_event(touch(7, TouchPhase::Started, 20.0, 18.0));
        // Moved (from the synthesized cursor move) then Down.
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Moved,
                position: Pos { x: 2, y: 1 },
                ..
            }))
        ));
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                position: Pos { x: 2, y: 1 },
                ..
            }))
        ));

        app.handle_window_event(touch(7, TouchPhase::Ended, 20.0, 18.0));
        // The synthesized move fires while the touch's `Left` button is still held (the release
        // hasn't been synthesized yet), so it's reported as a drag, not a plain move.
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Left),
                ..
            }))
        ));
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left),
                position: Pos { x: 2, y: 1 },
                ..
            }))
        ));
        assert_eq!(poll(&mut app), None);
    }

    #[test]
    fn touch_drag_synthesizes_moves_between_down_and_up() {
        use winit::event::TouchPhase;
        let mut app = test_window_app();
        app.handle_window_event(touch(1, TouchPhase::Started, 0.0, 0.0));
        poll(&mut app); // Moved
        poll(&mut app); // Down

        app.handle_window_event(touch(1, TouchPhase::Moved, 40.0, 32.0));
        // Held Left button since Started: this is a drag, not a plain move.
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Left),
                position: Pos { x: 5, y: 2 },
                ..
            }))
        ));

        app.handle_window_event(touch(1, TouchPhase::Cancelled, 40.0, 32.0));
        poll(&mut app); // Drag (button still held until the synthesized Up just below)
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left),
                ..
            }))
        ));
    }

    #[test]
    fn second_finger_is_ignored_while_first_is_down() {
        use winit::event::TouchPhase;
        let mut app = test_window_app();
        app.handle_window_event(touch(1, TouchPhase::Started, 0.0, 0.0));
        poll(&mut app); // Moved
        poll(&mut app); // Down

        // A second finger goes down, moves, and lifts: all ignored.
        app.handle_window_event(touch(2, TouchPhase::Started, 80.0, 80.0));
        app.handle_window_event(touch(2, TouchPhase::Moved, 88.0, 80.0));
        app.handle_window_event(touch(2, TouchPhase::Ended, 88.0, 80.0));
        assert_eq!(poll(&mut app), None);

        // The first finger still completes its gesture.
        app.handle_window_event(touch(1, TouchPhase::Ended, 8.0, 0.0));
        poll(&mut app); // Moved
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left),
                position: Pos { x: 1, y: 0 },
                ..
            }))
        ));
    }

    #[test]
    fn scroll_up_line_delta() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseWheel {
            device_id: winit::event::DeviceId::dummy(),
            delta: winit::event::MouseScrollDelta::LineDelta(0.0, 1.0),
            phase: winit::event::TouchPhase::Moved,
        });
        let ev = poll(&mut app).unwrap();
        assert!(matches!(
            ev,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Scroll { dx: 0.0, dy },
                ..
            }) if dy > 0.0
        ));
    }

    #[test]
    fn scroll_down_line_delta() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseWheel {
            device_id: winit::event::DeviceId::dummy(),
            delta: winit::event::MouseScrollDelta::LineDelta(0.0, -1.0),
            phase: winit::event::TouchPhase::Moved,
        });
        let ev = poll(&mut app).unwrap();
        assert!(matches!(
            ev,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Scroll { dx: 0.0, dy },
                ..
            }) if dy < 0.0
        ));
    }

    #[test]
    fn scroll_up_pixel_delta() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseWheel {
            device_id: winit::event::DeviceId::dummy(),
            delta: winit::event::MouseScrollDelta::PixelDelta(winit::dpi::PhysicalPosition::new(
                0.0_f64, 15.0_f64,
            )),
            phase: winit::event::TouchPhase::Moved,
        });
        let ev = poll(&mut app).unwrap();
        assert!(matches!(
            ev,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Scroll { dx: 0.0, dy },
                ..
            }) if dy > 0.0
        ));
    }

    #[test]
    fn scroll_right_line_delta() {
        // A pure horizontal LineDelta (trackpad swipe, tilt wheel): scroll_y == 0.0.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseWheel {
            device_id: winit::event::DeviceId::dummy(),
            delta: winit::event::MouseScrollDelta::LineDelta(1.0, 0.0),
            phase: winit::event::TouchPhase::Moved,
        });
        let ev = poll(&mut app).unwrap();
        assert!(matches!(
            ev,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Scroll { dx, dy: 0.0 },
                ..
            }) if dx > 0.0
        ));
    }

    #[test]
    fn scroll_left_pixel_delta() {
        // Regression test for retroglyph#293: before the fix, a pure-horizontal `PixelDelta`
        // (scroll_y == 0.0) spuriously fell through to a spurious vertical scroll instead of
        // being reported as (or, before horizontal scroll was wired up, dropped as) a
        // horizontal scroll.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseWheel {
            device_id: winit::event::DeviceId::dummy(),
            delta: winit::event::MouseScrollDelta::PixelDelta(winit::dpi::PhysicalPosition::new(
                -15.0_f64, 0.0_f64,
            )),
            phase: winit::event::TouchPhase::Moved,
        });
        let ev = poll(&mut app).unwrap();
        assert!(matches!(
            ev,
            Event::Mouse(MouseEvent {
                kind: MouseEventKind::Scroll { dx, dy: 0.0 },
                ..
            }) if dx < 0.0
        ));
    }

    #[test]
    fn scroll_with_zero_delta_on_both_axes_pushes_no_event() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseWheel {
            device_id: winit::event::DeviceId::dummy(),
            delta: winit::event::MouseScrollDelta::LineDelta(0.0, 0.0),
            phase: winit::event::TouchPhase::Moved,
        });
        assert_eq!(poll(&mut app), None);
    }

    #[test]
    fn modifiers_propagate_to_mouse_event() {
        let mut app = test_window_app();
        // Simulate a ModifiersChanged before the click.
        app.handle_window_event(WindowEvent::ModifiersChanged(
            winit::event::Modifiers::from(winit::keyboard::ModifiersState::SHIFT),
        ));
        let _ = poll(&mut app); // no event emitted for modifiers
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Left,
        });
        let ev = poll(&mut app).unwrap();
        assert!(matches!(
            ev,
            Event::Mouse(MouseEvent {
                modifiers,
                ..
            }) if modifiers.contains(KeyModifiers::SHIFT)
        ));
    }

    // ── mouse drag (retroglyph#554) ───────────────────────────────────────────

    #[test]
    fn cursor_moved_with_no_button_held_emits_moved() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(8.0_f64, 16.0_f64),
        });
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Moved,
                ..
            }))
        ));
    }

    #[test]
    fn cursor_moved_while_button_held_emits_drag_not_moved() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Left,
        });
        let _ = poll(&mut app); // Down

        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(40.0_f64, 32.0_f64),
        });
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Left),
                ..
            }))
        ));
    }

    #[test]
    fn cursor_moved_after_button_release_goes_back_to_moved() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Left,
        });
        let _ = poll(&mut app); // Down
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Released,
            button: winit::event::MouseButton::Left,
        });
        let _ = poll(&mut app); // Up

        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(40.0_f64, 32.0_f64),
        });
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Moved,
                ..
            }))
        ));
    }

    #[test]
    fn right_button_drag_reports_right_not_left() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Right,
        });
        let _ = poll(&mut app); // Down

        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(40.0_f64, 32.0_f64),
        });
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Right),
                ..
            }))
        ));
    }

    #[test]
    fn left_button_takes_priority_over_right_when_both_are_held() {
        // Deterministic tie-break documented on `on_cursor_moved`: Left wins when more than one
        // button is held at once.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Right,
        });
        let _ = poll(&mut app); // Down
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Left,
        });
        let _ = poll(&mut app); // Down

        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(40.0_f64, 32.0_f64),
        });
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Left),
                ..
            }))
        ));
    }

    #[test]
    fn touch_drag_produces_drag_left_not_moved() {
        // Regression test for retroglyph#554: `on_touch` synthesizes a left-button `Down` before
        // its `Moved` phase forwards to `on_cursor_moved`, so a touch drag must fall out of the
        // same `held_buttons` tracking a real mouse drag uses, with no touch-specific code.
        use winit::event::TouchPhase;
        let mut app = test_window_app();
        app.handle_window_event(touch(1, TouchPhase::Started, 0.0, 0.0));
        poll(&mut app); // Moved
        poll(&mut app); // Down

        app.handle_window_event(touch(1, TouchPhase::Moved, 40.0, 32.0));
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Drag(MouseButton::Left),
                ..
            }))
        ));
    }

    #[test]
    fn focus_lost_clears_held_button_so_refocus_move_is_not_a_stale_drag() {
        // Regression test for retroglyph#554: a button released while the window is unfocused
        // never delivers `MouseInput`, so `held_buttons` must be force-cleared on blur or every
        // move after refocus keeps reporting a `Drag` for a button that's actually up.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Left,
        });
        let _ = poll(&mut app); // Down

        app.handle_window_event(WindowEvent::Focused(false));
        assert_eq!(poll(&mut app), Some(Event::FocusLost));
        assert_eq!(app.held_buttons, 0);

        app.handle_window_event(WindowEvent::Focused(true));
        assert_eq!(poll(&mut app), Some(Event::FocusGained));
        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(40.0_f64, 32.0_f64),
        });
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Moved,
                ..
            }))
        ));
    }

    // ── user events (EventProxy) ─────────────────────────────────────────────

    #[test]
    fn user_event_pushes_custom_event() {
        let mut app = test_window_app();
        app.handle_user_event(42);
        assert_eq!(poll(&mut app), Some(Event::Custom(42)));
    }

    #[test]
    fn multiple_user_events_preserve_fifo_order() {
        let mut app = test_window_app();
        app.handle_user_event(1);
        app.handle_user_event(2);
        assert_eq!(poll(&mut app), Some(Event::Custom(1)));
        assert_eq!(poll(&mut app), Some(Event::Custom(2)));
        assert_eq!(poll(&mut app), None);
    }

    #[test]
    fn user_events_interleave_with_window_events_in_arrival_order() {
        let mut app = test_window_app();
        app.handle_user_event(7);
        app.handle_window_event(WindowEvent::CloseRequested);
        assert_eq!(poll(&mut app), Some(Event::Custom(7)));
        assert_eq!(poll(&mut app), Some(Event::Close));
    }

    #[test]
    fn event_proxy_closed_reports_the_undelivered_id() {
        let err = EventProxyClosed(42);
        assert_eq!(err.into_inner(), 42);
        assert_eq!(err.to_string(), "event loop closed");
    }

    #[test]
    fn event_proxy_closed_round_trips_a_non_u64_payload() {
        // `EventProxyClosed<T>` carries whatever `T` `EventProxy<T>::send_event` was called
        // with, not just the `u64` default.
        let err = EventProxyClosed(String::from("asset.bin"));
        assert_eq!(err.to_string(), "event loop closed");
        assert_eq!(err.into_inner(), "asset.bin");
    }

    // ── typed EventProxy<T> (non-`u64` custom payload) ────────────────────────

    /// A payload that is emphatically not `u64`, to prove the typed path never funnels through
    /// [`Event::Custom`] (which is fixed to `u64` in `retroglyph_core`).
    #[derive(Debug, Clone, PartialEq, Eq)]
    struct AssetLoaded {
        name: String,
        bytes: usize,
    }

    type TypedAppLoop = fn(&mut Terminal<WindowBackend<MockPresenter>>);
    type TypedHandler = Box<dyn FnMut(AssetLoaded, &mut Terminal<WindowBackend<MockPresenter>>)>;
    type TypedApp = WindowApp<MockPresenter, TypedAppLoop, AssetLoaded, TypedHandler>;

    fn test_typed_window_app(on_custom_event: TypedHandler) -> TypedApp {
        let terminal = Terminal::new(WindowBackend::new(MockPresenter::default()));
        WindowApp {
            terminal: Some(terminal),
            app_loop: |_| {},
            on_custom_event,
            _user_event: PhantomData,
            window: None,
            title: String::new(),
            init_size: InitWindowSize {
                width: 80,
                height: 80,
            },
            attrs: WindowAttrs::default(),
            current_modifiers: KeyModifiers::NONE,
            cursor_px: (0.0, 0.0),
            active_touch: None,
            held_buttons: 0,
            frame_interval: None,
            event_driven: true,
            #[cfg(not(target_arch = "wasm32"))]
            next_frame: std::time::Instant::now(),
            exit_requested: Rc::new(Cell::new(false)),
            skip_present: Rc::new(Cell::new(false)),
            needs_redraw: false,
            consecutive_present_errors: 0,
        }
    }

    #[test]
    fn typed_user_event_reaches_the_custom_handler_not_event_custom() {
        let received: Rc<RefCell<Vec<AssetLoaded>>> = Rc::new(RefCell::new(Vec::new()));
        let received_in_handler = received.clone();
        let handler: TypedHandler = Box::new(move |payload, _term| {
            received_in_handler.borrow_mut().push(payload);
        });
        let mut app = test_typed_window_app(handler);

        let payload = AssetLoaded {
            name: "asset.bin".to_string(),
            bytes: 4096,
        };
        app.handle_user_event(payload.clone());

        // Delivered to the handler directly...
        assert_eq!(received.borrow().as_slice(), &[payload]);
        // ...and never pushed onto the `WindowBackend` event queue as an `Event` at all: there is
        // no `Event` variant a non-`u64` payload could become.
        assert_eq!(
            app.terminal
                .as_mut()
                .unwrap()
                .backend_mut()
                .poll_event(Duration::ZERO),
            None
        );
    }

    #[test]
    fn typed_user_event_still_sets_needs_redraw() {
        // Same wake-the-idle-loop behavior as the `u64`/`Event::Custom` path.
        let handler: TypedHandler = Box::new(|_payload, _term| {});
        let mut app = test_typed_window_app(handler);
        assert!(!app.needs_redraw);
        app.handle_user_event(AssetLoaded {
            name: "asset.bin".to_string(),
            bytes: 4096,
        });
        assert!(app.needs_redraw);
    }

    #[test]
    fn close_requested_pushes_close_event() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::CloseRequested);
        assert_eq!(poll(&mut app), Some(Event::Close));
    }

    // ── IME (issue #296) ──────────────────────────────────────────────────────

    #[test]
    fn ime_commit_pushes_paste_event() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::Ime(winit::event::Ime::Commit(
            "pasted".to_string(),
        )));
        assert_eq!(poll(&mut app), Some(Event::Paste("pasted".to_string())));
    }

    #[test]
    fn ime_preedit_and_enabled_push_no_event() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::Ime(winit::event::Ime::Enabled));
        app.handle_window_event(WindowEvent::Ime(winit::event::Ime::Preedit(
            "nihon".to_string(),
            Some((0, 5)),
        )));
        assert_eq!(poll(&mut app), None);
    }

    // ── graceful exit (issue #157) ────────────────────────────────────────────

    /// A `WindowApp` whose `app_loop` is a boxed closure, so a test can capture and flip a
    /// shared flag from inside it, mirroring how `run_app_with_proxy`'s real closure sets
    /// `exit_requested` on `Flow::Exit` (it can't return a value or reach `ActiveEventLoop`
    /// itself; see `exit_requested`'s doc comment).
    type BoxedAppLoop = Box<dyn FnMut(&mut Terminal<WindowBackend<MockPresenter>>)>;
    type BoxedApp = WindowApp<
        MockPresenter,
        BoxedAppLoop,
        u64,
        fn(u64, &mut Terminal<WindowBackend<MockPresenter>>),
    >;

    #[test]
    fn redraw_requested_runs_app_loop_and_does_not_set_exit_by_default() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::RedrawRequested);
        assert!(!app.exit_requested.get());
    }

    #[test]
    fn app_loop_setting_exit_requested_is_observed_after_redraw() {
        // Simulates `run_app_with_proxy`'s closure: on `Flow::Exit` it sets the shared flag
        // instead of calling `std::process::exit`. `handle_window_event` itself never calls
        // `event_loop.exit()` (it can't: no `ActiveEventLoop`, see its doc comment); that
        // happens in `ApplicationHandler::window_event`, which this flag lets the test assert
        // on without a live winit event loop.
        let terminal = Terminal::new(WindowBackend::new(MockPresenter::default()));
        let exit_requested = Rc::new(Cell::new(false));
        let exit_requested_in_loop = exit_requested.clone();
        let app_loop: BoxedAppLoop = Box::new(move |_term| exit_requested_in_loop.set(true));
        let mut app: BoxedApp = WindowApp {
            terminal: Some(terminal),
            app_loop,
            on_custom_event: push_custom_event,
            _user_event: PhantomData,
            window: None,
            title: String::new(),
            init_size: InitWindowSize {
                width: 80,
                height: 80,
            },
            attrs: WindowAttrs::default(),
            current_modifiers: KeyModifiers::NONE,
            cursor_px: (0.0, 0.0),
            active_touch: None,
            held_buttons: 0,
            frame_interval: None,
            event_driven: true,
            #[cfg(not(target_arch = "wasm32"))]
            next_frame: std::time::Instant::now(),
            exit_requested,
            skip_present: Rc::new(Cell::new(false)),
            needs_redraw: false,
            consecutive_present_errors: 0,
        };

        assert!(!app.exit_requested.get());
        app.handle_window_event(WindowEvent::RedrawRequested);
        assert!(app.exit_requested.get());
    }

    #[test]
    fn theme_changed_pushes_mapped_system_theme_event() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::ThemeChanged(winit::window::Theme::Light));
        assert_eq!(
            poll(&mut app),
            Some(Event::ThemeChanged(
                retroglyph_core::event::SystemTheme::Light
            ))
        );

        app.handle_window_event(WindowEvent::ThemeChanged(winit::window::Theme::Dark));
        assert_eq!(
            poll(&mut app),
            Some(Event::ThemeChanged(
                retroglyph_core::event::SystemTheme::Dark
            ))
        );
    }

    #[test]
    fn focused_pushes_focus_gained_and_lost_events() {
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::Focused(true));
        assert_eq!(poll(&mut app), Some(Event::FocusGained));

        app.handle_window_event(WindowEvent::Focused(false));
        assert_eq!(poll(&mut app), Some(Event::FocusLost));
    }

    #[test]
    fn focus_lost_resets_stuck_modifiers() {
        // Regression test for #153: a modifier held down when focus is lost
        // (e.g. alt-tabbing away while holding Shift) must not stay "held"
        // for events delivered after focus returns.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::ModifiersChanged(
            winit::event::Modifiers::from(winit::keyboard::ModifiersState::SHIFT),
        ));
        let _ = poll(&mut app); // no event emitted for modifiers
        assert_eq!(app.current_modifiers, KeyModifiers::SHIFT);

        app.handle_window_event(WindowEvent::Focused(false));
        assert_eq!(poll(&mut app), Some(Event::FocusLost));
        assert_eq!(app.current_modifiers, KeyModifiers::NONE);

        // A click after refocusing must not still carry the stale Shift.
        app.handle_window_event(WindowEvent::Focused(true));
        assert_eq!(poll(&mut app), Some(Event::FocusGained));
        app.handle_window_event(WindowEvent::MouseInput {
            device_id: winit::event::DeviceId::dummy(),
            state: winit::event::ElementState::Pressed,
            button: winit::event::MouseButton::Left,
        });
        let ev = poll(&mut app).unwrap();
        assert!(matches!(
            ev,
            Event::Mouse(MouseEvent { modifiers, .. }) if modifiers == KeyModifiers::NONE
        ));
    }

    #[test]
    fn focus_lost_releases_stuck_active_touch() {
        // Regression test for #153: a finger lifted while the window is
        // unfocused/backgrounded never delivers `TouchPhase::Ended` or
        // `Cancelled`, so `active_touch` must be released on blur instead of
        // silently ignoring every subsequent finger down.
        use winit::event::TouchPhase;
        let mut app = test_window_app();
        app.handle_window_event(touch(3, TouchPhase::Started, 20.0, 18.0));
        poll(&mut app); // Moved
        poll(&mut app); // Down
        assert_eq!(app.active_touch, Some(3));

        app.handle_window_event(WindowEvent::Focused(false));
        assert_eq!(poll(&mut app), Some(Event::FocusLost));
        // Synthesized Up releasing the stuck touch at its last known
        // position; no new Moved, since blur carries no fresh location.
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Up(MouseButton::Left),
                ..
            }))
        ));
        assert_eq!(poll(&mut app), None);
        assert_eq!(app.active_touch, None);

        // A new finger down after refocusing must be tracked, not ignored.
        app.handle_window_event(WindowEvent::Focused(true));
        assert_eq!(poll(&mut app), Some(Event::FocusGained));
        app.handle_window_event(touch(4, TouchPhase::Started, 40.0, 32.0));
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Moved,
                ..
            }))
        ));
        assert!(matches!(
            poll(&mut app),
            Some(Event::Mouse(MouseEvent {
                kind: MouseEventKind::Down(MouseButton::Left),
                ..
            }))
        ));
        assert_eq!(app.active_touch, Some(4));
    }

    #[test]
    fn focus_lost_without_active_touch_pushes_no_extra_events() {
        // No touch in progress: blur should push exactly one FocusLost, no
        // synthesized mouse events.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::Focused(false));
        assert_eq!(poll(&mut app), Some(Event::FocusLost));
        assert_eq!(poll(&mut app), None);
    }

    #[test]
    fn resized_pushes_resize_event_in_cells() {
        // 8x16 cells: 88x80 px -> 11 cols, 5 rows.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::Resized(winit::dpi::PhysicalSize::new(88, 80)));
        assert_eq!(poll(&mut app), Some(Event::Resize(11, 5)));
    }

    // ── scale factor changes ─────────────────────────────────────────────────

    #[test]
    fn scale_factor_changed_notifies_presenter() {
        // `handle_window_event` can't be exercised directly here: winit's
        // `InnerSizeWriter::new` is `pub(crate)`, so a real
        // `WindowEvent::ScaleFactorChanged` can't be constructed outside the
        // winit crate. `on_scale_factor_changed` is called directly instead:
        // it's the same code the `WindowEvent::ScaleFactorChanged` arm in
        // `handle_window_event` dispatches to.
        let mut app = test_window_app();
        app.on_scale_factor_changed(2.0);
        assert_eq!(
            app.terminal
                .as_ref()
                .unwrap()
                .backend()
                .presenter()
                .last_scale_factor
                .get(),
            Some(2.0)
        );
    }

    #[test]
    fn scale_factor_changed_without_a_window_is_a_no_op_resize() {
        // `test_window_app` has no real winit window (`window: None`), so
        // there is no physical size to re-align the surface to: this must
        // not panic, and must not push a spurious `Event::Resize`.
        let mut app = test_window_app();
        app.on_scale_factor_changed(2.0);
        assert_eq!(poll(&mut app), None);
    }

    #[test]
    fn resize_to_clamps_to_whole_cells_and_pushes_resize_event() {
        // Shared helper behind both `on_resized` and
        // `on_scale_factor_changed`: 8x16 cells, 90x81 px clamps down to
        // 11 cols x 5 rows (88x80 px), not a fractional cell.
        let mut app = test_window_app();
        app.resize_to(winit::dpi::PhysicalSize::new(90, 81));
        assert_eq!(poll(&mut app), Some(Event::Resize(11, 5)));
    }

    #[test]
    fn resize_to_updates_backend_size_immediately() {
        // Regression test for #508: previously `backend.size()` (via `Output::size`) kept
        // reporting the pre-resize dimensions until the app called `Terminal::resize` in
        // response to `Event::Resize`, so polling the backend directly for drift was useless.
        // `resize_to` must now also call `Output::resize` so `size()` agrees with the surface
        // right away, independent of whether/when the app resizes the terminal's own grid.
        let mut app = test_window_app();
        assert_eq!(
            app.terminal.as_ref().unwrap().backend().size(),
            Size::new(10, 5)
        );
        app.resize_to(winit::dpi::PhysicalSize::new(90, 81));
        assert_eq!(
            app.terminal.as_ref().unwrap().backend().size(),
            Size::new(11, 5)
        );
        // `Terminal::size` (the grid itself) is untouched: that stays the app's job, done by
        // calling `Terminal::resize` in response to the `Event::Resize` this same call pushed.
        assert_eq!(app.terminal.as_ref().unwrap().size(), Size::new(10, 5));
    }

    #[test]
    fn resized_below_one_cell_clamps_surface_and_event_to_1x1() {
        // Regression test for #140: an 8x16-cell presenter resized to a
        // window smaller than one cell (4x4 px) must not compute 0 cols/0
        // rows: that would ask `resize_surface` for a zero-size surface,
        // which crashes softbuffer.
        type RecordingApp = WindowApp<
            RecordingPresenter,
            fn(&mut Terminal<WindowBackend<RecordingPresenter>>),
            u64,
            fn(u64, &mut Terminal<WindowBackend<RecordingPresenter>>),
        >;
        let resize_calls = Rc::new(RefCell::new(Vec::new()));
        let presenter = RecordingPresenter {
            resize_calls: resize_calls.clone(),
        };
        let terminal = Terminal::new(WindowBackend::new(presenter));
        let mut app: RecordingApp = WindowApp {
            terminal: Some(terminal),
            app_loop: |_| {},
            on_custom_event: push_custom_event,
            _user_event: PhantomData,
            window: None,
            title: String::new(),
            init_size: InitWindowSize {
                width: 80,
                height: 80,
            },
            attrs: WindowAttrs::default(),
            current_modifiers: KeyModifiers::NONE,
            cursor_px: (0.0, 0.0),
            active_touch: None,
            held_buttons: 0,
            frame_interval: None,
            event_driven: true,
            #[cfg(not(target_arch = "wasm32"))]
            next_frame: std::time::Instant::now(),
            exit_requested: Rc::new(Cell::new(false)),
            skip_present: Rc::new(Cell::new(false)),
            needs_redraw: false,
            consecutive_present_errors: 0,
        };

        app.handle_window_event(WindowEvent::Resized(winit::dpi::PhysicalSize::new(4, 4)));

        // Surface must be resized to at least one full cell (8x16), not
        // 0x0.
        assert_eq!(resize_calls.borrow().as_slice(), &[(8, 16)]);
        // Event::Resize must report the same clamped 1x1 grid, not 0x0.
        assert_eq!(
            app.terminal
                .as_mut()
                .unwrap()
                .backend_mut()
                .poll_event(Duration::ZERO),
            Some(Event::Resize(1, 1))
        );
    }

    // ── needs_redraw (idle/redraw-on-demand, issue #155) ─────────────────────

    #[test]
    fn fresh_app_does_not_need_a_redraw() {
        // `test_window_app` starts with `needs_redraw: false`, unlike the real
        // `resumed()` path, which sets it `true` once the window/surface exists (a real winit
        // `ActiveEventLoop` can't be constructed in a unit test, so `resumed` itself isn't
        // exercised here; see `handle_window_event`/`handle_user_event` below for the parts of
        // the redraw-on-demand logic that are testable without one).
        let app = test_window_app();
        assert!(!app.needs_redraw);
    }

    #[test]
    fn window_event_sets_needs_redraw() {
        // Any real window event (a mouse move here, but any arm other than `RedrawRequested`
        // behaves the same; see `handle_window_event`'s doc comment) should mark that the app
        // loop has something new to react to, so the next `about_to_wait` requests a redraw
        // instead of leaving the loop idle.
        let mut app = test_window_app();
        assert!(!app.needs_redraw);
        app.handle_window_event(WindowEvent::CursorMoved {
            device_id: winit::event::DeviceId::dummy(),
            position: winit::dpi::PhysicalPosition::new(1.0_f64, 1.0_f64),
        });
        assert!(app.needs_redraw);
    }

    #[test]
    fn redraw_requested_does_not_itself_set_needs_redraw() {
        // `RedrawRequested` is the render this flag exists to gate, not a new event to redraw
        // again for: an idle app that gets exactly one `RedrawRequested` (e.g. right after
        // `resumed`) must not perpetually re-arm itself into another one forever.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::RedrawRequested);
        assert!(!app.needs_redraw);
    }

    #[test]
    fn user_event_sets_needs_redraw() {
        // A cross-thread `Event::Custom` injection (network, audio, timer, ...) must wake an
        // idle loop into rendering the next frame just like a real window event does.
        let mut app = test_window_app();
        assert!(!app.needs_redraw);
        app.handle_user_event(1);
        assert!(app.needs_redraw);
    }

    #[test]
    fn unhandled_window_events_still_set_needs_redraw() {
        // Even a `WindowEvent` variant with no dedicated handling below (falls through to the
        // `_ => {}` arm in `handle_window_event`'s `match`) should still be treated as "something
        // happened": the flag is set once, up front, before the match runs.
        let mut app = test_window_app();
        app.handle_window_event(WindowEvent::Occluded(true));
        assert!(app.needs_redraw);
    }

    // ── frame-rate cap (target_fps) ───────────────────────────────────────────

    #[test]
    fn target_fps_none_is_redraw_on_demand() {
        // `target_fps: None` leaves `frame_interval` unset, i.e. uncapped whenever a redraw
        // happens; `event_driven: true` is what sends `about_to_wait` down the
        // `needs_redraw`-gated branch.
        let presenter = MockPresenter::default();
        assert_eq!(
            WindowConfig::fit(&presenter, "test", None, true).target_fps(),
            None
        );
    }

    #[test]
    fn target_fps_some_survives_to_the_config() {
        // Regression guard for the wasm32 half of the freeze this mode fixes: `target_fps` used
        // to be dropped on the floor for wasm builds (`frame_interval` was `#[cfg(not(target_arch
        // = "wasm32"))]`), so a browser app asking for continuous rendering silently got
        // redraw-on-demand and rendered one frame for the life of the page. The field is
        // unconditional now; this pins the config end of that, and the `compile-wasm` CI job pins
        // the driver end.
        let presenter = MockPresenter::default();
        assert_eq!(
            WindowConfig::fit(&presenter, "test", Some(60), false).target_fps(),
            Some(60)
        );
    }

    #[test]
    fn event_driven_accessor_reflects_the_config() {
        let presenter = MockPresenter::default();
        assert!(WindowConfig::fit(&presenter, "test", None, true).event_driven());
        assert!(!WindowConfig::fit(&presenter, "test", None, false).event_driven());
    }

    #[test]
    fn target_fps_and_event_driven_combine_independently() {
        // The combination `fit` alone couldn't express before: always redraw (not event-driven)
        // but uncapped (no `target_fps`).
        let presenter = MockPresenter::default();
        let config = WindowConfig::fit(&presenter, "test", None, false);
        assert_eq!(config.target_fps(), None);
        assert!(!config.event_driven());
    }

    #[test]
    fn animated_is_sugar_for_continuous_capped_fit() {
        let presenter = MockPresenter::default();
        let config = WindowConfig::animated(&presenter, "test", 60);
        assert_eq!(config.target_fps(), Some(60));
        assert!(!config.event_driven());
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn frame_deadline_in_the_future_parks_the_loop() {
        let now = std::time::Instant::now();
        let next = now + Duration::from_millis(10);
        assert_eq!(
            next_frame_deadline(now, next, Duration::from_millis(16)),
            None
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn frame_deadline_reached_advances_by_exactly_one_interval() {
        // On time (deadline just passed): the next deadline is one interval on from the *deadline*,
        // not from `now`, so a steady loop doesn't drift later and later.
        let interval = Duration::from_millis(16);
        let next = std::time::Instant::now();
        let now = next + Duration::from_micros(200);
        assert_eq!(
            next_frame_deadline(now, next, interval),
            Some(next + interval)
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn overrun_frame_deadline_clamps_to_now_instead_of_bursting() {
        // A frame that blew well past its budget must not leave a backlog of deadlines already in
        // the past, which would render several catch-up frames back to back at full speed.
        let interval = Duration::from_millis(16);
        let next = std::time::Instant::now();
        let now = next + Duration::from_millis(500);
        assert_eq!(next_frame_deadline(now, next, interval), Some(now));
    }

    // ── handle_redraw_requested / present() failure recovery ─────────────────

    type FailingApp = WindowApp<
        FailingPresenter,
        fn(&mut Terminal<WindowBackend<FailingPresenter>>),
        u64,
        fn(u64, &mut Terminal<WindowBackend<FailingPresenter>>),
    >;

    fn failing_app() -> (FailingApp, Rc<Cell<bool>>, Rc<Cell<u32>>) {
        let failing = Rc::new(Cell::new(false));
        let init_surface_calls = Rc::new(Cell::new(0));
        let presenter = FailingPresenter {
            failing: failing.clone(),
            init_surface_calls: init_surface_calls.clone(),
        };
        let terminal = Terminal::new(WindowBackend::new(presenter));
        let app: FailingApp = WindowApp {
            terminal: Some(terminal),
            app_loop: (|_| {}) as fn(&mut Terminal<WindowBackend<FailingPresenter>>),
            on_custom_event: push_custom_event,
            _user_event: PhantomData,
            window: None,
            title: String::new(),
            init_size: InitWindowSize {
                width: 80,
                height: 80,
            },
            attrs: WindowAttrs::default(),
            current_modifiers: KeyModifiers::NONE,
            cursor_px: (0.0, 0.0),
            active_touch: None,
            held_buttons: 0,
            frame_interval: None,
            event_driven: true,
            #[cfg(not(target_arch = "wasm32"))]
            next_frame: std::time::Instant::now(),
            exit_requested: Rc::new(Cell::new(false)),
            skip_present: Rc::new(Cell::new(false)),
            needs_redraw: false,
            consecutive_present_errors: 0,
        };
        (app, failing, init_surface_calls)
    }

    #[test]
    fn successful_presents_never_increment_the_failure_counter() {
        let (mut app, _failing, _init_calls) = failing_app();
        for _ in 0..5 {
            app.handle_redraw_requested();
        }
        assert_eq!(app.consecutive_present_errors, 0);
    }

    #[test]
    fn failing_presents_increment_the_counter_and_stop_short_of_recovery() {
        let (mut app, failing, init_calls) = failing_app();
        failing.set(true);
        for _ in 0..PRESENT_FAILURE_RECOVERY_THRESHOLD - 1 {
            app.handle_redraw_requested();
        }
        assert_eq!(
            app.consecutive_present_errors,
            PRESENT_FAILURE_RECOVERY_THRESHOLD - 1
        );
        // No window to recover from in this test app (`window: None`), but recovery should not
        // even have been attempted yet regardless: confirmed by `try_recover_surface`'s own
        // no-window guard never being reached, i.e. `init_surface` was never called past the
        // initial 0.
        assert_eq!(init_calls.get(), 0);
    }

    #[test]
    fn counter_resets_after_recovering_from_a_failure_streak() {
        let (mut app, failing, _init_calls) = failing_app();
        failing.set(true);
        for _ in 0..5 {
            app.handle_redraw_requested();
        }
        assert_eq!(app.consecutive_present_errors, 5);

        failing.set(false);
        app.handle_redraw_requested();
        assert_eq!(app.consecutive_present_errors, 0);
    }

    #[test]
    fn crossing_the_recovery_threshold_attempts_recovery_without_panicking() {
        // `test_window_app`/`failing_app` have no real winit `Window` (constructing one needs a
        // live event loop, unavailable in a unit test, the same limitation documented on
        // `scale_factor_changed_without_a_window_is_a_no_op_resize` above), so this can't assert
        // `init_surface` actually re-runs; `try_recover_surface`'s own no-window guard is exercised
        // directly below instead. What this does verify: the threshold-crossing call does not
        // panic, and the counter keeps incrementing through and past the threshold rather than
        // resetting or overflowing.
        let (mut app, failing, init_calls) = failing_app();
        failing.set(true);
        for _ in 0..PRESENT_FAILURE_RECOVERY_THRESHOLD {
            app.handle_redraw_requested();
        }
        assert_eq!(
            app.consecutive_present_errors,
            PRESENT_FAILURE_RECOVERY_THRESHOLD
        );
        assert_eq!(
            init_calls.get(),
            0,
            "no window means try_recover_surface's guard skips init_surface"
        );
    }

    #[test]
    fn try_recover_surface_without_a_window_is_a_no_op() {
        let (mut app, _failing, init_calls) = failing_app();
        app.try_recover_surface();
        assert_eq!(init_calls.get(), 0);
    }

    // ── automatic `Terminal::present` on redraw ───────────────────────────────

    /// A [`Presenter`] that mirrors every drawn diff into an in-memory grid (like
    /// [`retroglyph_core::backend::Headless`], but implementing [`Presenter`] instead), so tests
    /// can assert on what was actually presented rather than just on whether `present()` returned
    /// `Ok`.
    #[derive(Default)]
    struct GridRecordingPresenter {
        /// `(x, y) -> glyph` for every cell ever written by `draw_layers`. A real display only
        /// keeps the latest write per cell, which is exactly what repeated `HashMap` inserts give
        /// us here.
        cells: RefCell<std::collections::HashMap<(u16, u16), char>>,
        /// Number of `draw_layers` calls observed, so tests can assert whether a second (and, per
        /// this module's `present`-erases-if-nothing-new-was-drawn finding, harmful) diff was ever
        /// sent.
        draw_calls: Cell<u32>,
    }

    impl Output for GridRecordingPresenter {
        type Error = core::convert::Infallible;

        fn draw<'a, I>(&mut self, _content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            Ok(())
        }

        fn draw_layers<'a, I>(&mut self, content: I) -> Result<(), Self::Error>
        where
            I: Iterator<Item = DrawCell<'a>>,
        {
            self.draw_calls.set(self.draw_calls.get() + 1);
            let mut cells = self.cells.borrow_mut();
            for cell in content {
                cells.insert((cell.pos.x, cell.pos.y), cell.tile.glyph());
            }
            Ok(())
        }

        fn flush(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn size(&self) -> Size {
            Size::new(10, 5)
        }

        fn clear(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }

        fn resize(&mut self, _size: Size) {}
    }

    impl Presenter for GridRecordingPresenter {
        type SurfaceError = core::convert::Infallible;

        fn init_surface(
            &mut self,
            _window: Arc<dyn crate::presenter::WindowHandle>,
        ) -> Result<(), Self::SurfaceError> {
            Ok(())
        }

        fn resize_surface(&mut self, _width: u32, _height: u32) {}

        fn present(&mut self) -> Result<(), Self::SurfaceError> {
            Ok(())
        }

        fn cell_size(&self) -> (u32, u32) {
            (8, 16)
        }
    }

    type GridRecordingApp = WindowApp<
        GridRecordingPresenter,
        fn(&mut Terminal<WindowBackend<GridRecordingPresenter>>),
        u64,
        fn(u64, &mut Terminal<WindowBackend<GridRecordingPresenter>>),
    >;

    /// Boxed-closure counterparts of [`GridRecordingApp`]'s type parameters, for tests (like
    /// [`skip_present_set_inside_app_loop_suppresses_the_automatic_present`]) whose `app_loop`
    /// needs to capture and mutate a shared flag, which a bare `fn` pointer cannot do.
    type BoxedGridRecordingAppLoop =
        Box<dyn FnMut(&mut Terminal<WindowBackend<GridRecordingPresenter>>)>;
    type BoxedGridRecordingApp = WindowApp<
        GridRecordingPresenter,
        BoxedGridRecordingAppLoop,
        u64,
        fn(u64, &mut Terminal<WindowBackend<GridRecordingPresenter>>),
    >;

    fn recording_app(
        app_loop: fn(&mut Terminal<WindowBackend<GridRecordingPresenter>>),
    ) -> GridRecordingApp {
        let terminal = Terminal::new(WindowBackend::new(GridRecordingPresenter::default()));
        WindowApp {
            terminal: Some(terminal),
            app_loop,
            on_custom_event: push_custom_event,
            _user_event: PhantomData,
            window: None,
            title: String::new(),
            init_size: InitWindowSize {
                width: 80,
                height: 80,
            },
            attrs: WindowAttrs::default(),
            current_modifiers: KeyModifiers::NONE,
            cursor_px: (0.0, 0.0),
            active_touch: None,
            held_buttons: 0,
            frame_interval: None,
            event_driven: true,
            #[cfg(not(target_arch = "wasm32"))]
            next_frame: std::time::Instant::now(),
            exit_requested: Rc::new(Cell::new(false)),
            skip_present: Rc::new(Cell::new(false)),
            needs_redraw: false,
            consecutive_present_errors: 0,
        }
    }

    #[test]
    fn app_loop_that_never_presents_is_still_drawn_by_the_automatic_present() {
        // Case (a): an `app_loop` that draws but never calls `term.present()` itself must still
        // reach the backend: that's the whole point of this driver-side automatic present.
        let mut app = recording_app(|term| {
            term.surface()
                .put((0, 0), '@', retroglyph_core::color::Style::default());
        });
        app.handle_redraw_requested();
        let term = app.terminal.as_ref().unwrap();
        let presenter = term.backend().presenter();
        assert_eq!(presenter.cells.borrow().get(&(0, 0)), Some(&'@'));
        assert_eq!(
            presenter.draw_calls.get(),
            1,
            "exactly one present this frame"
        );
    }

    #[test]
    fn app_loop_that_already_presents_itself_is_not_double_drawn() {
        // Case (b): an `app_loop` that still calls `term.present()` itself (the pre-fix pattern)
        // must keep working, and, crucially, must not have its frame blanked by a second,
        // driver-side `present()` call diffing an now-empty `current` against the just-drawn
        // `previous` (see `Terminal::present`'s doc comment for why that second call would
        // otherwise erase the frame).
        let mut app = recording_app(|term| {
            term.surface()
                .put((0, 0), '@', retroglyph_core::color::Style::default());
            term.present().expect("app_loop's own present");
        });
        app.handle_redraw_requested();
        let term = app.terminal.as_ref().unwrap();
        let presenter = term.backend().presenter();
        assert_eq!(presenter.cells.borrow().get(&(0, 0)), Some(&'@'));
        assert_eq!(
            presenter.draw_calls.get(),
            1,
            "the driver must detect app_loop's own present and skip its automatic one"
        );
    }

    #[test]
    fn skip_present_set_inside_app_loop_suppresses_the_automatic_present() {
        // Simulates an `App::update` returning `Flow::Idle`: `run_app_with_proxy`'s closure draws
        // nothing and sets `skip_present` from inside `app_loop`, the same point in the frame
        // `run_app_with_proxy`'s real closure sets it from. `handle_redraw_requested` must honor
        // it: `Terminal::present` always presents unconditionally (even on an untouched frame),
        // so without this explicit skip it would still run and erase whatever the previous frame
        // left on screen.
        let terminal = Terminal::new(WindowBackend::new(GridRecordingPresenter::default()));
        let skip_present = Rc::new(Cell::new(false));
        let skip_present_in_loop = skip_present.clone();
        let app_loop: BoxedGridRecordingAppLoop =
            Box::new(move |_term| skip_present_in_loop.set(true));
        let mut app: BoxedGridRecordingApp = WindowApp {
            terminal: Some(terminal),
            app_loop,
            on_custom_event: push_custom_event,
            _user_event: PhantomData,
            window: None,
            title: String::new(),
            init_size: InitWindowSize {
                width: 80,
                height: 80,
            },
            attrs: WindowAttrs::default(),
            current_modifiers: KeyModifiers::NONE,
            cursor_px: (0.0, 0.0),
            active_touch: None,
            held_buttons: 0,
            frame_interval: None,
            event_driven: true,
            #[cfg(not(target_arch = "wasm32"))]
            next_frame: std::time::Instant::now(),
            exit_requested: Rc::new(Cell::new(false)),
            skip_present,
            needs_redraw: false,
            consecutive_present_errors: 0,
        };
        app.handle_redraw_requested();
        let term = app.terminal.as_ref().unwrap();
        let presenter = term.backend().presenter();
        assert_eq!(
            presenter.draw_calls.get(),
            0,
            "no present reaches the backend when app_loop sets skip_present"
        );
    }

    #[test]
    fn skip_present_does_not_carry_over_to_the_next_redraw() {
        // `handle_redraw_requested` must reset `skip_present` before running `app_loop`, so a
        // stale `true` from a previous `Idle` frame can't suppress the next frame's present.
        let mut app = recording_app(|term| {
            term.surface()
                .put((0, 0), '@', retroglyph_core::color::Style::default());
        });
        app.skip_present.set(true); // Stale value, as if left over from a prior Idle frame.
        app.handle_redraw_requested();
        let term = app.terminal.as_ref().unwrap();
        let presenter = term.backend().presenter();
        assert_eq!(presenter.cells.borrow().get(&(0, 0)), Some(&'@'));
        assert_eq!(presenter.draw_calls.get(), 1);
    }

    #[test]
    fn present_count_advances_once_per_present_call() {
        let mut term = Terminal::new(WindowBackend::new(GridRecordingPresenter::default()));
        assert_eq!(term.present_count(), 0);
        term.present().expect("present");
        assert_eq!(term.present_count(), 1);
        term.present().expect("present");
        assert_eq!(term.present_count(), 2);
    }

    // ── handle_redraw_requested / unrecoverable (`is_recoverable() == false`) errors ─────────

    type FatalApp = WindowApp<
        FatalPresenter,
        fn(&mut Terminal<WindowBackend<FatalPresenter>>),
        u64,
        fn(u64, &mut Terminal<WindowBackend<FatalPresenter>>),
    >;

    fn fatal_app() -> (FatalApp, Rc<Cell<bool>>, Rc<Cell<u32>>) {
        let failing = Rc::new(Cell::new(false));
        let init_surface_calls = Rc::new(Cell::new(0));
        let presenter = FatalPresenter {
            failing: failing.clone(),
            init_surface_calls: init_surface_calls.clone(),
        };
        let terminal = Terminal::new(WindowBackend::new(presenter));
        let app: FatalApp = WindowApp {
            terminal: Some(terminal),
            app_loop: (|_| {}) as fn(&mut Terminal<WindowBackend<FatalPresenter>>),
            on_custom_event: push_custom_event,
            _user_event: PhantomData,
            window: None,
            title: String::new(),
            init_size: InitWindowSize {
                width: 80,
                height: 80,
            },
            attrs: WindowAttrs::default(),
            current_modifiers: KeyModifiers::NONE,
            cursor_px: (0.0, 0.0),
            active_touch: None,
            held_buttons: 0,
            frame_interval: None,
            event_driven: true,
            #[cfg(not(target_arch = "wasm32"))]
            next_frame: std::time::Instant::now(),
            exit_requested: Rc::new(Cell::new(false)),
            skip_present: Rc::new(Cell::new(false)),
            needs_redraw: false,
            consecutive_present_errors: 0,
        };
        (app, failing, init_surface_calls)
    }

    #[test]
    fn unrecoverable_present_failure_never_attempts_recovery_even_past_the_threshold() {
        // Unlike `FailingPresenter` (recoverable errors, generic threshold-based recovery), a
        // `FatalPresenter` failure is fatal on every single call: `present_failure_action`
        // returns `Fatal` immediately (see the pure-function tests above), so
        // `handle_redraw_requested` must never route it through `try_recover_surface`, no matter
        // how many consecutive failures accumulate past `PRESENT_FAILURE_RECOVERY_THRESHOLD`.
        let (mut app, failing, init_calls) = fatal_app();
        failing.set(true);
        for _ in 0..2 * PRESENT_FAILURE_RECOVERY_THRESHOLD {
            app.handle_redraw_requested();
        }
        assert_eq!(init_calls.get(), 0);
    }

    #[test]
    fn unrecoverable_present_failure_does_not_panic_and_keeps_counting() {
        let (mut app, failing, _init_calls) = fatal_app();
        failing.set(true);
        for _ in 0..5 {
            app.handle_redraw_requested();
        }
        assert_eq!(app.consecutive_present_errors, 5);
    }

    #[test]
    fn recovering_from_an_unrecoverable_failure_streak_still_resets_the_counter() {
        let (mut app, failing, _init_calls) = fatal_app();
        failing.set(true);
        for _ in 0..3 {
            app.handle_redraw_requested();
        }
        assert_eq!(app.consecutive_present_errors, 3);

        failing.set(false);
        app.handle_redraw_requested();
        assert_eq!(app.consecutive_present_errors, 0);
    }
}