quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows 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
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
//! Win-GUI runner: Win32 message loop driving an [`AppLogic`] impl.
//!
//! The runner creates a Win32 window (`RegisterClassEx` + `CreateWindowEx`),
//! initialises a Direct2D render target via [`WinBackend::attach_surface`],
//! enters the message loop, and translates window-lifecycle `WM_*`
//! messages → [`UiEvent`] → `app.handle()`, redrawing via `app.render()`
//! on `WM_PAINT`.
//!
//! Mirrors `quadraui::gtk::run` and `quadraui::tui::run` — consumers
//! call `quadraui::win::run(MyApp::new())` and the same `AppLogic`
//! impl drives every backend. [`run_with`] takes a [`RunConfig`] for the
//! one value a `ShellConfig`-driven consumer needs that [`run`] hardcodes
//! (the window title) — see `win::shell_runner::run_with_shell`,
//! mirroring `gtk::run::RunConfig`.
//!
//! # Window chrome: standard frame, not CSD — `desktop::WindowDragArm` N/A
//!
//! `create_window` creates its window with `WS_OVERLAPPEDWINDOW` (below) —
//! the standard Windows title bar, system menu, and non-client resize
//! border, not a client-side-decorated one quadraui paints itself.
//! Title-bar drag-to-move and edge-resize are therefore already handled
//! entirely by Windows' own non-client (`WM_NC*`) message processing
//! before this `wndproc` ever sees them, the same way GTK's `gtk4::
//! WindowHandle`/edge-resize gesture needs [`crate::desktop::WindowDragArm`]
//! specifically *because* GTK's `DrawingArea`-filled window has no native
//! frame to delegate to. #702's audit considered adopting
//! `WindowDragArm` here and concluded it doesn't apply for exactly this
//! reason — see that type's doc comment for the fuller rationale. This
//! is a deliberate "not applicable", not an unfinished gap: adopt it only
//! if a future issue gives `win::run` a custom (CSD-style) frame.
//!
//! # Scope
//!
//! Issue #19 landed the window + render-target *bootstrap* and exactly
//! the three window-lifecycle events the message loop itself needs to
//! stay alive and responsive: `WM_SIZE` → [`UiEvent::WindowResized`],
//! `WM_DPICHANGED` → [`UiEvent::DpiChanged`], `WM_CLOSE` →
//! [`UiEvent::WindowClose`]. Issue #20 adds the rest of the input table
//! this `wndproc` dispatches: mouse buttons/motion/wheel, `WM_KEYDOWN` +
//! `WM_CHAR`, and focus — decoded by [`super::msg`], translated by
//! [`super::events`]. Issue #743 adds `WM_SYSKEYDOWN` + `WM_SYSCHAR` (the
//! Alt-held twins of `WM_KEYDOWN`/`WM_CHAR` — Alt+F4, menu mnemonics,
//! app-registered Alt accelerators), reusing the exact same translators —
//! see the `WM_SYSKEYDOWN`/`WM_SYSCHAR` arms below for the Alt+F4
//! dispatch-vs-`DefWindowProcW` decision. `WM_KEYUP`/`WM_SYSKEYUP` and the
//! double-click family remain unhandled (no quadraui `UiEvent` counterpart
//! exists yet for the former pair; see `super::events`' module docs for
//! the latter).
//!
//! # Dispatch model: direct, not `poll_events`/`wait_events`
//!
//! A Win32 message loop is callback-driven (`DispatchMessageW` calls
//! `WndProc` synchronously), not poll-driven like the TUI runner's
//! `wait_events(timeout)`. This mirrors the GTK runner: GTK's live
//! signal handlers call `dispatch_event`/`app.handle` directly from
//! each signal callback rather than routing through
//! `Backend::poll_events` (see `gtk::run`'s module docs, "single-DA
//! model"); `Backend::poll_events`/`wait_events` exist as a
//! forward-compat seam for future headless-driver parity, not as this
//! runner's hot path.
//!
//! quadraui#806 gave `WinBackend::poll_events`/`wait_events` a real
//! `docs/BACKEND.md` queue-adapter implementation — draining
//! `WinBackend::events`, non-panicking — instead of the `todo!()` stubs
//! that made any polling caller (a headless driver, quadraui#785's
//! shared `DriverCore`, quadraweb) crash. This `wndproc` still does not
//! feed that queue: it keeps calling [`dispatch_event`]/`app.handle`
//! directly per message, same as before, and the two paths are mutually
//! exclusive today (nothing both runs a live window through this
//! function *and* polls the same `WinBackend` for events). Wiring
//! `wndproc` to also push translated events onto `WinBackend::events`
//! (`events_handle`/`push_event`) so a future consumer can observe the
//! live pump through the adapter — the way `docs/BACKEND.md` describes
//! GTK's signal handlers eventually doing — is follow-up work, not
//! required to stop the panic this issue was filed for.
//!
//! # Per-window state without closures
//!
//! `WndProc` must be a plain `extern "system" fn` — it cannot capture
//! `app`/`backend` as a closure. `WindowState` (wrapping `RunState` in a
//! `RefCell`, alongside a reentrancy-guard counter — see "Reentrancy
//! guard" below) is heap-allocated once via `Box::into_raw` *before*
//! `CreateWindowExW` runs, and its address is
//! threaded through as `CreateWindowExW`'s last parameter
//! (`lpCreateParams`), which Windows hands back inside `WM_NCCREATE`'s
//! `CREATESTRUCTW`. `wndproc::<A>` stashes that pointer in
//! `GWLP_USERDATA` on `WM_NCCREATE` and reads it back on every
//! subsequent message — the same raw-pointer-in-`GWLP_USERDATA` pattern
//! every Win32 Rust binding uses, since the OS API predates closures by
//! three decades.
//!
//! `wndproc::<A>` is a generic function monomorphized once per
//! concrete `A: AppLogic` — each instantiation is a distinct
//! `extern "system" fn` with its own address, so `RegisterClassExW`
//! (which needs one concrete function pointer) can register the right
//! one for whatever app type `run::<A>` was called with.
//!
//! # Reentrancy guard
//!
//! `wndproc` dispatches `app.handle`/`app.render` while holding
//! `WindowState::state`'s `RefCell` borrow. A `wndproc` invoked by
//! `DispatchMessageW` never nests directly, but a *synchronous* native
//! re-entry onto this same thread is possible — a future `AppLogic` that
//! shows a native modal (which internally pumps messages) or
//! `SendMessage`s its own `hwnd` from inside `handle`/`render` — and
//! would otherwise double-borrow the same `RefCell` and panic (quadraui
//! #702, following up on #498/#427, which hit the identical hazard in
//! `gtk::services`'s async-dialog pump first). [`guarded_call`] plus the
//! `ws.pump_depth.is_pumping()` check at the top of `wndproc` close it:
//! [`crate::desktop::ModalPumpDepth`]/[`crate::desktop::ModalPumpGuard`]
//! (extracted backend-neutral by #498) track whether a guarded call is
//! already in flight, and a reentrant message is ceded to
//! `DefWindowProcW` rather than ever touching `WindowState::state`.
//! [`guarded_call`] itself has no WinAPI dependency, so it — and the
//! double-borrow scenario it prevents — are unit-tested off Windows; see
//! the `tests` module below.
//!
//! Ceding a *message* this way is safe for input — the next one simply
//! arrives later — but `WM_SIZE`/`WM_DPICHANGED` are one-shot state
//! notifications with no later arrival to fall back on:
//! `ShowWindow(SW_MAXIMIZE)`, called synchronously from
//! `WinBackend::toggle_window_maximize` inside a guarded `app.handle`,
//! sends `WM_SIZE` re-entrantly, and ceding it outright left the render
//! target stretched over the new client area with stale hit-testing.
//! `WindowState::pending_resize_resync` plus `win32::resync_pending_resize`
//! close that gap: the top-of-`wndproc` check records the ceded
//! notification instead of dropping it, and the next non-reentrant
//! `wndproc` call replays it — via `GetClientRect`, since the original
//! `lparam` is long gone — before doing its own work.
//!
//! # Headless smoke mode (#702, adopting `desktop::SmokeConfig`)
//!
//! Mirrors `gtk::run`'s "Headless smoke mode" (quadraui#450, GD-5): two
//! environment variables, read once at startup via
//! [`crate::desktop::SmokeConfig::from_env`], let any `win_*` example run
//! unattended and exit with a deterministic, checkable status instead of
//! sitting in the message loop forever waiting for a user who isn't
//! there.
//!
//! - `QUADRAUI_WIN_SMOKE_MS=<u64>` — enables smoke mode. `after_ms`
//!   milliseconds after the window is shown, a one-shot `WM_TIMER`
//!   (`win32::SMOKE_TIMER_ID`) fires `win32::run_smoke_check`, which
//!   checks the client area's size against a sane floor
//!   ([`crate::desktop::smoke_size_ok`] — the same #437 tiny-window
//!   regression class GTK's smoke lane guards against), then closes the
//!   window.
//! - `QUADRAUI_WIN_SMOKE_PASTE=<text>` — optional. If set, the same timer
//!   round-trips `<text>` through the real OS clipboard
//!   (`WinPlatformServices::clipboard()`, the same object the live Ctrl-V
//!   handler below reads) and checks it byte-for-byte via
//!   [`crate::desktop::smoke_clipboard_round_trip_ok`], then — since
//!   #728 gave `dispatch_event` a real Ctrl-V → `ClipboardPaste`
//!   interception path — dispatches a synthetic Ctrl-V `KeyPressed`
//!   through it, mirroring `gtk::run::schedule_smoke_check`'s identical
//!   round-trip-then-replay sequence. Note this replay's `dispatch`
//!   return value is never inspected here (same as GTK's equivalent
//!   fire-and-forget call) — it exercises the interception code path so
//!   a panic there would fail the smoke, but on its own it cannot tell
//!   "recognised as paste" apart from "fell through to `app.handle`
//!   unchanged," since nothing asserts on the outcome. Real coverage of
//!   `is_paste_keypress` matching is `crate::desktop`'s pure-predicate
//!   unit tests, not this smoke check.
//!
//! Any assertion failure is printed to stderr (`win32::run_smoke_check`
//! is exempted from the crate-wide `print_stderr` deny for the same
//! reason `gtk::run`'s equivalent is) and flips [`run`]'s
//! [`std::process::ExitCode`] to [`std::process::ExitCode::FAILURE`].
//! Disabled (zero runtime cost — no timer is ever armed) unless
//! `QUADRAUI_WIN_SMOKE_MS` is set.

use crate::backend::Backend;
use crate::event::{Point, Viewport};
use crate::primitives::image::ImageSource;
use crate::runner::AppLogic;
// `EventOutcome` — what the caller should do after `dispatch_event`
// handles one event — is defined once in `crate::runtime` and shared by
// every backend runner; re-exported (not just imported)
// so `win::testing` reaches it through this path, mirroring
// `tui::run`/`macos::run`.
pub(crate) use crate::runtime::EventOutcome;
// `StepOutcome` — what happened during one non-blocking `step`/`pump`
// call — is defined once in `crate::runner` and shared by every
// backend's embedding-friendly runner (`WinRunner` here, `TuiRunner` on
// TUI, `crate::gtk::run::GtkRunner` on GTK), the same way `Reaction`
// already is; re-exported (not just imported) so existing in-crate
// callers that reach it through this module keep working. Deliberately
// *not* `target_os`-gated: `StepOutcome` itself is a plain enum with no
// WinAPI dependency, so this compiles identically on every host even
// though `WinRunner` (the type that actually produces one) only exists
// inside `mod win32` below.
pub use crate::runner::StepOutcome;
use crate::win::backend::WinBackend;
use crate::{ButtonMask, Modifiers, MouseButton, UiEvent};

/// Dispatch one already-translated [`UiEvent`] through the app, applying
/// the shared runner pre-processing pipeline first. This is the funnel
/// both the live `wndproc`'s `dispatch` helper (`mod win32`, below) and
/// [`super::testing::WinDriver`] route through, so a test
/// exercises the exact pre-processing a real keypress gets.
///
/// The pre-processing itself — double-click folding, ActivityBar
/// keyboard-focus redirect, Tab/Shift+Tab focus cycling,
/// global accelerator rewrite, Ctrl-C copy,
/// Ctrl-V/Ctrl-Shift-V paste, middle-click PRIMARY-selection paste
/// (a no-op on Windows — see
/// [`crate::backend::Clipboard::read_primary_selection`]'s default),
/// Ctrl-A select-all, selection-display clearing, `TextSelectionChanged`
/// — lives in [`crate::runtime::preprocess_event`], shared
/// with TUI/GTK/macOS; see that function's doc for the exact priority
/// order.
///
/// Not `target_os`-gated: none of `WinBackend`'s `PreprocessBackend`
/// methods touch Direct2D/Win32 directly (they read plain `Option`/`Vec`
/// fields populated by `register_accelerator`/`draw_activity_bar`, or
/// forward to `dispatch::DoubleClickDetector`/`text_selection`, neither
/// of which has a WinAPI dependency), so this compiles and behaves
/// identically on every host — same "compiles everywhere" posture as
/// [`RunConfig`] above. The paste/middle-click steps keep that posture
/// too: `WinPlatformServices::clipboard()`'s `read_text()`/
/// `read_primary_selection()` are real Win32 clipboard reads under
/// `target_os = "windows"` and an unconditional `None` everywhere else
/// (see `win::services`'s `Clipboard` impl), so off-Windows those arms
/// always fall through to `EventOutcome::Continue` with nothing
/// forwarded to the app — never a compile-time or behavioral surprise on
/// the `ubuntu-latest` `--features win` leg.
///
/// `#[allow(dead_code)]`: this function's only callers — `mod win32`'s
/// live `wndproc`/`dispatch` and [`super::testing::WinDriver`] — are both
/// `#[cfg(target_os = "windows")]`-gated (the former directly, the
/// latter because `mod testing` only exists on Windows — see
/// `win::mod`'s doc). On a non-Windows host (`cargo check`/`cargo test
/// --features win` on the `ubuntu-latest` CI leg) neither caller exists,
/// so without this it — and everything it calls in turn
/// (`WinBackend::focused_activity_bar_id`/`match_keypress`,
/// `key_to_activity_bar_string`, `EventOutcome`) — would trip `-D
/// warnings`' dead-code lint on that leg despite being genuinely used on
/// the `windows-latest` leg where it matters.
///
/// # Panic safety
///
/// This is the one funnel every message `wndproc` dispatches to
/// `app.handle` passes through (directly, or via
/// [`route_mouse_down`]/[`route_mouse_move`]/[`route_mouse_up`] below,
/// which call back into this same function). `wndproc` is a Win32
/// `WNDPROC` — a C ABI callback that cannot unwind — so a panic
/// anywhere in `preprocess_event`/`app.handle` (an app bug, or a
/// `WinBackend` rasteriser's reachable `todo!()`) would otherwise
/// escalate straight to `abort()` instead of staying a recoverable
/// panic (see the module-level issue this closes: quadraui#922,
/// following the real-world vimcode#896 incident on macOS's equivalent
/// unguarded boundary). `catch_unwind` here converts that into "this one
/// event is dropped, everything else keeps running": on a caught panic,
/// `backend`/`app` may be left in a partially-mutated state (unavoidable
/// — that's what makes catching correct instead of merely convenient,
/// not a claim that the state is fine), but no `BeginDraw`/`EndDraw`
/// bracket is open at this call site (that's [`render_frame`]'s
/// concern), so there is nothing here that needs unwinding to leave
/// balanced. `AssertUnwindSafe` is required because `backend: &mut
/// WinBackend` is not `UnwindSafe` — see [`crate::desktop::report_caught_panic_once`]'s
/// doc for the once-per-site reporting this uses instead of logging
/// every single frame's re-panic.
///
/// # Caret-blink bump
///
/// Any `KeyPressed`/`CharTyped` calls [`WinBackend::note_caret_activity`]
/// first, holding the `MultiSectionView` aux-row caret solid for the
/// typing-pause window — mirrors `gtk::run::dispatch_event`'s identical
/// bump. The recurring blink timer that ticks the caret while idle is
/// `CARET_BLINK_TIMER_ID`, armed once by `win32::create_window`.
#[allow(dead_code)]
pub(crate) fn dispatch_event<A: AppLogic>(
    event: UiEvent,
    backend: &mut WinBackend,
    app: &mut A,
) -> EventOutcome {
    if matches!(event, UiEvent::KeyPressed { .. } | UiEvent::CharTyped(_)) {
        backend.note_caret_activity(std::time::Instant::now());
    }
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        crate::runtime::preprocess_event(event, backend, app)
    })) {
        Ok(outcome) => outcome,
        Err(payload) => {
            crate::desktop::report_caught_panic_once(
                "win::run::dispatch_event (app.handle)",
                payload.as_ref(),
            );
            EventOutcome::Continue
        }
    }
}

/// Route a `MouseDown` through the shared pointer-routing pipeline
/// ([`crate::dispatch::route_pointer`], issue #1088) before handing the
/// resulting event(s) to [`dispatch_event`] — the Win-GUI twin of
/// `gtk::run`'s `connect_pressed` closure / `TuiBackend::apply_dispatch`'s
/// `MouseDown` arm. `route_pointer` also tracks the clicked region
/// so Ctrl-A can resolve it even before the first drag-move fires a
/// `TextSelectionChanged` event.
///
/// Not itself `#[cfg(target_os = "windows")]`: same posture as
/// [`dispatch_event`] — its only callers (`mod win32`'s `WM_*BUTTONDOWN`
/// handler and `super::testing::WinDriver::mouse_down`) are both
/// windows-gated, so this stays `#[allow(dead_code)]` on every other host
/// rather than cfg-gated, keeping it type-checked (and unit-testable,
/// below) everywhere — see `dispatch_event`'s doc for the identical
/// rationale.
#[allow(dead_code)]
pub(crate) fn route_mouse_down<A: AppLogic>(
    backend: &mut WinBackend,
    app: &mut A,
    position: Point,
    button: MouseButton,
    modifiers: Modifiers,
) -> EventOutcome {
    let events = {
        let stack_rc = backend.modal_stack_handle();
        let drag_rc = backend.drag_state_handle();
        let stack = stack_rc.borrow();
        let mut drag = drag_rc.borrow_mut();
        crate::dispatch::route_pointer(
            &stack,
            &mut drag,
            backend.text_selection_state_mut(),
            UiEvent::MouseDown {
                widget: None,
                button,
                position,
                modifiers,
            },
        )
    };

    let mut outcome = EventOutcome::Continue;
    for ev in events {
        let step = dispatch_event(ev, backend, app);
        if matches!(step, EventOutcome::Exit) {
            return EventOutcome::Exit;
        }
        // Keep the *earliest* `RedrawAfter` deadline seen in
        // this batch rather than the first non-`Continue` one — see
        // `EventOutcome::merge`'s doc for why that distinction matters.
        outcome = outcome.merge(step);
    }
    outcome
}

/// Route a `MouseMoved` (button held) through
/// [`crate::dispatch::route_pointer`] so a `TextSelection`/scrollbar
/// drag armed by [`route_mouse_down`] emits `TextSelectionChanged`/
/// scroll events — the Win-GUI twin of `gtk::run`'s motion-controller
/// closure. See [`route_mouse_down`]'s doc for why this isn't
/// `#[cfg(target_os = "windows")]`-gated.
#[allow(dead_code)]
pub(crate) fn route_mouse_move<A: AppLogic>(
    backend: &mut WinBackend,
    app: &mut A,
    position: Point,
    buttons: ButtonMask,
) -> EventOutcome {
    let events = {
        let stack_rc = backend.modal_stack_handle();
        let drag_rc = backend.drag_state_handle();
        let stack = stack_rc.borrow();
        let mut drag = drag_rc.borrow_mut();
        crate::dispatch::route_pointer(
            &stack,
            &mut drag,
            backend.text_selection_state_mut(),
            UiEvent::MouseMoved { position, buttons },
        )
    };

    let mut outcome = EventOutcome::Continue;
    for ev in events {
        let step = dispatch_event(ev, backend, app);
        if matches!(step, EventOutcome::Exit) {
            return EventOutcome::Exit;
        }
        // Keep the *earliest* `RedrawAfter` deadline seen in
        // this batch rather than the first non-`Continue` one — see
        // `EventOutcome::merge`'s doc for why that distinction matters.
        outcome = outcome.merge(step);
    }
    outcome
}

/// Route a `MouseUp` through [`crate::dispatch::route_pointer`] (issue
/// #1088) so an in-progress scrollbar/text-selection drag ends cleanly —
/// the Win-GUI twin of `gtk::run`'s `connect_released` closure. See
/// [`route_mouse_down`]'s doc for why this isn't
/// `#[cfg(target_os = "windows")]`-gated.
#[allow(dead_code)]
pub(crate) fn route_mouse_up<A: AppLogic>(
    backend: &mut WinBackend,
    app: &mut A,
    position: Point,
    button: MouseButton,
) -> EventOutcome {
    let events = {
        let stack_rc = backend.modal_stack_handle();
        let drag_rc = backend.drag_state_handle();
        let stack = stack_rc.borrow();
        let mut drag = drag_rc.borrow_mut();
        crate::dispatch::route_pointer(
            &stack,
            &mut drag,
            backend.text_selection_state_mut(),
            UiEvent::MouseUp {
                widget: None,
                button,
                position,
            },
        )
    };

    let mut outcome = EventOutcome::Continue;
    for ev in events {
        let step = dispatch_event(ev, backend, app);
        if matches!(step, EventOutcome::Exit) {
            return EventOutcome::Exit;
        }
        // Keep the *earliest* `RedrawAfter` deadline seen in
        // this batch rather than the first non-`Continue` one — see
        // `EventOutcome::merge`'s doc for why that distinction matters.
        outcome = outcome.merge(step);
    }
    outcome
}

/// Render one frame: `begin_frame` + `app.render` + `end_frame` — the
/// exact body `mod win32`'s `WM_PAINT` handler used to run inline,
/// extracted so it never depends on a live `HWND`, only a [`WinBackend`]
/// with *some* surface attached (a real one via
/// [`WinBackend::attach_surface`], or a headless one via
/// [`WinBackend::attach_headless`]). Shared by the live runner and
/// [`super::testing::WinDriver`] — mirrors
/// [`crate::gtk::run::render_frame`] / [`crate::macos::run::render_frame`].
///
/// `#[allow(dead_code)]`: same reasoning as [`dispatch_event`]'s doc —
/// both its callers only exist on `target_os = "windows"`.
///
/// # Panic safety
///
/// `WM_PAINT`'s handler in `mod win32` runs this from inside `wndproc` —
/// a Win32 `WNDPROC`, a C ABI callback that cannot unwind — so `app.render`
/// (arbitrary consumer code, or a `WinBackend` rasteriser's reachable
/// `todo!()`) is wrapped in its own `catch_unwind` rather than being
/// allowed to unwind through that boundary into `abort()` (quadraui#922,
/// following the vimcode#896 incident on macOS's equivalent unguarded
/// `drawRect:`). A caught panic skips the rest of this frame — no focus
/// ring, no selection highlight, both of which read state a panicking
/// `render` may have left inconsistent — but `backend.end_frame()` below
/// still always runs, so the `BeginDraw`/`EndDraw` bracket
/// `backend.begin_frame` opened above stays balanced for the next
/// `WM_PAINT` regardless of whether this one panicked.
#[allow(dead_code)]
pub(crate) fn render_frame<A: AppLogic>(backend: &mut WinBackend, app: &A, viewport: Viewport) {
    backend.begin_frame(viewport);
    let rendered = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        app.render(&mut *backend, Default::default());
    }));
    if let Err(payload) = rendered {
        crate::desktop::report_caught_panic_once(
            "win::run::render_frame (app.render)",
            payload.as_ref(),
        );
        backend.end_frame();
        return;
    }
    // After app.render: paint the focus-ring convention — mirrors
    // the other three runners' post-render overlay ordering.
    // `focused_stop_rect` is the one implementation of this
    // lookup; every runner used to carry its own copy.
    let focus_ring_rect =
        crate::runtime::focused_stop_rect(backend, app, <A as AppLogic>::AreaId::default());
    if let Some(rect) = focus_ring_rect {
        backend.draw_focus_ring(rect);
    }
    // After app.render: overlay the text-selection highlight on top of the
    // rendered content — mirrors `gtk::run::render_frame`'s
    // `apply_selection_highlight(cr)` call and `TuiBackend::run`'s
    // `apply_selection_highlight(buf)` call, both made at this same point
    // in the frame.
    backend.apply_selection_highlight();
    backend.end_frame();
}

/// Configuration for [`run_with`]: the window title [`run`] hardcodes to
/// a generic default (`"quadraui"`).
///
/// A `ShellConfig`-driven consumer (`win::shell_runner::run_with_shell`)
/// needs its own window title to reach the real Win32 window instead of
/// always showing `"quadraui"` — mirrors `gtk::run::RunConfig`, minus the
/// GTK-specific `app_id`/`icon_name` fields Win32 has no equivalent
/// concept for.
///
/// Deliberately *not* `#[cfg(target_os = "windows")]`: it must type-check
/// under a plain `cargo check --features win` on Linux, since
/// `win::shell_runner::run_with_shell` constructs one unconditionally
/// (same "compiles everywhere, only *works* on Windows" posture as the
/// rest of `src/win/` — see `Cargo.toml`'s `win`-example comments).
///
/// ## Downstream impact (CLAUDE.md rule 8): `single_instance` field
///
/// `RunConfig` is a plain, all-`pub`-field struct with no
/// `#[non_exhaustive]`, so adding [`Self::single_instance`] is only safe
/// if no consumer builds one with an exhaustive struct literal. Blast
/// radius, per CLAUDE.md's mandatory rule 1:
///
/// ```text
/// $ grep -rn 'RunConfig' ~/src/coord-tui/src ~/src/vimcode/src
/// (no output — zero hits in both)
/// ```
///
/// Both consumers reach this backend exclusively through
/// `run_with_shell(app, ShellConfig)` (`shell_runner`), which builds its
/// own `RunConfig` internally — neither consumer constructs or names
/// `win::RunConfig` at all. Adding this field is a no-op for both.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RunConfig {
    /// Window title shown by the title bar, taskbar, and Alt-Tab switcher.
    ///
    /// Encoded as a `\0`-terminated wide string before reaching Win32
    /// (see `create_window`'s `title_nul`) — an embedded `'\0'` character in
    /// this string silently truncates the displayed title at that point
    /// rather than erroring, since Win32 treats the first NUL as the
    /// terminator. Not a concern for any title a real app would set, but
    /// worth knowing if this is ever built from untrusted input.
    pub title: String,
    /// Whether a second launch of this app is forwarded to the
    /// already-running instance instead of opening a second window.
    /// `false` (the default — see [`Self::default`]) reproduces every
    /// pre-single-instance launch: one independent window per process.
    ///
    /// When `true`, `run`/`run_with` creates a named `CreateMutexW`
    /// keyed off [`Self::title`] (Win has no `app_id` concept the way
    /// `gtk::RunConfig` does, so the title doubles as this backend's
    /// stable app identity) before opening a window. If that mutex
    /// already exists — another instance of this same app is already
    /// running — this process forwards its own `argv` to the existing
    /// instance's window via `WM_COPYDATA`, brings that window to the
    /// foreground, and exits without ever creating a window of its own.
    /// The receiving instance decodes the forwarded `argv` the same way
    /// it decodes its own at startup — through
    /// [`crate::event::classify_open_args`] — and dispatches the result
    /// as [`crate::UiEvent::OpenRequested`].
    ///
    /// The registered window class (what `FindWindowW` searches by to
    /// locate that existing instance's window) is scoped by this same
    /// `title` too — via a hash, not `title` embedded verbatim, see
    /// `instance_identity`'s doc comment in `win/run.rs` — so two
    /// different-titled quadraui apps running at once never collide on
    /// either name.
    pub single_instance: bool,
    /// App icon applied to the window's titlebar and taskbar entry via
    /// `WM_SETICON` (`ICON_BIG` + `ICON_SMALL`) — issue #1142. `None`
    /// (the default) reproduces every pre-#1142 launch: no icon set,
    /// same as before this field existed. Set via
    /// [`Self::with_app_icon`]; a `ShellConfig`-driven consumer reaches
    /// this through [`crate::shell::ShellConfig::with_app_icon`] via
    /// `win::shell_runner::run_with_shell`.
    pub app_icon: Option<ImageSource>,
}

impl RunConfig {
    /// Build a config with the given window title. Single-instance
    /// forwarding is off — see [`Self::with_single_instance`] to opt in.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            single_instance: false,
            app_icon: None,
        }
    }

    /// Opt in/out of single-instance dedup + `WM_COPYDATA` `argv`
    /// forwarding — see [`Self::single_instance`]'s doc for
    /// the full contract. Defaults to `false`.
    pub fn with_single_instance(mut self, single_instance: bool) -> Self {
        self.single_instance = single_instance;
        self
    }

    /// Set the window/taskbar icon applied via `WM_SETICON` — see
    /// [`Self::app_icon`].
    pub fn with_app_icon(mut self, icon: ImageSource) -> Self {
        self.app_icon = Some(icon);
        self
    }
}

impl Default for RunConfig {
    /// Mirrors [`run`]'s previously-hardcoded window title, so
    /// `run_with(app, RunConfig::default())` and `run(app)` behave
    /// identically.
    fn default() -> Self {
        Self {
            title: "quadraui".to_string(),
            single_instance: false,
            app_icon: None,
        }
    }
}

/// Encode `args` as a `WM_COPYDATA` payload body: joined on
/// `'\0'`, not `'\n'` — a NUL byte can never appear inside a real `argv`
/// entry on any platform (C-style `argv` strings are themselves
/// NUL-terminated), whereas `'\n'` is a legal, if unusual, path
/// character. [`decode_copydata_argv`] is this function's inverse.
///
/// Pure string joining, no WinAPI dependency, so it's unit-tested off
/// Windows below.
///
/// `#[allow(dead_code)]`: this function's only caller,
/// `forward_argv_to_existing_instance`, is `#[cfg(target_os =
/// "windows")]`-gated (it lives inside `mod win32`), so on a non-Windows
/// host (`cargo check`/`cargo test --features win` on the
/// `ubuntu-latest` CI leg) it has no caller and would trip `-D warnings`'
/// dead-code lint despite being genuinely used on the `windows-latest`
/// leg — same rationale as [`dispatch_event`]'s identical attribute
/// above.
#[allow(dead_code)]
fn encode_copydata_argv(args: &[String]) -> String {
    args.join("\0")
}

/// Inverse of [`encode_copydata_argv`]: splits a decoded `WM_COPYDATA`
/// payload body back into the original `argv` entries. Trims trailing
/// NUL(s) first — `forward_argv_to_existing_instance` appends one
/// defensively even though `cbData`'s exact byte count means Win32
/// doesn't strictly need it — then drops any empty entry a trailing
/// separator would otherwise turn into a bogus empty path.
///
/// Pure string splitting, no WinAPI dependency, so it's unit-tested off
/// Windows below.
///
/// `#[allow(dead_code)]`: same rationale as [`encode_copydata_argv`] —
/// its only caller (`wndproc`'s `WM_COPYDATA` arm) is Windows-only.
#[allow(dead_code)]
fn decode_copydata_argv(payload: &str) -> Vec<String> {
    payload
        .trim_end_matches('\0')
        .split('\0')
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .collect()
}

/// Prefix for [`window_class_name_string`]'s per-title window class name.
const CLASS_NAME_PREFIX: &str = "QuadrauiWin32WindowClass";

/// A deterministic identity derived from `RunConfig::title`, shared
/// by the single-instance mutex and the window class name
/// ([`window_class_name_string`]). This ensures both names are
/// locked together by construction — two different quadraui-based
/// apps running at once never collide on either name.
///
/// A hash (rather than embedding `title` verbatim in the class name)
/// sidesteps Win32's ~256-character class-name limit and any
/// characters in an arbitrary title that Win32 class names can't
/// carry, and sidesteps the embedded-`\`/embedded-`\0` mutex
/// namespace hazard [`RunConfig::title`]'s doc flags too.
///
/// `DefaultHasher`'s `SipHash` keys have been fixed (not
/// process-randomized) since Rust 1.36, so this is deterministic
/// across the two separate process launches that need to agree on
/// it. It is *not* guaranteed stable across different Rust/std
/// versions — irrelevant here, since both launches being compared
/// are always the same build of the same binary.
///
/// Pure hashing, no WinAPI dependency, so it's unit-tested off
/// Windows below.
fn instance_identity(title: &str) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    title.hash(&mut hasher);
    hasher.finish()
}

/// Window class name for `title`'s instance family — see
/// [`instance_identity`]. Not `\0`-terminated or wide-encoded; callers in
/// `mod win32` do both before handing this to `lpszClassName`/
/// `FindWindowW`.
///
/// Pure string formatting, no WinAPI dependency, so it's unit-tested off
/// Windows below.
///
/// `#[allow(dead_code)]`: same rationale as [`encode_copydata_argv`] —
/// its only callers (`win32::create_window`'s `RegisterClassExW` and
/// `win32::forward_argv_to_existing_instance`'s `FindWindowW`) are
/// Windows-only.
#[allow(dead_code)]
fn window_class_name_string(title: &str) -> String {
    format!("{CLASS_NAME_PREFIX}-{:016x}", instance_identity(title))
}

// `ModalPumpDepth`/`ModalPumpGuard`/`RefCell` are only reachable from
// `guarded_call` and its test module below — both `#[cfg(any(target_os
// = "windows", test))]`, matching `win32`'s own `target_os = "windows"`
// gate plus an off-Windows `test`-only carve-out (see `guarded_call`'s
// doc for why it, unlike `win32`, is unit-testable off Windows). Gating
// these imports identically avoids an unresolved-import error on a
// plain, non-test `cargo check --features win` build on a non-Windows
// host, where neither `guarded_call` nor `win32::dispatch` exist to
// consume them.
#[cfg(any(target_os = "windows", test))]
use crate::desktop::{ModalPumpDepth, ModalPumpGuard};
#[cfg(any(target_os = "windows", test))]
use std::cell::RefCell;

/// Runs `f` against a mutable borrow of `*state`, guarded by
/// `pump_depth` against the `wndproc` reentrancy hazard this module used
/// to just document rather than close (#702, following up on #498): if
/// `pump_depth` already shows a guarded call in flight on this thread —
/// i.e. something reachable from `f` re-enters this same call path
/// synchronously, the way `win32::dispatch`'s doc comment describes a
/// future `AppLogic` pumping a native modal or `SendMessage`ing its own
/// `hwnd` from inside `handle` — this returns `None` *without ever
/// taking `state`'s `RefCell` borrow*, instead of panicking on a double
/// `borrow_mut()`.
///
/// Pure `RefCell`/[`ModalPumpDepth`] logic with no WinAPI dependency of
/// its own, so — unlike its production caller, `win32::dispatch`
/// (Windows-only, since `wndproc` itself is) — this is unit-testable off
/// Windows; see the `tests` module below for a from-scratch reproduction
/// of the double-borrow panic this guards against.
#[cfg(any(target_os = "windows", test))]
fn guarded_call<T, R>(
    state: &RefCell<T>,
    pump_depth: &ModalPumpDepth,
    f: impl FnOnce(&mut T) -> R,
) -> Option<R> {
    if pump_depth.is_pumping() {
        return None;
    }
    let _guard = ModalPumpGuard::new(pump_depth);
    Some(f(&mut state.borrow_mut()))
}

#[cfg(target_os = "windows")]
mod win32 {
    use std::cell::{Cell, RefCell};
    use std::ffi::c_void;
    use std::mem::size_of;
    use std::rc::Rc;
    use std::time::{Duration, Instant};

    use windows::core::{Error as WinError, PCWSTR};
    use windows::Win32::Foundation::{
        GetLastError, ERROR_ALREADY_EXISTS, HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM,
    };
    use windows::Win32::Graphics::Gdi::{
        InvalidateRect, ScreenToClient, UpdateWindow, ValidateRect,
    };
    // `WM_COPYDATA`'s payload struct lives in `System::DataExchange`,
    // not `WindowsAndMessaging` (the message id itself, and every other
    // API this feature needs — `FindWindowW`/`SendMessageW`/
    // `SetForegroundWindow`/`SW_RESTORE` — do).
    use windows::Win32::System::DataExchange::COPYDATASTRUCT;
    use windows::Win32::System::LibraryLoader::GetModuleHandleW;
    use windows::Win32::System::Threading::CreateMutexW;
    use windows::Win32::UI::HiDpi::{
        SetProcessDpiAwarenessContext, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,
    };
    use windows::Win32::UI::Input::KeyboardAndMouse::{
        GetKeyState, VIRTUAL_KEY, VK_CONTROL, VK_LWIN, VK_MENU, VK_RWIN, VK_SHIFT,
    };
    use windows::Win32::UI::WindowsAndMessaging::{
        CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, FindWindowW,
        GetClientRect, GetWindowLongPtrW, KillTimer, LoadCursorW, MsgWaitForMultipleObjects,
        PeekMessageW, PostQuitMessage, RegisterClassExW, SendMessageW, SetForegroundWindow,
        SetTimer, SetWindowLongPtrW, SetWindowPos, ShowWindow, TranslateMessage, CREATESTRUCTW,
        CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, GWLP_USERDATA, HTCAPTION, HTCLIENT, ICON_BIG,
        ICON_SMALL, IDC_ARROW, MSG, NCCALCSIZE_PARAMS, PM_REMOVE, QS_ALLINPUT, SWP_NOACTIVATE,
        SWP_NOZORDER, SW_RESTORE, SW_SHOW, WINDOW_EX_STYLE, WM_CHAR, WM_CLOSE, WM_COPYDATA,
        WM_DESTROY, WM_DPICHANGED, WM_DROPFILES, WM_KEYDOWN, WM_KILLFOCUS, WM_LBUTTONDOWN,
        WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL,
        WM_NCCALCSIZE, WM_NCCREATE, WM_NCHITTEST, WM_PAINT, WM_QUIT, WM_RBUTTONDOWN, WM_RBUTTONUP,
        WM_SETCURSOR, WM_SETFOCUS, WM_SETICON, WM_SIZE, WM_SYSCHAR, WM_SYSKEYDOWN, WM_TIMER,
        WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_OVERLAPPEDWINDOW,
    };
    // `WM_DROPFILES` decode (`HDROP`, `DragAcceptFiles`/
    // `DragQueryFileW`/`DragQueryPoint`/`DragFinish`) — all real Shell32
    // calls against a live drag session, so (unlike `super::events`'
    // pure translators) this stays inside `mod win32` rather than a
    // cross-platform-testable module.
    use windows::Win32::UI::Shell::{
        DragAcceptFiles, DragFinish, DragQueryFileW, DragQueryPoint, HDROP,
    };

    use crate::backend::Backend;
    use crate::desktop::{
        smoke_clipboard_round_trip_ok, smoke_size_ok, ModalPumpDepth, ModalPumpGuard, SmokeConfig,
    };
    use crate::event::{classify_open_args, UiEvent};
    use crate::primitives::image::ImageSource;
    use crate::runner::{AppLogic, Reaction, StepOutcome};
    use crate::win::backend::WinBackend;
    // Reuses the tray icon's WIC → `HICON` decode for the
    // titlebar/taskbar icon — see [`decode_hicon`]'s doc for why this is
    // a shared pipeline rather than a second decoder.
    use crate::win::tray::decode_hicon;
    // Message → `UiEvent` translation lives in `super::events` so it can
    // be unit-tested off Windows (pure functions over already-decoded
    // ints/floats/bools) — see that module's docs.
    use crate::win::events::{
        win_button_down, win_button_up, win_files_dropped, win_focus_to_uievent, win_modifiers,
        win_mouse_button_for_message, win_mouse_moved, win_wheel_to_uievent, wm_char_to_uievent,
        wm_keydown_to_uievent,
    };
    // Payload decoding lives in `super::msg` so it can be unit-tested off
    // Windows — see that module's docs for why the shifts aren't inlined
    // here.
    use crate::runtime::{ResizeDebouncer, RESIZE_SETTLE};
    use crate::win::msg::{
        dpi_scale_from_wparam, is_repeat_from_lparam, point_from_lparam, size_from_lparam,
        wheel_delta_from_wparam,
    };
    use crate::{ButtonMask, Key, Modifiers};

    use super::RunConfig;

    /// Window class name for `title`'s instance family, wide-encoded and
    /// `\0`-terminated, ready for `lpszClassName`/`FindWindowW`. The pure
    /// identity/formatting logic lives in `super::window_class_name_string`
    /// (unit-tested off Windows below its definition) — this just adds
    /// the Win32-specific encoding, which needs `mod win32`'s own `wide`.
    fn window_class_name(title: &str) -> Vec<u16> {
        wide(&format!("{}\0", super::window_class_name_string(title)))
    }

    /// `COPYDATASTRUCT::dwData` tag identifying an argv-forward payload.
    /// Checked by `wndproc`'s `WM_COPYDATA` arm on receipt so a
    /// `WM_COPYDATA` message from something other than
    /// [`forward_argv_to_existing_instance`] isn't mistaken for one and
    /// acted on as `UiEvent::OpenRequested`. This is a same-process-
    /// family sanity tag, not an authentication mechanism — any local
    /// process that can `FindWindowW` this window can read this constant
    /// from the source and forge a matching one. `WM_COPYDATA` has no
    /// stronger built-in provenance check; see the module docs for the
    /// accepted tradeoff.
    const ARGV_FORWARD_TAG: usize = 0x957;

    /// Seed window size in DIPs, matching the GTK runner's
    /// `DEFAULT_WINDOW_WIDTH`/`HEIGHT`. `WM_SIZE` (fired synchronously
    /// from inside `CreateWindowExW`, then again on every real resize)
    /// immediately corrects `WinBackend`'s viewport to the window's
    /// actual client size.
    const DEFAULT_WIDTH: i32 = 800;
    const DEFAULT_HEIGHT: i32 = 600;

    // ─── Headless smoke mode ────────────────────────────────────────────
    //
    // See the module doc's "Headless smoke mode" section. Env var names
    // mirror GTK's `QUADRAUI_GTK_SMOKE_MS`/`_PASTE` with a `WIN` infix —
    // `SmokeConfig::from_env` is parameterised over the name specifically
    // so a second backend's adoption never collides with GTK's.
    const SMOKE_MS_VAR: &str = "QUADRAUI_WIN_SMOKE_MS";
    const SMOKE_PASTE_VAR: &str = "QUADRAUI_WIN_SMOKE_PASTE";
    /// Comfortably below [`DEFAULT_WIDTH`]/[`DEFAULT_HEIGHT`] so a
    /// normal (even heavily letterboxed) window passes, but still
    /// catches the tiny/wrapped-window regression class.
    const SMOKE_MIN_WIDTH: i32 = 200;
    const SMOKE_MIN_HEIGHT: i32 = 150;
    /// `SetTimer`/`KillTimer`'s `nIDEvent`. Only ever one timer live on a
    /// given `hwnd` in this runner, so any nonzero id is fine — Win32
    /// scopes timer ids per-window, not per-process.
    const SMOKE_TIMER_ID: usize = 1;
    /// `SetTimer`/`KillTimer`'s `nIDEvent` for the resize-settle debounce.
    /// Distinct from [`SMOKE_TIMER_ID`] — Win32 timer ids
    /// are scoped per-`hwnd`, and both can legitimately be armed on the
    /// same window (a headless smoke run that also resizes).
    const RESIZE_TIMER_ID: usize = 2;
    /// `SetTimer`'s `nIDEvent` for the coarse idle-poll safety net — see
    /// [`crate::runtime::IDLE_POLL_CEILING`]'s doc and
    /// [`AppLogic::tick`][crate::runner::AppLogic::tick]'s per-backend
    /// table. Distinct from [`SMOKE_TIMER_ID`]/[`RESIZE_TIMER_ID`]/
    /// [`crate::win::backend::FRAME_TIMER_ID`] — all four can legitimately
    /// be live on the same `hwnd` at once (Win32 scopes timer ids
    /// per-window). Unlike the other three, this one is armed once with
    /// `SetTimer`'s native repeat behaviour and never killed — Win32
    /// keeps re-posting `WM_TIMER` for it every `IDLE_POLL_CEILING` until
    /// the window itself is destroyed, which is exactly the "fires
    /// whether or not anything explicitly asked to be woken" contract
    /// this safety net exists for.
    const IDLE_POLL_TIMER_ID: usize = 4;
    /// `SetTimer`'s `nIDEvent` for the caret-blink tick — see
    /// [`crate::caret_blink::CaretBlinkState`]'s doc. Distinct from
    /// [`SMOKE_TIMER_ID`]/[`RESIZE_TIMER_ID`]/[`IDLE_POLL_TIMER_ID`]/
    /// [`crate::win::backend::FRAME_TIMER_ID`] — all five can legitimately
    /// be live on the same `hwnd` at once. Armed once at startup with
    /// `SetTimer`'s native repeat behaviour, at
    /// `WinBackend::caret_blink_period()`, and never killed — same
    /// always-on posture as `IDLE_POLL_TIMER_ID`. Its `WM_TIMER` arm ticks
    /// `WinBackend::tick_caret_blink` directly rather than going through
    /// the shared `tick()`/`AppLogic::tick` wake path, so it can never
    /// double-tick against that path's own frame/idle timers.
    const CARET_BLINK_TIMER_ID: usize = 5;

    /// Everything a live window needs, reachable from `wndproc::<A>` via
    /// `GWLP_USERDATA` (see module docs).
    struct RunState<A: AppLogic> {
        app: A,
        backend: WinBackend,
    }

    /// Per-window state stashed in `GWLP_USERDATA` (see module docs).
    /// `pump_depth` deliberately lives *outside* `state`'s `RefCell`
    /// rather than as a `RunState` field: `super::guarded_call` (used by
    /// [`dispatch`] and the `WM_PAINT` handler below) must be able to
    /// read it without itself needing a borrow of the very `RefCell` a
    /// reentrant `wndproc` call would already be fighting over — see
    /// `super::guarded_call`'s docs.
    struct WindowState<A: AppLogic> {
        state: RefCell<RunState<A>>,
        pump_depth: ModalPumpDepth,
        /// `Some` only when `QUADRAUI_WIN_SMOKE_MS` is set — see
        /// the module doc's "Headless smoke mode" section. Read once by
        /// the `WM_TIMER` handler in [`wndproc`]; never mutated.
        smoke: Option<SmokeConfig>,
        /// `Rc`, not a plain `Cell`, so [`create_window`]'s caller (a
        /// [`WinRunner`], or `run_inner`'s loop) can hold a clone that
        /// survives past `WindowState` itself being freed (`finish`'s
        /// `Box::from_raw` happens before `run_inner`'s final exit-code
        /// decision needs this value) — same reason `gtk::run::run_with`'s
        /// `smoke_failed` is an `Rc<Cell<bool>>` shared with the
        /// `Application`, not a plain local.
        smoke_failed: Rc<Cell<bool>>,
        /// Pending-viewport store for the resize-settle debounce
        /// — see `crate::runtime::ResizeDebouncer`'s doc.
        /// `WM_SIZE` calls `note()` on every message; the `RESIZE_TIMER_ID`
        /// `WM_TIMER` arm calls `take()` once `SetTimer` proves the drag
        /// has settled (`SetTimer` replaces an already-armed timer of the
        /// same id rather than stacking a new one, so a live drag keeps
        /// rescheduling the same timer and only the final call's deadline
        /// ever actually fires).
        resize_debouncer: RefCell<ResizeDebouncer>,
        /// Set by the top-of-`wndproc` `pump_depth.is_pumping()`
        /// re-entrancy check when the message it just ceded to
        /// `DefWindowProcW` was `WM_SIZE` or `WM_DPICHANGED` — i.e. a
        /// synchronous Win32 call made from inside a live `guarded_call`
        /// (`ShowWindow(SW_MAXIMIZE)` from a drawn maximize-button click,
        /// chiefly) sent a size/DPI notification that re-entered `wndproc`
        /// and got bounced before `wndproc`'s own `WM_SIZE`/`WM_DPICHANGED`
        /// arms ever ran. Those arms are a one-shot state notification, not
        /// input — ceding them without remembering the attempt silently
        /// drops the resize for good (the bug this issue reports: a
        /// stretched render target and stale hit-testing after the OS
        /// window maximizes). Checked at the top of every *non-reentrant*
        /// `wndproc` call (right after the `is_pumping()` check that would
        /// itself otherwise cede again) and cleared there: by that point
        /// `pump_depth` is back to 0, so `GetClientRect` reads the real,
        /// settled post-maximize/post-DPI-change size and the normal
        /// `WM_SIZE` path (`resize_surface`, debouncer `note`,
        /// `RESIZE_TIMER_ID`, `InvalidateRect`) runs against it — the same
        /// ordering a posted `WM_APP` message would give for free, without
        /// needing one.
        pending_resize_resync: Cell<bool>,
    }

    /// Encode a Rust `&str` (already `\0`-terminated by its caller) as
    /// UTF-16 for a Win32 wide-string API.
    fn wide(s: &str) -> Vec<u16> {
        s.encode_utf16().collect()
    }

    // `WM_MOUSEMOVE`'s `wparam` key-state flags (`<winuser.h>`'s
    // `MK_LBUTTON`/`MK_RBUTTON`/`MK_MBUTTON`). Defined locally rather than
    // pulled from the `windows` crate — same reasoning `super::events`'
    // module docs give for its local `WM_*` consts: only the arithmetic
    // mask is needed, and it's one less binding-crate detail to get right.
    const MK_LBUTTON: usize = 0x0001;
    const MK_RBUTTON: usize = 0x0002;
    const MK_MBUTTON: usize = 0x0010;

    // `WM_QUADRAUI_USER_EVENT` is defined in
    // `crate::win::backend` (`WinBackend::waker` — the producer — needs
    // it too, so it lives next to that field rather than being
    // duplicated). `FRAME_TIMER_ID` is its
    // `request_frame_in` sibling, same rationale.
    use crate::win::backend::{FRAME_TIMER_ID, WM_QUADRAUI_TRAY_CALLBACK, WM_QUADRAUI_USER_EVENT};

    /// Live modifier state for the message currently being dispatched,
    /// via `GetKeyState` — see `super::events`' module docs on why Win32
    /// needs a per-message read here rather than a bitmask carried on the
    /// message itself (the one exception, `WM_MOUSEMOVE`'s `MK_*` button
    /// flags, is handled separately above).
    fn win_key_modifiers() -> Modifiers {
        win_modifiers(
            key_is_down(VK_CONTROL),
            key_is_down(VK_SHIFT),
            key_is_down(VK_MENU),
            key_is_down(VK_LWIN) || key_is_down(VK_RWIN),
        )
    }

    /// `GetKeyState`'s return value has its high bit set when the key is
    /// currently down — reading it as a signed `i16` and comparing `< 0`
    /// is the standard idiom (matches `IS_KEY_DOWN`-style macros other
    /// Win32 bindings define for this).
    fn key_is_down(vk: VIRTUAL_KEY) -> bool {
        // SAFETY: `GetKeyState` takes a plain `i32` virtual-key code and
        // returns a status word by value — no pointer, no handle, no
        // precondition beyond being called on a thread with a message
        // queue (true for every caller here, all of which run inside
        // `wndproc` or its dispatch helpers).
        unsafe { GetKeyState(vk.0 as i32) < 0 }
    }

    /// Single-instance gate. Creates a named `CreateMutexW` keyed off
    /// [`super::instance_identity`] (Win has no `app_id` concept the way
    /// `gtk::RunConfig` does, so the window title doubles as this
    /// backend's stable app identity) and reports whether *this* call is
    /// the one that actually created it.
    ///
    /// `CreateMutexW` itself succeeds either way — whether the name is
    /// new or already held by another process, it returns a handle
    /// referring to whichever instance owns it — so telling "I created
    /// this" apart from "this already existed" needs the standard Win32
    /// idiom: check `GetLastError()` for `ERROR_ALREADY_EXISTS`
    /// immediately after a successful call, before anything else can run
    /// and clobber the thread-local error code.
    ///
    /// The returned handle is deliberately never closed: Win32 releases
    /// every handle a process still holds open when it exits, and a
    /// single-instance guard is meant to live exactly that long.
    ///
    /// A `CreateMutexW` failure for any other reason fails open —
    /// returns `true` — so a `RunConfig` opting into this convenience
    /// never silently refuses to open a window over it; it degrades to
    /// "act as the primary instance", not "don't start".
    ///
    /// Named via [`super::instance_identity`] rather than `title`
    /// embedded verbatim: a raw title could contain `\`, which the
    /// kernel-object namespace treats as a hierarchy separator, or an
    /// embedded `\0`, which would silently truncate the effective
    /// name — hashing sidesteps both.
    fn is_primary_instance(title: &str) -> bool {
        let name = wide(&format!(
            "Local\\quadraui-single-instance-{:016x}\0",
            super::instance_identity(title)
        ));
        // SAFETY: `name` is a `Vec<u16>` built by `wide()` just above and
        // still in scope for the duration of this call, so `name.as_ptr()`
        // stays valid; `CreateMutexW(None, false, ...)` requests no
        // security-attributes override and no initial ownership, so there
        // is no handle-ownership precondition on the caller beyond
        // eventually letting the returned `HANDLE` drop.
        //
        // `_handle` is deliberately dropped immediately rather than kept
        // alive in a `static` or leaked on the heap — that is intentional,
        // not an oversight (see this function's doc comment above:
        // "deliberately never closed"). `windows::Win32::Foundation::HANDLE`
        // is `Copy`/non-owning in this crate's bindings — dropping the
        // Rust value does **not** call `CloseHandle`, so the underlying
        // kernel mutex object stays alive and held by this process exactly
        // as long as the process itself runs, which is what a
        // single-instance guard needs. Windows closes every handle a
        // process still holds when it exits, so there is no leak in the
        // OS-resource sense either — only in the sense that no Rust value
        // holds onto it, which is the desired lifetime here.
        match unsafe { CreateMutexW(None, false, PCWSTR(name.as_ptr())) } {
            // SAFETY: `GetLastError()` reads the calling thread's
            // thread-local last-error code, set by the `CreateMutexW` call
            // immediately above and not yet clobbered by any other Win32
            // call on this thread — no pointer, no handle, nothing to
            // uphold beyond that ordering.
            Ok(_handle) => (unsafe { GetLastError() }) != ERROR_ALREADY_EXISTS,
            Err(_) => true,
        }
    }

    /// Forwards this process's own `argv` to another instance that
    /// already holds the single-instance mutex. Finds that instance's
    /// window — by [`window_class_name`], scoped to this same `title`
    /// the mutex check just used — and forwards this process's own
    /// `argv` to it via `WM_COPYDATA`, the same message [`wndproc`]'s
    /// `WM_COPYDATA` arm decodes back into a `UiEvent::OpenRequested`
    /// on the receiving end. `SendMessageW` (unlike `PostMessageW`)
    /// blocks until the receiver has processed the message, so it's safe
    /// to let `payload_wide`/`cds` drop right after this call returns.
    ///
    /// A `FindWindowW` failure (the mutex's owner exited in the narrow
    /// window between creating it and this call reaching it) silently
    /// does nothing further — there's no window left to forward to.
    fn forward_argv_to_existing_instance(title: &str) {
        let class_name = window_class_name(title);
        // SAFETY: `class_name` is a `Vec<u16>` from `window_class_name`,
        // still in scope so `class_name.as_ptr()` stays valid for the
        // duration of the call; `FindWindowW` performs no write through
        // either pointer argument and `PCWSTR::null()` is the documented
        // way to say "don't filter on window title".
        let Ok(hwnd) = (unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) }) else {
            return;
        };
        // `argv[0]` is this process's own executable path, not part of
        // the open request — every other backend's argv-classification
        // (see `classify_open_args`'s callers) skips it the same way.
        //
        // Encoded via `super::encode_copydata_argv`, not a raw
        // `"\n"`.join`: an argv entry could itself contain a literal
        // newline, which would silently split into two bogus entries on
        // the receiving end — see that function's doc for why `'\0'`
        // is the separator that can't collide with real argv content.
        let payload = super::encode_copydata_argv(&std::env::args().skip(1).collect::<Vec<_>>());
        let payload_wide = wide(&format!("{payload}\0"));
        let cds = COPYDATASTRUCT {
            // Tag checked on the receiving end: `wndproc`'s `WM_COPYDATA`
            // arm rejects any payload that doesn't carry this exact tag.
            dwData: ARGV_FORWARD_TAG,
            cbData: (payload_wide.len() * size_of::<u16>()) as u32,
            lpData: payload_wide.as_ptr() as *mut c_void,
        };
        // SAFETY: `hwnd` came from the successful `FindWindowW` just above
        // and `SendMessageW` blocks until the receiver has processed the
        // message (see this function's doc comment), so `hwnd` cannot be
        // destroyed out from under this call by anything on *this*
        // thread. `cds` (and the `payload_wide` buffer its `lpData` points
        // into) are stack-local and outlive the call, which is all
        // `WM_COPYDATA` requires — the receiving `wndproc` only reads
        // `*lparam` synchronously during dispatch, per `WM_COPYDATA`'s
        // documented contract, and never retains the pointer.
        // `SetForegroundWindow`/`ShowWindow` below take only `hwnd`, still
        // valid for the same reason.
        unsafe {
            SendMessageW(
                hwnd,
                WM_COPYDATA,
                Some(WPARAM(0)),
                Some(LPARAM(std::ptr::addr_of!(cds) as isize)),
            );
            // Best-effort: the receiving instance is what the user
            // actually wanted to see come forward. A failure here
            // (e.g. the foreground-lock restrictions Windows applies to
            // background processes) still leaves the `WM_COPYDATA`
            // delivery itself intact.
            let _ = SetForegroundWindow(hwnd);
            let _ = ShowWindow(hwnd, SW_RESTORE);
        }
    }

    pub(super) fn run<A: AppLogic + 'static>(
        app: A,
        config: super::RunConfig,
    ) -> std::process::ExitCode {
        // DPI scale factor plumbed to Viewport::scale. Without
        // per-monitor-v2 awareness, Windows silently bitmap-scales the
        // whole window on HiDPI displays and `GetDpiForWindow` always
        // reports 96 (100%) — this must run before the window (and its
        // DPI-aware render target) is created. Best-effort: an older
        // Windows build lacking this API, or a manifest that already
        // declared DPI awareness, both make this call fail harmlessly.
        //
        // SAFETY: `SetProcessDpiAwarenessContext` takes a plain enum
        // value (no pointer, no handle) and has no precondition beyond
        // "call it before creating any window", which this function
        // does.
        unsafe {
            let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
        }

        // Checked *before* any window/backend/`A` setup below — if
        // another instance already holds the single-instance mutex, this
        // process's only job is to forward its own `argv` to that
        // instance's window and get out of the way, never touching `app`
        // (dropped unused) or opening a `WNDCLASSEXW` of its own.
        if config.single_instance && !is_primary_instance(&config.title) {
            forward_argv_to_existing_instance(&config.title);
            return std::process::ExitCode::SUCCESS;
        }

        // SAFETY: `run_inner`'s contract (its `# Safety` doc above) is
        // "must construct and step the resulting `WinRunner` from the
        // same thread". `run` itself never spawns a thread — it is the
        // public `run(app)`/`run_with(app, config)` entry point (bottom
        // of this file) called directly on the caller's thread, and
        // everything below this point (window creation, `wndproc`
        // dispatch, `WinRunner::pump`'s drain loop) happens inline
        // within this same call, so the thread that reaches here is
        // exactly the thread that steps the runner.
        match unsafe { run_inner(app, &config) } {
            // `Ok(smoke_ok)`: `smoke_ok` is `true` unless
            // `QUADRAUI_WIN_SMOKE_MS` was set *and* `run_smoke_check`
            // found a failure — see the module doc's "Headless
            // smoke mode" section. Always `true` when smoke mode is off.
            Ok(smoke_ok) => {
                if smoke_ok {
                    std::process::ExitCode::SUCCESS
                } else {
                    std::process::ExitCode::FAILURE
                }
            }
            Err(_) => {
                // `Backend`'s frame/window lifecycle has no error
                // channel and this crate denies `clippy::print_stderr`
                // crate-wide, so the `windows::core::Error`'s message
                // has nowhere to go beyond the process exit code.
                std::process::ExitCode::FAILURE
            }
        }
    }

    /// The live [`HWND`], its heap-owned `WindowState<A>` (freed by the
    /// caller via `Box::from_raw`, as [`WinRunner::finish`] does), and a
    /// clone of the headless-smoke `smoke_failed` flag — the return of
    /// [`create_window`], named to keep the tuple out of its signature.
    type CreatedWindow<A> = (HWND, *mut WindowState<A>, Rc<Cell<bool>>);

    /// # Safety
    ///
    /// Must run on the thread that will pump the resulting message loop
    /// (via [`WinRunner::step`]/[`WinRunner::pump`]) to completion — Win32
    /// windows are thread-affine, and `wndproc` below assumes it's only
    /// ever invoked by `DispatchMessageW` on this same thread (no
    /// synchronization guards `RunState`'s `RefCell`). The returned
    /// [`WinRunner`] inherits this same-thread contract: it must be
    /// constructed and stepped from one thread only (enforced for free —
    /// `HWND` wraps a raw pointer, so `WinRunner` is `!Send`/`!Sync`).
    /// [`WinBackend::waker`](crate::win::backend::WinBackend::waker) is
    /// the one piece of this surface that is explicitly any-thread: it
    /// may be called from a background thread to nudge the runner's
    /// thread without busy-polling.
    ///
    /// Returns the live [`HWND`], the heap-allocated `state_ptr` (owned —
    /// the caller becomes responsible for eventually freeing it via
    /// `Box::from_raw`, which [`WinRunner::finish`] does), and a clone of
    /// `smoke_failed`: `smoke_failed.get()` is always `false` unless
    /// `QUADRAUI_WIN_SMOKE_MS` armed the headless smoke check and it found
    /// a failure — see the module doc's "Headless smoke mode" section and
    /// [`run_smoke_check`].
    unsafe fn create_window<A: AppLogic + 'static>(
        mut app: A,
        title: &str,
        app_icon: Option<&ImageSource>,
    ) -> windows::core::Result<CreatedWindow<A>> {
        // SAFETY: `GetModuleHandleW(PCWSTR::null())` is the documented
        // idiom for "give me this process's own module handle" — the
        // null pointer is an explicit sentinel the API defines, not a
        // dereference, and the returned `HMODULE` is process-lifetime
        // (never needs freeing).
        let hinstance: HINSTANCE = unsafe { GetModuleHandleW(PCWSTR::null())?.into() };

        // Scoped by `title` via `window_class_name`, matching
        // `is_primary_instance`'s mutex scope.
        let class_name = window_class_name(title);
        // `wide()` expects an already-`\0`-terminated string (see its doc
        // comment) — `title` (from `RunConfig::title`) carries no
        // terminator of its own, unlike the `\0`-suffixed string literals
        // this module builds everywhere else.
        let title_nul = format!("{title}\0");
        let window_title = wide(&title_nul);

        let wc = WNDCLASSEXW {
            cbSize: size_of::<WNDCLASSEXW>() as u32,
            style: CS_HREDRAW | CS_VREDRAW,
            lpfnWndProc: Some(wndproc::<A>),
            hInstance: hinstance,
            // SAFETY: `LoadCursorW(None, IDC_ARROW)` loads a built-in
            // system cursor by its predefined `PCWSTR` id (`None` means
            // "no module — this is a system resource, not an app
            // resource"); the returned `HCURSOR` is a shared system handle
            // that outlives the process and needs no explicit release.
            hCursor: unsafe { LoadCursorW(None, IDC_ARROW)? },
            lpszClassName: PCWSTR(class_name.as_ptr()),
            ..Default::default()
        };
        // `RegisterClassExW` returns 0 (a Win32 `ATOM` is never zero on
        // success) on failure — there's no `Result`-returning wrapper for
        // it in `windows-rs`, so this reaches for `GetLastError()` via
        // `Error::from_thread()` the same way the crate's own `Result`
        // wrappers do internally.
        //
        // SAFETY: `wc` is a fully-initialized `WNDCLASSEXW` on the stack,
        // still in scope; `RegisterClassExW` reads it synchronously and
        // does not retain the pointer past the call. `class_name.as_ptr()`
        // (via `lpszClassName`) stays valid because `class_name` outlives
        // this call. `wndproc::<A>` is `extern "system"`-callable with the
        // exact signature `WNDPROC` requires — enforced by the compiler at
        // the `Some(wndproc::<A>)` assignment above, not by this call.
        if unsafe { RegisterClassExW(&wc) } == 0 {
            return Err(WinError::from_thread());
        }

        // Backend + app setup happens *before* the window exists — same
        // ordering as `gtk::run` (`GtkBackend::new()` then `app.setup()`
        // before the `ApplicationWindow` is realized) and `tui::run`.
        // `backend.viewport()` reads `WinBackend::new`'s zeroed seed
        // until `WM_SIZE`/`attach_surface` populate it below; apps
        // reading it from `setup()` for immediate sizing decisions won't
        // see the real window size yet, matching the other two runners'
        // same limitation.
        let mut backend = WinBackend::new();
        app.setup(&mut backend);

        // `None` (zero runtime cost — no timer ever armed below)
        // unless `QUADRAUI_WIN_SMOKE_MS` is set. See the module doc's
        // "Headless smoke mode" section.
        let smoke = SmokeConfig::from_env(SMOKE_MS_VAR, SMOKE_PASTE_VAR);
        let smoke_failed = Rc::new(Cell::new(false));

        let state_ptr: *mut WindowState<A> = Box::into_raw(Box::new(WindowState {
            state: RefCell::new(RunState { app, backend }),
            pump_depth: ModalPumpDepth::new(),
            smoke,
            smoke_failed: smoke_failed.clone(),
            resize_debouncer: RefCell::new(ResizeDebouncer::new()),
            pending_resize_resync: Cell::new(false),
        }));

        // SAFETY: `class_name`/`window_title` are `Vec<u16>`s that outlive
        // this call, so their `as_ptr()`s stay valid; `state_ptr` (passed
        // as `lpCreateParams`) was just leaked via `Box::into_raw` above
        // and is not otherwise aliased yet. `CreateWindowExW` synchronously
        // dispatches `WM_NCCREATE`/`WM_CREATE` to `wndproc::<A>` (registered
        // above) before returning; `wndproc`'s `WM_NCCREATE` arm (below)
        // stores `lpCreateParams` into `GWLP_USERDATA` and never
        // dereferences it during that same call, so `state_ptr` doesn't
        // need to be readable-as-`WindowState<A>` until *after*
        // `CreateWindowExW` returns.
        let hwnd = unsafe {
            CreateWindowExW(
                WINDOW_EX_STYLE::default(),
                PCWSTR(class_name.as_ptr()),
                PCWSTR(window_title.as_ptr()),
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                DEFAULT_WIDTH,
                DEFAULT_HEIGHT,
                None,
                None,
                Some(hinstance),
                Some(state_ptr as *const c_void),
            )
        };
        let hwnd = match hwnd {
            Ok(hwnd) => hwnd,
            Err(e) => {
                // SAFETY: `state_ptr` came from `Box::into_raw` above and
                // hasn't been freed yet — `CreateWindowExW` failing means
                // `wndproc` never got far enough to need it again.
                drop(unsafe { Box::from_raw(state_ptr) });
                return Err(e);
            }
        };

        // The window exists now, so `WinBackend` can create its
        // `ID2D1HwndRenderTarget` sized to the real client rect.
        // `WM_SIZE` fired synchronously during `CreateWindowExW` above
        // already ran with `surface: None` (see
        // `WinBackend::resize_surface`'s docs) — this is the first
        // point a surface can exist at all.
        let attach_result = {
            // SAFETY: `state_ptr` is valid and no other reference to it
            // exists yet — `wndproc` only reads it starting with the
            // `WM_NCCREATE` this same `CreateWindowExW` call already
            // dispatched (synchronously, before returning), and that
            // path only stores the pointer in `GWLP_USERDATA`, never
            // dereferences it.
            let ws: &WindowState<A> = unsafe { &*state_ptr };
            // A call inside `attach_surface` that synchronously
            // re-enters `wndproc` with a nested message before returning
            // — while `ws.state` is still borrowed on this same stack —
            // is the same reentrancy hazard `ModalPumpGuard` already
            // guards every `guarded_call` against. This call happens
            // during window creation, before the first `guarded_call`
            // has ever run — nothing had armed `pump_depth` yet — so a
            // nested message here would sail through to a second,
            // panicking `ws.state.borrow_mut()` without this guard.
            // Arm it explicitly so any such message bounces to
            // `DefWindowProcW` instead.
            let _guard = ModalPumpGuard::new(&ws.pump_depth);
            ws.state.borrow_mut().backend.attach_surface(hwnd)
        };
        if let Err(e) = attach_result {
            // SAFETY: `state_ptr` must stay valid until `DestroyWindow`
            // returns. `DestroyWindow` synchronously re-enters `wndproc`
            // on this thread (at minimum for `WM_DESTROY`/`WM_NCDESTROY`,
            // potentially others), and `wndproc` unconditionally
            // dereferences `GWLP_USERDATA` before matching on `msg` — so
            // freeing the box first would leave that pointer dangling
            // for every message `DestroyWindow` generates, not just the
            // ones that read `state`. `DestroyWindow` completes its
            // entire synchronous dispatch before returning — the same
            // guarantee the normal-shutdown path below relies on when it
            // frees `state_ptr` only after the message loop has exited —
            // so freeing it here, after `DestroyWindow` returns, is safe.
            let _ = unsafe { DestroyWindow(hwnd) };
            // SAFETY: `DestroyWindow` above has returned, so its
            // synchronous `wndproc` dispatch (the reason this box must
            // stay alive, per the comment above) is complete — nothing
            // left running on this thread still holds `state_ptr`, and
            // it was never handed to another thread.
            drop(unsafe { Box::from_raw(state_ptr) });
            return Err(e);
        }

        // Opt the window into `WM_DROPFILES` — off by default for
        // every `HWND`. Without this, `WM_DROPFILES` never
        // arrives at all (rather than arriving with an empty `HDROP`),
        // so a missing call here is silent, not a visible failure.
        //
        // SAFETY: `hwnd` is the just-created, still-live window from
        // `CreateWindowExW` above; `DragAcceptFiles` takes only a handle
        // and a bool, no pointer.
        unsafe {
            DragAcceptFiles(hwnd, true);
        }

        // Apply `RunConfig::app_icon` (from `ShellConfig::with_app_icon`)
        // to the titlebar/taskbar via `WM_SETICON` — before `ShowWindow`
        // below, so the icon is already in place for the window's first
        // paint rather than flashing the generic default first. Both
        // `ICON_BIG` (Alt-Tab switcher, taskbar) and `ICON_SMALL`
        // (titlebar) are set from the same decoded `HICON`: unlike a
        // `.ico` resource, `ImageSource` carries no separate small-size
        // variant, and Windows itself scales one bitmap for both uses.
        // A decode failure (missing file, corrupt bytes, unrecognised
        // format) silently leaves the window with no icon — same
        // collapse-to-nothing posture `TrayService::set_icon`'s
        // `decode_hicon` documents — rather than failing window creation
        // over a cosmetic detail.
        //
        // The `HICON` this builds is intentionally never destroyed: it is
        // a `CreateIconIndirect` handle, not a shared system resource, and
        // this window's icon is set exactly once at startup with no
        // `set_app_icon` API to replace it later — same "left for the
        // process lifetime" posture `WinBackend::registered_font_bytes`
        // documents for DirectWrite's font-file loader.
        if let Some(source) = app_icon {
            if let Some(hicon) = decode_hicon(source) {
                // SAFETY: `hwnd` is the live window from `CreateWindowExW`
                // above; `hicon` is a valid `HICON` `decode_hicon` just
                // produced and (per the comment above) is intentionally
                // kept alive for the process lifetime, so it is still
                // valid for both `WM_SETICON` sends below.
                unsafe {
                    SendMessageW(
                        hwnd,
                        WM_SETICON,
                        Some(WPARAM(ICON_BIG as usize)),
                        Some(LPARAM(hicon.0 as isize)),
                    );
                    SendMessageW(
                        hwnd,
                        WM_SETICON,
                        Some(WPARAM(ICON_SMALL as usize)),
                        Some(LPARAM(hicon.0 as isize)),
                    );
                }
            }
        }

        // Paint the real first frame into the swap chain *before* the
        // window becomes visible, not after. `attach_surface` above
        // only creates the `ID2D1HwndRenderTarget` — nothing has called
        // `BeginDraw`/`Clear`/`EndDraw` on it yet, so the backing
        // surface DWM would composite the instant `ShowWindow` (below)
        // makes this window visible still holds whatever undefined
        // contents a brand-new swap-chain backbuffer starts with.
        // `render_frame` — the same `begin_frame`/`app.render`/
        // `end_frame` bracket `WM_PAINT`'s handler below runs — works
        // on any `WinBackend` with a surface attached regardless of
        // whether its `HWND` is visible yet, so calling it here, while
        // the window is still hidden, guarantees the current theme's
        // background (and whatever `app.render` paints on top of it)
        // is already the first thing DWM ever composites for this
        // window — the standard mitigation for the Win32/Direct2D
        // "first-frame white flash" class of bug.
        //
        // Routed through the same `super::guarded_call`/`ModalPumpGuard`
        // bracket the `WM_PAINT` handler below uses, for the same
        // reentrancy reason `attach_surface` above is guarded: `app.render`
        // is arbitrary consumer code, and nothing yet guarantees it
        // can't synchronously trigger a nested message on this thread.
        // A `None` result just means this priming frame is skipped —
        // the first real `WM_PAINT` after `ShowWindow` below still
        // recovers it, same as any other missed frame.
        //
        // One retry if `EndDraw` itself failed (device lost): `ensure_surface`
        // rebuilds the render target exactly the way the next `WM_PAINT`
        // would, so a transient failure right here gets the same
        // recovery a transient failure mid-session already gets, instead
        // of this window showing with nothing painted after all.
        {
            // SAFETY: `state_ptr` is valid and not concurrently referenced
            // here — same as the `attach_surface`/app-icon/smoke-timer
            // borrows above and below.
            let ws: &WindowState<A> = unsafe { &*state_ptr };
            let _ = super::guarded_call(&ws.state, &ws.pump_depth, |run_state| {
                let viewport = run_state.backend.viewport();
                let RunState { app, backend } = run_state;
                super::render_frame(backend, app, viewport);
                if matches!(
                    Backend::last_error(backend),
                    Some(crate::backend::BackendError::SurfaceLost)
                ) && backend.ensure_surface().is_ok()
                {
                    let viewport = backend.viewport();
                    super::render_frame(backend, app, viewport);
                }
            });
        }

        // SAFETY: `hwnd` is the live window created above; both calls
        // take only a handle (plus, for `ShowWindow`, a plain show-command
        // enum) — no pointer.
        let _ = unsafe { ShowWindow(hwnd, SW_SHOW) };
        // The priming render above already painted the real first frame
        // into the surface while the window was still hidden, so this
        // is now belt-and-suspenders rather than the primary mechanism
        // it used to be: it still forces a synchronous repaint of
        // whatever became invalid between the priming render and here.
        //
        // SAFETY: same as `ShowWindow` immediately above.
        let _ = unsafe { UpdateWindow(hwnd) };

        // Arm the coarse idle-poll safety net, unconditionally and
        // independent of `RunConfig`/smoke mode — see `IDLE_POLL_TIMER_ID`'s
        // doc above and `AppLogic::tick`'s per-backend table. `SetTimer`
        // itself re-posts `WM_TIMER` for this id every `IDLE_POLL_CEILING`
        // until the window is destroyed, so this is armed exactly once,
        // unlike `FRAME_TIMER_ID`'s re-arm-on-every-fire one-shot pattern.
        //
        // SAFETY: `hwnd` is the live window just shown above; `SetTimer`
        // with `lpTimerFunc: None` posts `WM_TIMER` through the normal
        // message queue to `wndproc` rather than calling a raw function
        // pointer, so there is no callback-signature precondition here.
        unsafe {
            SetTimer(
                Some(hwnd),
                IDLE_POLL_TIMER_ID,
                crate::runtime::IDLE_POLL_CEILING
                    .as_millis()
                    .min(u32::MAX as u128) as u32,
                None,
            );
        }

        // Arm the caret-blink timer, unconditionally — see
        // `CARET_BLINK_TIMER_ID`'s doc above. Same once-armed,
        // native-repeat, never-killed posture as `IDLE_POLL_TIMER_ID`
        // immediately above, just at `WinBackend::caret_blink_period()`
        // instead of `IDLE_POLL_CEILING`.
        {
            // SAFETY: `state_ptr` is valid and not concurrently
            // referenced here — same as the other `state_ptr` borrows in
            // this function.
            let ws: &WindowState<A> = unsafe { &*state_ptr };
            let period_ms = ws
                .state
                .borrow()
                .backend
                .caret_blink_period()
                .as_millis()
                .min(u32::MAX as u128) as u32;
            // SAFETY: `hwnd` is the live window just shown above;
            // `SetTimer` with `lpTimerFunc: None` posts `WM_TIMER`
            // through the normal message queue to `wndproc` rather than
            // calling a raw function pointer, so there is no
            // callback-signature precondition here.
            unsafe {
                SetTimer(Some(hwnd), CARET_BLINK_TIMER_ID, period_ms, None);
            }
        }

        // Arm the one-shot smoke-check timer, if enabled. See the
        // module doc's "Headless smoke mode" section and
        // `run_smoke_check`'s `WM_TIMER` handler in `wndproc` below.
        {
            // SAFETY: same as the `attach_surface` borrow above —
            // `state_ptr` is valid and not concurrently referenced here.
            let ws: &WindowState<A> = unsafe { &*state_ptr };
            if let Some(cfg) = &ws.smoke {
                // SAFETY: `hwnd` is the live window; `SetTimer` with
                // `lpTimerFunc: None` posts `WM_TIMER` through the normal
                // message queue to `wndproc` rather than calling a raw
                // function pointer, so there is no callback-signature
                // precondition here.
                unsafe {
                    SetTimer(Some(hwnd), SMOKE_TIMER_ID, cfg.after_ms as u32, None);
                }
            }
        }

        // Dispatch `argv` (skipping `argv[0]`, the executable path
        // itself) as an `OpenRequested` right away, unconditionally —
        // independent of `RunConfig::single_instance`, which only gates
        // *runtime* forwarding from a second launch. A document app
        // registered as a file/URL handler is launched with the
        // file/URL as a plain command-line argument the same way on its
        // very first run as on every subsequent one, so this needs no
        // opt-in.
        {
            let args: Vec<String> = std::env::args().skip(1).collect();
            if !args.is_empty() {
                // SAFETY: same as the smoke-timer borrow just above.
                let ws: &WindowState<A> = unsafe { &*state_ptr };
                // `dispatch` (via `dispatch_with`) acts on `Reaction::Exit`
                // itself — `DestroyWindow` posts `WM_QUIT` via
                // `WM_DESTROY`, so the message loop (now driven by
                // `WinRunner`) still sees it immediately and exits cleanly.
                dispatch(ws, hwnd, classify_open_args(args));
            }
        }

        Ok((hwnd, state_ptr, smoke_failed))
    }

    /// A non-blocking, steppable Win32 message-loop runner.
    ///
    /// Mirrors [`crate::tui::run::TuiRunner`] and
    /// [`crate::gtk::run::GtkRunner`]'s shape: [`WinRunner::new`] /
    /// [`WinRunner::new_with`] create the window (via [`create_window`])
    /// but never block; [`WinRunner::step`] drains whatever Win32
    /// messages are already queued and returns immediately;
    /// [`WinRunner::pump`] blocks for up to a given timeout waiting for
    /// the next message (via `MsgWaitForMultipleObjects`) before
    /// draining. [`run_inner`]'s blocking `run()`/`run_with()` entry
    /// points are now just `loop { pump(IDLE_POLL_CEILING)? }`.
    ///
    /// # Thread affinity
    ///
    /// Must be constructed and stepped from one thread only — see
    /// [`create_window`]'s `# Safety` doc. This is enforced by the type
    /// system with no explicit `unsafe impl` needed: `HWND` wraps a raw
    /// pointer (`*mut c_void`) and `state_ptr` is itself a raw pointer,
    /// so `WinRunner` is automatically `!Send`/`!Sync`.
    /// [`WinBackend::waker`](crate::win::backend::WinBackend::waker),
    /// by contrast, is explicitly safe to call from *any* thread — that
    /// is how a background thread nudges this runner's thread without
    /// busy-polling.
    pub struct WinRunner<A: AppLogic + 'static> {
        hwnd: HWND,
        state_ptr: *mut WindowState<A>,
        smoke_failed: Rc<Cell<bool>>,
        /// Set once `WM_QUIT` has been observed and `state_ptr` freed.
        /// Further `step`/`pump` calls become no-ops that report
        /// [`StepOutcome::Exited`] instead of touching the dangling
        /// pointer again.
        finished: bool,
    }

    impl<A: AppLogic + 'static> WinRunner<A> {
        /// # Safety
        ///
        /// See [`create_window`]'s `# Safety` doc — must be called on,
        /// and the returned `WinRunner` must be stepped from, a single
        /// thread.
        pub unsafe fn new(app: A) -> windows::core::Result<Self> {
            // SAFETY: delegates to `new_with`, which carries the exact
            // same single-thread contract documented on this function's
            // own `# Safety` doc above.
            unsafe { Self::new_with(app, &RunConfig::default()) }
        }

        /// # Safety
        ///
        /// See [`create_window`]'s `# Safety` doc.
        pub unsafe fn new_with(app: A, config: &RunConfig) -> windows::core::Result<Self> {
            // SAFETY: forwards this function's own `# Safety` contract
            // (documented above) unchanged to `create_window`.
            let created = unsafe { create_window(app, &config.title, config.app_icon.as_ref())? };
            let (hwnd, state_ptr, smoke_failed) = created;
            Ok(Self {
                hwnd,
                state_ptr,
                smoke_failed,
                finished: false,
            })
        }

        /// Drain any Win32 messages already queued and return
        /// immediately — never blocks. The non-blocking half of the
        /// `step()`/`pump()` seam (see `crate::runner`'s module doc).
        pub fn step(&mut self) -> windows::core::Result<StepOutcome> {
            self.run_one(None)
        }

        /// Block for up to `timeout` waiting for the next Win32 message
        /// (via `MsgWaitForMultipleObjects`), then drain whatever is
        /// queued. Returns early the moment a message arrives — `timeout`
        /// is a ceiling, not a fixed sleep.
        pub fn pump(&mut self, timeout: Duration) -> windows::core::Result<StepOutcome> {
            self.run_one(Some(timeout))
        }

        fn run_one(&mut self, block_for: Option<Duration>) -> windows::core::Result<StepOutcome> {
            if self.finished {
                return Ok(StepOutcome::Exited);
            }

            if let Some(timeout) = block_for {
                let timeout_ms = timeout.as_millis().min(u32::MAX as u128) as u32;
                // SAFETY: `phandles: None` with `fwaitall: false` just
                // waits on the calling thread's own message queue (via
                // `dwwakemask`); no handles are passed so there is
                // nothing for the caller to keep alive. The return value
                // is deliberately not matched on: `WAIT_TIMEOUT` just
                // means the `PeekMessageW` drain below finds nothing to
                // do, which is the correct, harmless outcome for a
                // `pump()` whose ceiling elapsed with no message.
                unsafe {
                    let _ = MsgWaitForMultipleObjects(None, false, timeout_ms, QS_ALLINPUT);
                }
            }

            let mut msg = MSG::default();
            loop {
                // SAFETY: `msg` is stack-local and live for the whole
                // loop; `hwnd: None` means "any message belonging to a
                // window owned by this thread", which is exactly the
                // one window this runner created on this same thread
                // (this type's thread-affinity contract, documented on
                // `new`/`new_with`).
                let peeked = unsafe { PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE) };
                let has_message = peeked.as_bool();
                if !has_message {
                    return Ok(StepOutcome::Continue);
                }
                if msg.message == WM_QUIT {
                    self.finish();
                    return Ok(StepOutcome::Exited);
                }
                // SAFETY: `msg` was just populated by the successful
                // `PeekMessageW` above; both calls route it back into
                // `wndproc::<A>` on this same thread, which is exactly
                // what `state_ptr` (stored in `GWLP_USERDATA`) is alive
                // for.
                unsafe {
                    let _ = TranslateMessage(&msg);
                    DispatchMessageW(&msg);
                }
            }
        }

        /// Idempotent: frees `state_ptr` (if not already freed) and
        /// marks `self` finished. Called both when `WM_QUIT` is observed
        /// in `run_one` and from `Drop` for a runner dropped before the
        /// app asked to exit.
        fn finish(&mut self) {
            if self.finished {
                return;
            }
            self.finished = true;
            // SAFETY: `WM_DESTROY`'s handler is the only other place
            // that could still touch `state_ptr`, and it doesn't — by
            // the time this runs (either `WM_QUIT` observed, or `Drop`
            // tearing down a runner that never saw one) there is no
            // `wndproc` invocation left that could observe this free.
            drop(unsafe { Box::from_raw(self.state_ptr) });
        }
    }

    impl<A: AppLogic + 'static> Drop for WinRunner<A> {
        fn drop(&mut self) {
            if !self.finished {
                // Ask the window to close; `WM_DESTROY`'s `PostQuitMessage`
                // then leaves a `WM_QUIT` in the queue that nothing will
                // ever drain, which is fine — the queue itself is torn
                // down with the thread/window.
                //
                // SAFETY: `self.hwnd` is live (`finished` is only set
                // after this same `DestroyWindow` or an equivalent
                // app-initiated one has already run).
                unsafe {
                    let _ = DestroyWindow(self.hwnd);
                }
            }
            self.finish();
        }
    }

    /// # Safety
    ///
    /// Must run on the thread that will pump the returned message loop
    /// to completion — see [`create_window`]'s `# Safety` doc, which
    /// this function inherits unchanged.
    ///
    /// Returns `Ok(smoke_ok)` rather than plain `Ok(())`:
    /// `smoke_ok` is always `true` unless `QUADRAUI_WIN_SMOKE_MS` armed
    /// the headless smoke check and it found a failure — see the module
    /// doc's "Headless smoke mode" section and [`run_smoke_check`].
    unsafe fn run_inner<A: AppLogic + 'static>(
        app: A,
        config: &super::RunConfig,
    ) -> windows::core::Result<bool> {
        // SAFETY: forwards this function's own `# Safety` contract
        // (documented above) unchanged to `WinRunner::new_with`.
        let mut runner = unsafe { WinRunner::new_with(app, config)? };
        while let StepOutcome::Continue = runner.pump(crate::runtime::IDLE_POLL_CEILING)? {}
        Ok(!runner.smoke_failed.get())
    }

    /// Dispatch `event` through [`super::dispatch_event`] (the shared
    /// pre-processing funnel — ActivityBar keyboard-focus redirect,
    /// Tab/Shift+Tab focus cycling, global accelerator matching, then
    /// `app.handle`), then honour the returned outcome via
    /// [`dispatch_with`]: a redraw invalidates the whole client area
    /// so the next message-loop iteration repaints via `WM_PAINT`, and
    /// an exit destroys the window there — `dispatch_with` is the
    /// single place any caller's `Reaction` gets acted on.
    ///
    /// Routes the `state.borrow_mut()` that spans `super::dispatch_event`
    /// through `super::guarded_call(&ws.state, &ws.pump_depth, ...)` so
    /// a reentrant message is ceded to `DefWindowProcW` rather than
    /// panicking on a double `borrow_mut()`. When that happens,
    /// `dispatch` returns `Reaction::Continue` for the dropped message:
    /// no redraw, no exit, matching every other message this `wndproc`
    /// doesn't otherwise handle.
    fn dispatch<A: AppLogic>(ws: &WindowState<A>, hwnd: HWND, event: UiEvent) -> Reaction {
        dispatch_with(ws, hwnd, |backend, app| {
            super::dispatch_event(event, backend, app)
        })
    }

    /// [`dispatch`]'s generalisation: runs `f` — any of `super::dispatch_event`,
    /// [`super::route_mouse_down`], [`super::route_mouse_move`], or
    /// [`super::route_mouse_up`] — under the same `guarded_call`
    /// re-entrancy guard and `InvalidateRect`-on-redraw handling `dispatch`
    /// already provided. `dispatch` itself is now a one-line wrapper around
    /// this; the mouse handlers below call this directly so a `MouseDown`/
    /// `MouseMoved`/`MouseUp` message routes through the shared
    /// `dispatch_click`/`dispatch_mouse_drag`/`dispatch_mouse_up` pipeline
    /// (text-region hit-testing, scrollbar drags) before any resulting
    /// event reaches `dispatch_event` — the same split `gtk::run`'s signal
    /// handlers keep between click-routing and `dispatch_event`'s own
    /// pre-processing.
    fn dispatch_with<A: AppLogic>(
        ws: &WindowState<A>,
        hwnd: HWND,
        f: impl FnOnce(&mut WinBackend, &mut A) -> super::EventOutcome,
    ) -> Reaction {
        let outcome = super::guarded_call(&ws.state, &ws.pump_depth, |run_state| {
            let RunState { app, backend } = run_state;
            f(backend, app)
        });
        let Some(outcome) = outcome else {
            return Reaction::Continue;
        };
        let reaction = match outcome {
            super::EventOutcome::Continue => Reaction::Continue,
            super::EventOutcome::Redraw => Reaction::Redraw,
            // Arm the scheduled-wake timer. `guarded_call`
            // above has already released its borrow of `ws.state` by
            // this point, so a fresh `borrow_mut()` here is safe.
            super::EventOutcome::RedrawAfter(delay) => {
                ws.state.borrow().backend.request_frame_in(delay);
                Reaction::Continue
            }
            super::EventOutcome::Exit => Reaction::Exit,
        };
        if reaction == Reaction::Redraw {
            // SAFETY: `hwnd` is a caller-supplied still-live window (every
            // call site passes the `hwnd` `wndproc` was itself invoked
            // with); `InvalidateRect` takes only handles/rects, no raw
            // pointer arithmetic.
            unsafe {
                let _ = InvalidateRect(Some(hwnd), None, false);
            }
        }
        // This is the only place a `Reaction::Exit` gets acted on: every
        // `wndproc` arm that routes through `dispatch`/`dispatch_with`
        // gets the exit handled here, so an app returning `Exit` from
        // any of them — a drawn-menu "Quit" click delivered as
        // `WM_LBUTTONUP`, or `:q` via `WM_KEYDOWN`, just as much as
        // `WM_CLOSE` — tears the window down the same way.
        if reaction == Reaction::Exit {
            // SAFETY: `hwnd` is a caller-supplied still-live window (see
            // above); `DestroyWindow` re-enters `wndproc` synchronously
            // for `WM_DESTROY`/`WM_NCDESTROY` on this same thread, which
            // is fine — `ws`/`state_ptr` stay valid for the whole of
            // the owning `WinRunner`'s lifetime, and a second
            // `DestroyWindow` on an already-destroyed handle (e.g. if a
            // caller also checks the returned `Reaction` itself) just
            // fails harmlessly.
            unsafe {
                let _ = DestroyWindow(hwnd);
            }
        }
        reaction
    }

    /// Fire [`AppLogic::tick`] — the target of both the
    /// [`crate::win::backend::FRAME_TIMER_ID`] `WM_TIMER` arm (once the timer
    /// [`crate::win::backend::WinBackend::request_frame_in`] armed has
    /// elapsed) and the [`IDLE_POLL_TIMER_ID`] arm (the unconditional
    /// `IDLE_POLL_CEILING` safety net). Deferred work that only marks
    /// state dirty with no explicit `Reaction::RedrawAfter`/
    /// `request_frame_in` of its own still gets picked up within
    /// `IDLE_POLL_CEILING`, same as on every other backend — see
    /// [`AppLogic::tick`]'s per-backend table.
    fn tick<A: AppLogic>(ws: &WindowState<A>, hwnd: HWND) -> Reaction {
        let reaction = super::guarded_call(&ws.state, &ws.pump_depth, |run_state| {
            let RunState { app, backend } = run_state;
            app.tick(backend)
        });
        let Some(reaction) = reaction else {
            return Reaction::Continue;
        };
        match reaction {
            // SAFETY: same as `dispatch_with`'s identical call above —
            // `hwnd` is caller-supplied and still live.
            Reaction::Redraw => unsafe {
                let _ = InvalidateRect(Some(hwnd), None, false);
            },
            Reaction::RedrawAfter(delay) => {
                ws.state.borrow().backend.request_frame_in(delay);
            }
            // Mirrors `dispatch_with`'s `DestroyWindow` handling: `tick`
            // is reached from both the scheduled-wake timer and the
            // unconditional idle-poll safety net (this function's own
            // doc), and both need an app's `Exit` to tear the window down.
            Reaction::Exit => {
                // SAFETY: same as `dispatch_with`'s identical call above
                // — `hwnd` is caller-supplied and still live.
                unsafe {
                    let _ = DestroyWindow(hwnd);
                }
            }
            Reaction::Continue => {}
        }
        reaction
    }

    /// Fired once by [`wndproc`]'s `WM_TIMER` handler `cfg.after_ms`
    /// after the window is shown — see the module doc's "Headless smoke
    /// mode" section. No-ops (does nothing, sets nothing) if `ws.smoke`
    /// is `None`, though in practice the `WM_TIMER` handler never fires
    /// without it (no timer is ever armed unless `ws.smoke.is_some()`).
    ///
    /// This *is* the headless smoke harness's own diagnostic output,
    /// opt-in via `QUADRAUI_WIN_SMOKE_MS`, never reached by a host
    /// embedding a live quadraui backend — so printing here doesn't
    /// fight the crate-wide `print_stderr` deny's actual purpose.
    #[allow(clippy::print_stderr)]
    fn run_smoke_check<A: AppLogic>(ws: &WindowState<A>, hwnd: HWND) {
        let Some(cfg) = ws.smoke.as_ref() else {
            return;
        };

        let mut rect = RECT::default();
        // SAFETY: `rect` is stack-local and outlives the call; `hwnd` is
        // caller-supplied and still live (this only runs from the
        // `WM_TIMER` handler while `wndproc` is dispatching for it).
        let (width, height) = unsafe {
            let _ = GetClientRect(hwnd, &mut rect);
            (rect.right - rect.left, rect.bottom - rect.top)
        };
        if !smoke_size_ok(width, height, SMOKE_MIN_WIDTH, SMOKE_MIN_HEIGHT) {
            eprintln!(
                "quadraui smoke: client area size looks broken ({width}x{height}px, expected \
                 at least {SMOKE_MIN_WIDTH}x{SMOKE_MIN_HEIGHT}px) — this is the quadraui#437 \
                 tiny-window regression class"
            );
            ws.smoke_failed.set(true);
        }

        if let Some(text) = &cfg.paste_text {
            let read_back = {
                let state = ws.state.borrow();
                let clipboard = state.backend.services().clipboard();
                clipboard.write_text(text);
                clipboard.read_text()
            };
            if !smoke_clipboard_round_trip_ok(text, read_back.as_deref()) {
                eprintln!(
                    "quadraui smoke: OS clipboard round-trip failed — wrote {text:?}, read back \
                     {read_back:?}"
                );
                ws.smoke_failed.set(true);
            } else {
                // Also exercise the real Ctrl-V interception path
                // (the exact code `WM_CHAR`'s live dispatch calls) —
                // mirrors `gtk::run::schedule_smoke_check`'s identical
                // follow-up dispatch. Note: the return value below isn't
                // inspected, so this alone can't distinguish "recognised
                // as paste" from "fell through to `app.handle`
                // unchanged" — it only guards against a panic in the
                // interception path itself. The predicate's actual
                // matching behavior is covered by `crate::desktop`'s
                // pure-predicate unit tests, not here.
                dispatch(
                    ws,
                    hwnd,
                    UiEvent::KeyPressed {
                        key: Key::Char('v'),
                        modifiers: Modifiers {
                            ctrl: true,
                            shift: false,
                            alt: false,
                            cmd: false,
                        },
                        repeat: false,
                    },
                );
            }
        }
    }

    /// Decode a `WM_DROPFILES` `HDROP` into the dropped file paths plus
    /// the client-area device-pixel drop position.
    ///
    /// `DragQueryFileW(hdrop, u32::MAX, None)` is the documented sentinel
    /// for "return the number of dropped files" rather than a path;
    /// `DragQueryFileW(hdrop, i, None)` (for a real index) returns the
    /// required buffer length (UTF-16 code units, excluding the NUL
    /// terminator) so the buffer can be sized exactly before the real
    /// call fills it. `DragFinish` releases the `HDROP` — per its own
    /// docs the handle is invalid afterwards, so this is the only
    /// function allowed to touch it, and it always runs before
    /// returning.
    fn paths_from_dropfiles(hdrop: HDROP) -> (Vec<std::path::PathBuf>, i16, i16) {
        let mut pt = POINT::default();
        // SAFETY: `hdrop` is the live `HDROP` this `WM_DROPFILES` message
        // carried; `DragQueryPoint` doesn't consume it.
        unsafe {
            let _ = DragQueryPoint(hdrop, &mut pt);
        }

        // SAFETY: `hdrop` is still valid — `DragFinish` hasn't run yet.
        let count = unsafe { DragQueryFileW(hdrop, u32::MAX, None) };
        let mut paths = Vec::with_capacity(count as usize);
        for i in 0..count {
            // SAFETY: `hdrop`/`i` valid; `None` just asks for the
            // required length.
            let len = unsafe { DragQueryFileW(hdrop, i, None) };
            let mut buf = vec![0u16; len as usize + 1];
            // SAFETY: `buf` is sized to hold `len` code units plus the
            // NUL terminator `DragQueryFileW` writes.
            let written = unsafe { DragQueryFileW(hdrop, i, Some(&mut buf[..])) };
            buf.truncate(written as usize);
            paths.push(std::path::PathBuf::from(String::from_utf16_lossy(&buf)));
        }

        // SAFETY: `hdrop` came from this `WM_DROPFILES` message and has
        // not been finished yet; this is its one and only `DragFinish`.
        unsafe {
            DragFinish(hdrop);
        }

        (paths, pt.x as i16, pt.y as i16)
    }

    /// The actual work of `wndproc`'s `WM_SIZE` arm — `resize_surface`,
    /// debounce `note`, (re)arm [`RESIZE_TIMER_ID`], `InvalidateRect` —
    /// factored out so the resync path (below) can run the
    /// identical sequence against a size read from `GetClientRect` rather
    /// than `WM_SIZE`'s own `lparam`, once a ceded `WM_SIZE`/
    /// `WM_DPICHANGED` notification needs replaying after the fact. See
    /// `WindowState::pending_resize_resync`'s doc for why that replay is
    /// necessary at all.
    fn apply_resize<A: AppLogic>(ws: &WindowState<A>, hwnd: HWND, width: u32, height: u32) {
        let viewport = {
            let mut s = ws.state.borrow_mut();
            // Recreate the render target first if a prior `EndDraw`
            // failure (see `backend.rs`'s `end_frame`) dropped it —
            // `resize_surface` alone is a no-op on the render-target side
            // while `surface` is `None`.
            let _ = s.backend.ensure_surface();
            // Best-effort: a failed resize (device lost mid-drag) leaves
            // the old-sized target in place for this frame; the next
            // `WM_PAINT`/`WM_SIZE` tries `ensure_surface` again.
            let _ = s.backend.resize_surface(width, height);
            s.backend.viewport()
        };
        // Debounce the `WindowResized` *dispatch* to the app
        // — painting stays live regardless, via
        // `resize_surface` above and `InvalidateRect` below on every call.
        // `note()` stashes the latest size; `SetTimer` (re)arms the
        // shared `RESIZE_TIMER_ID` timer, which Win32 resets rather than
        // stacking when it's already pending on this `hwnd` — so a live
        // resize drag keeps pushing the deadline out and only the final
        // `WM_TIMER`, once the drag settles for `RESIZE_SETTLE`, actually
        // fires and dispatches.
        ws.resize_debouncer.borrow_mut().note(viewport);
        // SAFETY: `hwnd` is this dispatch's own window; `SetTimer` with
        // `lpTimerFunc: None` posts `WM_TIMER` through the normal message
        // queue rather than invoking a raw function pointer.
        unsafe {
            SetTimer(
                Some(hwnd),
                RESIZE_TIMER_ID,
                RESIZE_SETTLE.as_millis() as u32,
                None,
            );
        }
        // SAFETY: `hwnd` is this dispatch's own window; `InvalidateRect`
        // takes only handles/rects.
        unsafe {
            let _ = InvalidateRect(Some(hwnd), None, false);
        }
    }

    /// Replays a `WM_SIZE`/`WM_DPICHANGED` notification that
    /// the top-of-`wndproc` `pump_depth.is_pumping()` check ceded
    /// to `DefWindowProcW` instead of handling, because it arrived
    /// re-entrantly while a `super::guarded_call` borrow was already live
    /// on this thread (chiefly: `ShowWindow(SW_MAXIMIZE)`, called
    /// synchronously from `WinBackend::toggle_window_maximize` inside
    /// `app.handle`, sends `WM_SIZE` before it returns). Called from the
    /// top of `wndproc`, *after* the `is_pumping()` check has already
    /// confirmed no guard is live — so `ws.state.borrow_mut()` here can't
    /// collide with anything, and `GetClientRect` reads the real, settled
    /// post-maximize/post-DPI-change size rather than whatever `lparam`
    /// the (ceded, now-stale) original message carried.
    fn resync_pending_resize<A: AppLogic>(ws: &WindowState<A>, hwnd: HWND) {
        if !ws.pending_resize_resync.replace(false) {
            return;
        }
        let mut rect = RECT::default();
        // SAFETY: `rect` is stack-local and outlives this call; `hwnd` is
        // caller-supplied and still live.
        let (width, height) = unsafe {
            let _ = GetClientRect(hwnd, &mut rect);
            // `GetClientRect` always yields `left`/`top` of `0`, so
            // `right`/`bottom` are the client size and never negative —
            // the cast to `u32` is a plain narrow, not a truncation of a
            // meaningfully negative value.
            (
                (rect.right - rect.left) as u32,
                (rect.bottom - rect.top) as u32,
            )
        };
        apply_resize(ws, hwnd, width, height);
    }

    /// The Win32 window procedure. Monomorphized once per concrete `A`
    /// (see module docs) so `RegisterClassExW` gets a real function
    /// pointer despite `run` being generic.
    ///
    /// # Safety
    ///
    /// Called only by Windows via `DispatchMessageW`/directly during
    /// `CreateWindowExW` (`WM_NCCREATE`), per the standard `WNDPROC`
    /// contract. `GWLP_USERDATA` is trusted to hold either `0` (no state
    /// yet — every message before `WM_NCCREATE` sets it) or a valid
    /// `*const WindowState<A>` that outlives every message this function
    /// will ever receive for this `hwnd` (guaranteed by `WinRunner::finish`
    /// freeing it only after `WM_QUIT` — for this same `hwnd` — has
    /// already been observed, or `run_inner`'s/`WinRunner::drop`'s
    /// teardown for an earlier exit).
    unsafe extern "system" fn wndproc<A: AppLogic + 'static>(
        hwnd: HWND,
        msg: u32,
        wparam: WPARAM,
        lparam: LPARAM,
    ) -> LRESULT {
        if msg == WM_NCCREATE {
            // SAFETY: `WM_NCCREATE`'s `lparam` always points at a live
            // `CREATESTRUCTW` for the duration of this call — that's the
            // OS's own contract for this message.
            let cs = lparam.0 as *const CREATESTRUCTW;
            if !cs.is_null() {
                // SAFETY: `cs` was just null-checked and, per the comment
                // above, the OS guarantees it points at a live
                // `CREATESTRUCTW` for the duration of this `WM_NCCREATE`
                // dispatch; `lpCreateParams` is a plain field read.
                let create_params = unsafe { (*cs).lpCreateParams };
                // SAFETY: `hwnd` is this call's own window (`WM_NCCREATE`
                // is dispatched with the window that's still being
                // created); `SetWindowLongPtrW` stores an opaque `isize`
                // — no dereference happens here, only later reads via
                // `GetWindowLongPtrW` below, gated by this function's own
                // `# Safety` contract on what that stored value means.
                unsafe {
                    SetWindowLongPtrW(hwnd, GWLP_USERDATA, create_params as isize);
                }
            }
            // SAFETY: `hwnd`/`msg`/`wparam`/`lparam` are this call's own
            // parameters, forwarded unchanged — `DefWindowProcW` is the
            // OS's own fallback handler and imposes no precondition beyond
            // "a live `wndproc` invocation", true by construction here.
            // Every other `DefWindowProcW` call in this function has the
            // same argument shape and the same justification; later ones
            // in this file just say "see `WM_NCCREATE`'s `DefWindowProcW`
            // above" rather than repeating this paragraph.
            return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
        }

        // SAFETY: `hwnd` is this call's own window; `GWLP_USERDATA`
        // either still holds the `0` `WNDCLASSEXW`/`CreateWindowExW`
        // implicitly initialize it to, or the `*const WindowState<A>` the
        // `WM_NCCREATE` arm above stored — both are valid `isize` values
        // to read back, per `GetWindowLongPtrW`'s own contract. The cast
        // to `*const WindowState<A>` that follows is not itself unsafe;
        // it's only dereferenced past the `is_null()` check below.
        let state_ptr = unsafe { GetWindowLongPtrW(hwnd, GWLP_USERDATA) } as *const WindowState<A>;
        if state_ptr.is_null() {
            // Messages Windows can send before `WM_NCCREATE` populates
            // `GWLP_USERDATA` (rare, but the contract allows it) — no
            // app/backend to dispatch to yet.
            //
            // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW` above.
            return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
        }
        // SAFETY: see this function's contract above.
        let ws: &WindowState<A> = unsafe { &*state_ptr };

        // A message re-entering `wndproc` while a `super::
        // guarded_call` borrow (`dispatch`'s `app.handle`, or `WM_PAINT`'s
        // `app.render`, below) is already live on this same thread — see
        // `super::guarded_call`'s and `dispatch`'s docs for the hazard
        // this closes. Cede to the default window proc rather than ever
        // touching `ws.state` while that's a live possibility; the next
        // non-reentrant message (once the outer guarded call returns)
        // handles normally.
        //
        // `WM_SIZE`/`WM_DPICHANGED` are a one-shot state
        // notification, not input — unlike every other message this
        // cedes, there is no later arrival of the *same* notification to
        // fall back on, so ceding one silently loses it (the "stretched,
        // mis-hit-tested window after a drawn maximize button" bug this
        // issue reports). Record that a resync is owed instead; the
        // `resync_pending_resize` call below, run from the next
        // non-reentrant invocation of this function, replays it once it's
        // actually safe to touch `ws.state` again.
        if ws.pump_depth.is_pumping() {
            if msg == WM_SIZE || msg == WM_DPICHANGED {
                ws.pending_resize_resync.set(true);
            }
            // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW` above.
            return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
        }

        // Replay any `WM_SIZE`/`WM_DPICHANGED` the branch
        // above deferred while a guarded call was in flight. Must run
        // before `match msg` below so a resize that settles exactly on
        // this message (e.g. this very message is the first `WM_PAINT`
        // after a maximize) still sees the corrected surface size.
        resync_pending_resize(ws, hwnd);

        match msg {
            WM_SIZE => {
                // `lparam`'s low/high words are the new client width/height
                // in pixels — the standard `WM_SIZE` payload shape.
                let (width, height) = size_from_lparam(lparam.0);
                apply_resize(ws, hwnd, width, height);
                LRESULT(0)
            }
            WM_DPICHANGED => {
                // `wparam`'s low word is the new DPI (`x` and `y` are
                // always equal on Windows) — see `WM_DPICHANGED`'s docs.
                let scale = dpi_scale_from_wparam(wparam.0);
                {
                    let mut s = ws.state.borrow_mut();
                    s.backend.set_dpi_scale(scale);
                }
                // `lparam` points at Windows' suggested new window rect
                // for the new DPI — applying it keeps the window's
                // *physical* on-screen size roughly constant across the
                // monitor change instead of staying pinned to its old
                // pixel dimensions (which would now be the wrong physical
                // size on the new monitor).
                let suggested = lparam.0 as *const RECT;
                if !suggested.is_null() {
                    // SAFETY: `suggested` was just null-checked and, per
                    // `WM_DPICHANGED`'s documented contract, `lparam`
                    // points at a live `RECT` for the duration of this
                    // dispatch; `*suggested` is a plain-old-data copy, not
                    // a retained reference.
                    let r = unsafe { *suggested };
                    // SAFETY: `hwnd` is this dispatch's own window; `r`
                    // (copied above) supplies plain integer coordinates,
                    // no pointer.
                    unsafe {
                        let _ = SetWindowPos(
                            hwnd,
                            None,
                            r.left,
                            r.top,
                            r.right - r.left,
                            r.bottom - r.top,
                            SWP_NOZORDER | SWP_NOACTIVATE,
                        );
                    }
                }
                dispatch(ws, hwnd, UiEvent::DpiChanged(scale));
                LRESULT(0)
            }
            WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN | WM_XBUTTONDOWN => {
                if let Some(button) = win_mouse_button_for_message(msg, wparam.0) {
                    let (x, y) = point_from_lparam(lparam.0);
                    let scale = ws.state.borrow().backend.viewport().scale;
                    let modifiers = win_key_modifiers();
                    // Route through `dispatch_click` (text-region/
                    // scrollbar drag hit-testing) before `dispatch_event`'s
                    // own pre-processing, instead of handing the raw
                    // `MouseDown` straight to `dispatch` — see
                    // `dispatch_with`'s doc.
                    // `win_button_down` is an unconditional constructor —
                    // it always returns `MouseDown` — so this destructure
                    // can never take the `else` branch.
                    let UiEvent::MouseDown { position, .. } =
                        win_button_down(button, x, y, scale, modifiers)
                    else {
                        unreachable!("win_button_down always returns UiEvent::MouseDown")
                    };
                    dispatch_with(ws, hwnd, |backend, app| {
                        super::route_mouse_down(backend, app, position, button, modifiers)
                    });
                }
                // `WM_XBUTTONDOWN`/`WM_XBUTTONUP` are the one pair in this
                // group whose docs require returning `TRUE` when handled —
                // every other message here (and everywhere else in this
                // `wndproc`) wants `0`.
                if msg == WM_XBUTTONDOWN {
                    LRESULT(1)
                } else {
                    LRESULT(0)
                }
            }
            WM_LBUTTONUP | WM_RBUTTONUP | WM_MBUTTONUP | WM_XBUTTONUP => {
                if let Some(button) = win_mouse_button_for_message(msg, wparam.0) {
                    let (x, y) = point_from_lparam(lparam.0);
                    let scale = ws.state.borrow().backend.viewport().scale;
                    // Route through `dispatch_mouse_up` (ends an
                    // in-progress scrollbar/text-selection drag) — see
                    // `dispatch_with`'s doc.
                    // `win_button_up` is an unconditional constructor — it
                    // always returns `MouseUp` — so this destructure can
                    // never take the `else` branch.
                    let UiEvent::MouseUp { position, .. } = win_button_up(button, x, y, scale)
                    else {
                        unreachable!("win_button_up always returns UiEvent::MouseUp")
                    };
                    dispatch_with(ws, hwnd, |backend, app| {
                        super::route_mouse_up(backend, app, position, button)
                    });
                }
                if msg == WM_XBUTTONUP {
                    LRESULT(1)
                } else {
                    LRESULT(0)
                }
            }
            WM_MOUSEMOVE => {
                let (x, y) = point_from_lparam(lparam.0);
                let scale = ws.state.borrow().backend.viewport().scale;
                let buttons = ButtonMask {
                    left: wparam.0 & MK_LBUTTON != 0,
                    right: wparam.0 & MK_RBUTTON != 0,
                    middle: wparam.0 & MK_MBUTTON != 0,
                };
                // Route through `dispatch_mouse_drag` so a
                // `TextSelection`/scrollbar drag armed by the button-down
                // handler above emits `TextSelectionChanged`/scroll events
                // — see `dispatch_with`'s doc.
                // `win_mouse_moved` is an unconditional constructor — it
                // always returns `MouseMoved` — so this destructure can
                // never take the `else` branch.
                let UiEvent::MouseMoved { position, .. } = win_mouse_moved(x, y, scale, buttons)
                else {
                    unreachable!("win_mouse_moved always returns UiEvent::MouseMoved")
                };
                dispatch_with(ws, hwnd, |backend, app| {
                    super::route_mouse_move(backend, app, position, buttons)
                });
                LRESULT(0)
            }
            WM_MOUSEWHEEL | WM_MOUSEHWHEEL => {
                // Unlike every other mouse message, `WM_MOUSEWHEEL`'s
                // `lparam` carries **screen** coordinates — `ScreenToClient`
                // converts before handing off to `win_wheel_to_uievent`,
                // which (like every other translator here) expects
                // client-area pixels. See `super::events`' module docs.
                // Forward every message's own delta immediately and in full
                // — no per-axis accumulation, no gating on a full notch.
                // `win_wheel_to_uievent` already divides by `WHEEL_DELTA`
                // into a fractional-notch `ScrollDelta`, so a high-
                // resolution wheel/trackpad message smaller than one notch
                // still produces a proportional sub-row `UiEvent::Scroll`
                // rather than being withheld until several messages sum to
                // a full notch. This matches the GTK/macOS translators,
                // which likewise forward the native delta with only a
                // sign/precision cast (see `super::events`' module docs);
                // reducing any nonzero magnitude to a whole row is a
                // decision the shared `primitives::scrollbar::wheel_row_delta`
                // makes once for every backend, not something this
                // translator should pre-empt by withholding events.
                let raw_delta = wheel_delta_from_wparam(wparam.0);
                let horizontal = msg == WM_MOUSEHWHEEL;
                let (screen_x, screen_y) = point_from_lparam(lparam.0);
                let mut pt = POINT {
                    x: screen_x as i32,
                    y: screen_y as i32,
                };
                // SAFETY: `hwnd` is this dispatch's own window; `pt` is
                // stack-local and outlives the call, `ScreenToClient`
                // writes through it in place.
                unsafe {
                    let _ = ScreenToClient(hwnd, &mut pt);
                }
                let scale = ws.state.borrow().backend.viewport().scale;
                let event =
                    win_wheel_to_uievent(raw_delta, pt.x as i16, pt.y as i16, scale, horizontal);
                dispatch(ws, hwnd, event);
                LRESULT(0)
            }
            WM_KEYDOWN => {
                // `WM_KEYUP` isn't separately dispatched: quadraui's
                // `UiEvent` has no key-release variant (mirroring the GTK
                // translator, which only wires `key-press-event`) — a
                // future release-tracking need should add that variant
                // rather than inventing one here. `TranslateMessage` in
                // `WinRunner::run_one`'s drain loop reads the raw
                // `WM_KEYDOWN` from the queue regardless of what this arm
                // returns, so intercepting it here doesn't suppress the
                // `WM_CHAR` it generates for printable keys.
                // Truncate rather than trust the upper `WPARAM` bits are
                // zero — a virtual-key code is always a single byte, same
                // masking discipline `super::msg`'s decoders use for
                // `LPARAM`.
                let vk = (wparam.0 & 0xFF) as u32;
                let repeat = is_repeat_from_lparam(lparam.0);
                let modifiers = win_key_modifiers();
                if let Some(event) = wm_keydown_to_uievent(vk, modifiers, repeat) {
                    dispatch(ws, hwnd, event);
                }
                LRESULT(0)
            }
            WM_CHAR => {
                // `wparam`'s low word is the UTF-16 code unit
                // `TranslateMessage` resolved through the active keyboard
                // layout. Surrogate-pair characters (outside the BMP) are
                // dropped here — `char::from_u32` returns `None` for a
                // lone surrogate half — same scope boundary
                // `wm_char_to_uievent`'s docs describe.
                let repeat = is_repeat_from_lparam(lparam.0);
                // Truncate to the 16-bit code unit before widening — same
                // reasoning as `WM_KEYDOWN`'s `vk` above.
                if let Some(c) = char::from_u32((wparam.0 & 0xFFFF) as u32) {
                    let modifiers = win_key_modifiers();
                    if let Some(event) = wm_char_to_uievent(c, modifiers, repeat) {
                        dispatch(ws, hwnd, event);
                    }
                }
                LRESULT(0)
            }
            WM_SYSKEYDOWN => {
                // Alt-held twin of `WM_KEYDOWN` — fires for Alt+F4,
                // menu mnemonics, and any Alt accelerator an app
                // registers. Reuses the exact same translator; the only
                // new decision is what to do about `DefWindowProcW`.
                //
                // Deliberately forwarded to `DefWindowProcW` (not
                // swallowed by returning `LRESULT(0)`, unlike every other
                // handled arm in this `wndproc`): `DefWindowProcW`'s own
                // `WM_SYSKEYDOWN` handling is what turns Alt+F4 into
                // `WM_SYSCOMMAND(SC_CLOSE)` -> `WM_CLOSE` (see the
                // `WM_CLOSE` arm below, which owns the actual close/veto
                // decision via `UiEvent::WindowClose`) and what opens the
                // system menu on Alt+Space — this runner reimplements
                // neither. So `Alt+F4` reaches the app as a `KeyPressed`
                // (`NamedKey::F(4)`, `modifiers.alt == true`) *and* still
                // closes the window through the normal `WM_CLOSE` veto
                // path — an app that wants to prevent the close does so
                // there, exactly as it already vetoes a mouse-driven
                // close, not by intercepting this message.
                let vk = (wparam.0 & 0xFF) as u32;
                let repeat = is_repeat_from_lparam(lparam.0);
                let modifiers = win_key_modifiers();
                if let Some(event) = wm_keydown_to_uievent(vk, modifiers, repeat) {
                    dispatch(ws, hwnd, event);
                }
                // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW` (top of
                // this function) — forwarded unchanged, deliberately, per
                // the comment above.
                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
            }
            WM_SYSCHAR => {
                // Alt-held twin of `WM_CHAR` — menu-mnemonic
                // characters (Alt+letter). Same translator, same
                // forward-to-`DefWindowProcW` reasoning as `WM_SYSKEYDOWN`
                // above (this runner has no menu, so `DefWindowProcW`'s
                // own handling here is just the system beep for an
                // unmatched mnemonic — harmless).
                let repeat = is_repeat_from_lparam(lparam.0);
                if let Some(c) = char::from_u32((wparam.0 & 0xFFFF) as u32) {
                    let modifiers = win_key_modifiers();
                    if let Some(event) = wm_char_to_uievent(c, modifiers, repeat) {
                        dispatch(ws, hwnd, event);
                    }
                }
                // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW` (top of
                // this function) — forwarded unchanged, deliberately, per
                // the comment above.
                unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
            }
            WM_SETFOCUS => {
                dispatch(ws, hwnd, win_focus_to_uievent(true));
                LRESULT(0)
            }
            WM_KILLFOCUS => {
                dispatch(ws, hwnd, win_focus_to_uievent(false));
                LRESULT(0)
            }
            WM_PAINT => {
                // Routed through `super::guarded_call` for the same
                // reason as `dispatch`: `app.render` can hit the
                // same synchronous-reentrancy hazard `app.handle` can.
                // The top-of-`wndproc` `is_pumping()` check above already
                // guarantees `WM_PAINT` itself is never the *reentrant*
                // call, but `guarded_call` still has to be the one
                // holding `ws.pump_depth`'s guard for the duration of
                // `app.render` — otherwise a nested pump triggered *from
                // inside* `render` wouldn't be caught by that same check.
                let _ = super::guarded_call(&ws.state, &ws.pump_depth, |run_state| {
                    // Recreate the render target if a prior `EndDraw`
                    // failure dropped it (device lost, RDP session
                    // change — see `backend.rs`'s `end_frame` docs).
                    // Best-effort: if recreation fails again (surface
                    // still unavailable), `begin_frame`/`end_frame`
                    // below are no-ops while `surface` stays `None`, and
                    // the next `WM_PAINT`/`WM_SIZE` tries again.
                    let _ = run_state.backend.ensure_surface();
                    let viewport = run_state.backend.viewport();
                    let RunState { app, backend } = run_state;
                    super::render_frame(backend, app, viewport);
                });
                // Direct2D draws straight to the swap chain via the
                // `ID2D1HwndRenderTarget` — no GDI `HDC`/`PAINTSTRUCT`
                // involved, so this validates the update region directly
                // instead of the usual `BeginPaint`/`EndPaint` pair (the
                // standard pattern for D2D-only `WM_PAINT` handlers).
                //
                // SAFETY: `hwnd` is this dispatch's own window;
                // `ValidateRect(hwnd, None)` validates the whole client
                // area, no pointer beyond the handle.
                unsafe {
                    let _ = ValidateRect(Some(hwnd), None);
                }
                LRESULT(0)
            }
            WM_NCCALCSIZE => {
                // Fold a host's drawn title-bar band into the native
                // caption instead of stacking a second, always-drawn row
                // underneath a still-real native one — the custom-caption
                // half of this issue's ask (the other half is
                // `WM_NCHITTEST`, below).
                //
                // `wparam != 0` is the "validate/adjust the proposed
                // client rect" form (the one this window ever receives);
                // the `NCCALCSIZE_PARAMS` it points at is in/out, and
                // `rgrc[0]` starts out holding the *proposed new window
                // rect* (screen coordinates) before any adjustment.
                if wparam.0 != 0 {
                    // SAFETY: `WM_NCCALCSIZE`'s contract guarantees
                    // `lparam` points at a live `NCCALCSIZE_PARAMS` for
                    // the duration of this call when `wparam != 0`.
                    let params = unsafe { &mut *(lparam.0 as *mut NCCALCSIZE_PARAMS) };
                    // Capture the window's own outer top edge before
                    // `DefWindowProcW` shrinks `rgrc[0]` for the standard
                    // caption + resize-border reservation.
                    let outer_top = params.rgrc[0].top;
                    // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW` (top
                    // of this function) — forwarded unchanged; `params`
                    // above is a live borrow of the same `*mut
                    // NCCALCSIZE_PARAMS` this call also writes through
                    // (that's the point — this lets `DefWindowProcW` do
                    // its own in-place adjustment before `outer_top` is
                    // reapplied below), which is fine since nothing reads
                    // `params` again until after this call returns.
                    unsafe {
                        DefWindowProcW(hwnd, msg, wparam, lparam);
                    }
                    // Push `top` back out to that outer edge — zeroing
                    // the caption-height reservation entirely (this
                    // issue's "keeps the window's outer bounds but
                    // zeroes the caption height") while leaving whatever
                    // `DefWindowProcW` just did to `left`/`right`/`bottom`
                    // (the resize-border inset) alone. The client area —
                    // and so the app's own drawn band, painted at its
                    // top — now extends all the way to the window's top
                    // edge instead of stopping below a reserved native
                    // caption strip.
                    params.rgrc[0].top = outer_top;
                    LRESULT(0)
                } else {
                    // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW`
                    // (top of this function) — forwarded unchanged.
                    unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
                }
            }
            WM_NCHITTEST => {
                // The `WM_NCHITTEST` half of the custom-caption
                // extension. Ask Windows for its own answer first — it
                // still owns the resize-border edges and anything else
                // outside the client area — and only reclassify an
                // ordinary `HTCLIENT` answer into `HTCAPTION` when the
                // point falls inside a host-registered title-bar drag
                // band that isn't itself covered by a smaller zone.
                // See `WinBackend::nc_hit_test`'s doc for the exact
                // classification this defers to.
                // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW`.
                let default = unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };
                if default.0 as u32 != HTCLIENT {
                    return default;
                }
                // `lparam` carries **screen** coordinates for this
                // message (same as `WM_MOUSEWHEEL` above) —
                // `ScreenToClient` converts before handing off to
                // `WinBackend::nc_hit_test`, which (like every other
                // consumer of a `Rect` in this crate) expects DIPs.
                let (screen_x, screen_y) = point_from_lparam(lparam.0);
                let mut pt = POINT {
                    x: screen_x as i32,
                    y: screen_y as i32,
                };
                // SAFETY: `hwnd` is this dispatch's own window; `pt` is
                // stack-local and outlives the call.
                unsafe {
                    let _ = ScreenToClient(hwnd, &mut pt);
                }
                let scale = ws.state.borrow().backend.viewport().scale;
                // Guards the same way `win::events::to_dip` does — an
                // (in-practice-impossible) zero scale degrades to
                // unscaled rather than producing `inf`/`NaN`.
                let (dip_x, dip_y) = if scale == 0.0 {
                    (pt.x as f32, pt.y as f32)
                } else {
                    (pt.x as f32 / scale, pt.y as f32 / scale)
                };
                match ws.state.borrow().backend.nc_hit_test(dip_x, dip_y) {
                    Some(true) => LRESULT(HTCAPTION as isize),
                    Some(false) | None => default,
                }
            }
            WM_SETCURSOR => {
                // Windows asks "what cursor belongs here?" via this
                // message on every mouse move over the window, including
                // moves that never reach `WM_MOUSEMOVE` (e.g. the pointer
                // re-entering after a click elsewhere). The low word of
                // `lparam` is the hit-test code from the preceding
                // `WM_NCHITTEST`; only handle the client area
                // (`HTCLIENT`) ourselves and re-apply
                // `WinBackend::current_pointer_shape` there — everywhere
                // else (the resize border, titlebar, …) is native
                // `WS_OVERLAPPEDWINDOW` chrome, so `DefWindowProcW`
                // already draws the right cursor for it and must stay in
                // control.
                let hit_test = (lparam.0 as usize) & 0xFFFF;
                if hit_test == HTCLIENT as usize {
                    ws.state.borrow().backend.apply_current_cursor();
                    LRESULT(1)
                } else {
                    // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW`
                    // (top of this function) — forwarded unchanged.
                    unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
                }
            }
            WM_TIMER => {
                // The one-shot headless-smoke timer armed by
                // `create_window`, if `QUADRAUI_WIN_SMOKE_MS` was set —
                // see the module doc's "Headless smoke mode" section.
                // The resize-settle debounce timer armed by the
                // `WM_SIZE` arm above.
                // `FRAME_TIMER_ID` — the scheduled-wake timer armed
                // by `WinBackend::request_frame_in`, itself reached via
                // `Reaction::RedrawAfter`/`EventOutcome::RedrawAfter`.
                // `IDLE_POLL_TIMER_ID` — the coarse idle-poll safety net
                // armed once by `create_window`, mirroring the
                // `IDLE_POLL_CEILING` fallback TUI/GTK/macOS also keep.
                // `CARET_BLINK_TIMER_ID` — the caret-blink tick armed once
                // by `create_window`, ticking `WinBackend::tick_caret_blink`
                // directly rather than going through `tick`.
                // Any other timer id is none of this runner's business
                // and falls through to `DefWindowProcW` untouched.
                //
                // SAFETY: (every `unsafe` block in this arm) `hwnd` is
                // this dispatch's own, still-live window. `KillTimer`
                // takes only a handle and a timer id — it is a documented
                // no-op, not an error, if that id isn't currently armed
                // (e.g. two timers racing to fire the same tick), so
                // there's no "must be armed" precondition to uphold.
                // `tick`/`dispatch` below act on `Reaction::Exit`
                // themselves (see `dispatch_with`'s doc), so this arm
                // needs no `Reaction::Exit`/`DestroyWindow` check of its
                // own.
                if wparam.0 == SMOKE_TIMER_ID {
                    // SAFETY: see this arm's opening comment above.
                    unsafe {
                        let _ = KillTimer(Some(hwnd), SMOKE_TIMER_ID);
                    }
                    run_smoke_check(ws, hwnd);
                    // SAFETY: see this arm's opening comment above.
                    unsafe {
                        let _ = DestroyWindow(hwnd);
                    }
                    LRESULT(0)
                } else if wparam.0 == RESIZE_TIMER_ID {
                    // SAFETY: see this arm's opening comment above.
                    unsafe {
                        let _ = KillTimer(Some(hwnd), RESIZE_TIMER_ID);
                    }
                    // The drag settled with no new `WM_SIZE` for
                    // `RESIZE_SETTLE` — dispatch the coalesced size now.
                    if let Some(viewport) = ws.resize_debouncer.borrow_mut().take() {
                        dispatch(ws, hwnd, UiEvent::WindowResized { viewport });
                    }
                    LRESULT(0)
                } else if wparam.0 == FRAME_TIMER_ID {
                    // SAFETY: see this arm's opening comment above.
                    unsafe {
                        let _ = KillTimer(Some(hwnd), FRAME_TIMER_ID);
                    }
                    // The scheduled wake this timer existed for has
                    // arrived — run `tick`. `tick` itself
                    // re-arms a fresh timer via `request_frame_in` if it
                    // wants to be woken again (the chained-rearm pattern
                    // `Reaction::RedrawAfter`'s doc describes), and acts
                    // on `Reaction::Exit` itself.
                    tick(ws, hwnd);
                    LRESULT(0)
                } else if wparam.0 == IDLE_POLL_TIMER_ID {
                    // The coarse safety-net fire. Deliberately never
                    // `KillTimer`'d — `SetTimer`'s own repeat keeps
                    // re-posting this every `IDLE_POLL_CEILING`
                    // regardless of whether `tick`/anything else asked to
                    // be woken, exactly like TUI/GTK's unconditional idle
                    // poll and macOS's repeating `idlePollTick:` `NSTimer`.
                    tick(ws, hwnd);
                    LRESULT(0)
                } else if wparam.0 == CARET_BLINK_TIMER_ID {
                    // Deliberately never `KillTimer`'d, same posture as
                    // `IDLE_POLL_TIMER_ID` immediately above. Ticks
                    // `WinBackend::tick_caret_blink` directly instead of
                    // going through `tick`/`AppLogic::tick`, so this can
                    // never double-tick against that path's own
                    // frame/idle timers; only invalidates the window when
                    // the blink state actually flipped phase.
                    let redraw = ws
                        .state
                        .borrow_mut()
                        .backend
                        .tick_caret_blink(Instant::now());
                    if redraw {
                        // SAFETY: `hwnd` is this dispatch's own, still-live
                        // window; `InvalidateRect` takes only
                        // handles/rects, no raw pointer arithmetic.
                        unsafe {
                            let _ = InvalidateRect(Some(hwnd), None, false);
                        }
                    }
                    LRESULT(0)
                } else {
                    // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW`
                    // (top of this function) — forwarded unchanged.
                    unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
                }
            }
            WM_QUADRAUI_USER_EVENT => {
                // Woke by `WinBackend::waker()` after a background
                // thread queued one or more `UiEvent::User` payloads.
                // `wndproc` already holds everything a live producer
                // would need (`ws`, `hwnd`), so this drains and
                // dispatches directly, the same `dispatch` helper every
                // other message in this match uses.
                let events = ws.state.borrow_mut().backend.drain_user_events();
                for event in events {
                    // `dispatch` acts on `Reaction::Exit` itself (see
                    // `dispatch_with`'s doc); this `break` just stops
                    // feeding the app further queued events once it has
                    // asked to exit.
                    if dispatch(ws, hwnd, event) == Reaction::Exit {
                        break;
                    }
                }
                LRESULT(0)
            }
            WM_QUADRAUI_TRAY_CALLBACK => {
                // Posted by `Shell_NotifyIconW` on every mouse event
                // over the tray icon. Classic (pre-`NOTIFYICON_VERSION_4`)
                // contract: `lparam` carries the raw Win32 mouse message
                // that fired (`WM_LBUTTONUP`/`WM_RBUTTONUP`/etc — see
                // `win::tray::tray_click_button`'s doc); `wparam` carries
                // the icon's `uID`, unread here since this backend owns
                // exactly one tray icon.
                let Some(button) = crate::win::tray::tray_click_button(lparam.0 as u32) else {
                    return LRESULT(0);
                };
                let menu = ws.state.borrow().backend.tray_menu();
                if let Some(menu) = menu {
                    // A menu is attached — show it and stop there,
                    // mirroring `NSStatusItem.menu`'s "the menu
                    // supersedes the plain click" behaviour (see
                    // `win::tray`'s module doc). `track_menu` blocks
                    // synchronously on `TrackPopupMenuEx`, the same
                    // modal-pop-up posture
                    // `macos::menu_bar_install::show_context_menu` has.
                    // `dispatch` acts on `Reaction::Exit` itself (see
                    // `dispatch_with`'s doc); the early `return` below
                    // just skips the `ContextMenuDismissed` dispatch once
                    // the app has asked to exit.
                    if let Some(id) = crate::win::tray::track_menu(hwnd, &menu) {
                        if dispatch(ws, hwnd, UiEvent::ContextMenuItemActivated(id))
                            == Reaction::Exit
                        {
                            return LRESULT(0);
                        }
                    }
                    dispatch(ws, hwnd, UiEvent::ContextMenuDismissed);
                } else {
                    dispatch(ws, hwnd, crate::win::tray::plain_click_event(button));
                }
                LRESULT(0)
            }
            WM_DROPFILES => {
                // `wparam` carries the `HDROP` handle — `DragAcceptFiles`
                // (called once after the window is shown, in
                // `create_window`) is what makes this message arrive at
                // all. Decode via
                // the real Shell32 calls (`paths_from_dropfiles`, below)
                // then hand off to the pure `win_files_dropped`
                // translator, same "decode raw params, then translate"
                // split every other message arm here uses.
                let hdrop = HDROP(wparam.0 as *mut c_void);
                let (paths, x, y) = paths_from_dropfiles(hdrop);
                if !paths.is_empty() {
                    let scale = ws.state.borrow().backend.viewport().scale;
                    dispatch(ws, hwnd, win_files_dropped(paths, x, y, scale));
                }
                LRESULT(0)
            }
            WM_COPYDATA => {
                // Arrives from `forward_argv_to_existing_instance` — a
                // second launch of this app, with
                // `RunConfig::single_instance` on, detected this instance
                // already holds the single-instance mutex and forwarded
                // its own `argv` here instead of opening a second window.
                //
                // SAFETY: `WM_COPYDATA`'s contract guarantees `lparam`
                // is a valid `*const COPYDATASTRUCT` for the duration of
                // this call — `SendMessageW` (unlike `PostMessageW`)
                // blocks the sender until this handler returns, so the
                // buffer it points into can't be freed out from under us.
                let cds = unsafe { &*(lparam.0 as *const COPYDATASTRUCT) };
                // Reject anything that isn't tagged as an argv-forward
                // before touching `cds.lpData`/bringing this window
                // forward. `LRESULT(0)` here means "unhandled", the
                // same as any other `WM_COPYDATA` this window doesn't
                // recognize.
                if cds.dwData != ARGV_FORWARD_TAG {
                    return LRESULT(0);
                }
                let code_units = cds.cbData as usize / size_of::<u16>();
                let units =
                    // SAFETY: `cds.lpData`/`cds.cbData` describe the same
                    // live buffer `cds` itself points into, per the same
                    // `WM_COPYDATA` contract above.
                    unsafe { std::slice::from_raw_parts(cds.lpData.cast::<u16>(), code_units) };
                let payload = String::from_utf16_lossy(units);
                // Decoded via `super::decode_copydata_argv`, the exact
                // inverse of `forward_argv_to_existing_instance`'s
                // `super::encode_copydata_argv` — see that function's doc
                // for why the separator is `'\0'`, not `'\n'`.
                let args = super::decode_copydata_argv(&payload);
                // A bare relaunch with no `argv` (the user just wants
                // the existing window brought forward) forwards an empty
                // payload — don't bother the app with a no-op
                // `OpenRequested { urls: [], files: [] }` for that case.
                if !args.is_empty() {
                    dispatch(ws, hwnd, classify_open_args(args));
                }
                // The whole point of forwarding rather than silently
                // dropping a second launch: the user should see *this*
                // window respond, not wonder why nothing happened.
                //
                // SAFETY: `hwnd` is this dispatch's own, still-live
                // window; both calls take only a handle (plus, for
                // `ShowWindow`, a plain show-command enum).
                unsafe {
                    let _ = SetForegroundWindow(hwnd);
                    let _ = ShowWindow(hwnd, SW_RESTORE);
                }
                // Win32 convention: a `WM_COPYDATA` receiver returns
                // nonzero (`TRUE`) to report the message was handled.
                LRESULT(1)
            }
            WM_CLOSE => {
                // Reached both from the title bar's close button and
                // (since #743) from Alt+F4: `WM_SYSKEYDOWN`'s arm above
                // forwards to `DefWindowProcW`, whose own `VK_F4` handling
                // posts `WM_SYSCOMMAND(SC_CLOSE)`, which `DefWindowProcW`
                // in turn resolves to this same `WM_CLOSE`. `dispatch`
                // acts on `Reaction::Exit` itself by destroying the
                // window. An app returning `Reaction::Continue`/`Redraw`
                // here vetoes the close, matching the GTK runner's
                // `Reaction::Exit => window.close()`.
                dispatch(ws, hwnd, UiEvent::WindowClose);
                LRESULT(0)
            }
            WM_DESTROY => {
                // SAFETY: `PostQuitMessage` posts to the calling thread's
                // own message queue by value (an exit code) — no pointer,
                // no handle, no precondition beyond having a message
                // queue, which every `wndproc`-dispatching thread has.
                unsafe {
                    PostQuitMessage(0);
                }
                LRESULT(0)
            }
            // SAFETY: same as `WM_NCCREATE`'s `DefWindowProcW` (top of
            // this function) — forwarded unchanged; this is the final
            // catch-all for every message this `wndproc` doesn't
            // otherwise handle.
            _ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
        }
    }

    /// A live-window `WM_NCHITTEST` round trip. Every other test in
    /// this file proves the Rust-side half — `nc_hit_test`'s
    /// classification, and (in `win::backend`'s own test module) that
    /// `draw_menu_bar`/`draw_status_bar_interactive`/
    /// `draw_command_center` now call `register_zone` for their own
    /// clickable bounds — but the regression only showed up once a
    /// real `WM_NCHITTEST` round-trips through a real `wndproc` on a
    /// real `HWND`. This module creates a real top-level window, paints
    /// real menu-bar / status-bar / command-centre widgets into its
    /// title-bar band via the real `WinBackend::draw_*` calls (so it
    /// exercises the actual fix, not a hand-registered zone), then
    /// drives `WM_NCHITTEST` with `SendMessageW` at each widget's real
    /// resolved centre and at an empty strip of the band between them.
    #[cfg(test)]
    mod live_window_nchittest_tests {
        use super::*;
        use std::sync::{Arc, Mutex};
        use std::time::{Duration, Instant};
        use windows::Win32::Graphics::Gdi::ClientToScreen;

        /// Real DIP centre points [`LiveWindowApp::render`] resolves each
        /// frame from the real `MenuBarLayout`/`StatusBarLayout`/
        /// `CommandCenterLayout` the real `WinBackend` `draw_*` calls hand
        /// back, plus the real `Viewport::scale` those bounds are in —
        /// shared with the probing thread so it computes real screen
        /// coordinates instead of guessing font-metric-dependent pixel
        /// offsets.
        #[derive(Clone, Copy, Debug, Default)]
        struct ProbeTargets {
            file_item: Option<(f32, f32)>,
            close_button: Option<(f32, f32)>,
            search_box: Option<(f32, f32)>,
            empty_band: (f32, f32),
            scale: f32,
        }

        struct LiveWindowApp {
            targets: Arc<Mutex<ProbeTargets>>,
        }

        impl AppLogic for LiveWindowApp {
            type AreaId = ();

            fn render(&self, backend: &mut dyn Backend, _area: ()) {
                let viewport = backend.viewport();
                let band_height = 32.0_f32;
                let band = crate::event::Rect::new(0.0, 0.0, viewport.width, band_height);
                Backend::register_zone(
                    backend,
                    crate::types::WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE),
                    band,
                );

                let bar = crate::MenuBar {
                    id: crate::types::WidgetId::new("probe:bar"),
                    items: vec![crate::MenuBarItem {
                        id: crate::types::WidgetId::new("probe:bar:file"),
                        label: "&File".into(),
                        disabled: false,
                        submenu: None,
                    }],
                    open_item: None,
                    focused_item: None,
                };
                let menu_layout = backend
                    .draw_menu_bar(crate::event::Rect::new(0.0, 0.0, 100.0, band_height), &bar);

                let status = crate::StatusBar {
                    id: crate::types::WidgetId::new("probe:status"),
                    left_segments: vec![],
                    right_segments: vec![crate::StatusBarSegment {
                        text: "X".into(),
                        fg: crate::types::Color::rgb(255, 255, 255),
                        bg: crate::types::Color::rgb(0, 0, 0),
                        bold: false,
                        action_id: Some(crate::types::WidgetId::new("probe:close")),
                    }],
                };
                let status_rect =
                    crate::event::Rect::new(viewport.width - 40.0, 0.0, 40.0, band_height);
                let status_layout = backend.draw_status_bar_interactive(
                    status_rect,
                    &status,
                    &crate::interaction::InteractionState::new(),
                );

                let cc = crate::CommandCenter {
                    id: crate::types::WidgetId::new("probe:cc"),
                    back_enabled: true,
                    forward_enabled: true,
                    search_label: "probe".into(),
                };
                let cc_rect = crate::event::Rect::new(160.0, 0.0, 240.0, band_height);
                let cc_layout = backend.draw_command_center(cc_rect, &cc);

                let file_item = menu_layout
                    .visible_items
                    .iter()
                    .find(|v| v.clickable)
                    .map(|v| {
                        (
                            v.bounds.x + v.bounds.width / 2.0,
                            v.bounds.y + v.bounds.height / 2.0,
                        )
                    });
                // `status_layout`'s `hit_regions` bounds are
                // bar-local (see `register_status_bar_segment_zones`'s
                // doc in `win::backend`), so the real absolute probe
                // point needs `status_rect`'s own origin added back in —
                // deriving it from the bar-local bounds alone would (pre-
                // fix) have landed near this band's *left* edge instead
                // of the close button's real position near the right
                // edge, and could pass "for the wrong reason" by luck
                // landing inside an unrelated zone.
                let close_button = status_layout.hit_regions.iter().find_map(|(r, hit)| {
                    matches!(hit, crate::primitives::status_bar::StatusBarHit::Segment(_)).then(
                        || {
                            (
                                status_rect.x + r.x + r.width / 2.0,
                                status_rect.y + r.y + r.height / 2.0,
                            )
                        },
                    )
                });
                let search_box = cc_layout
                    .search_bounds
                    .map(|r| (r.x + r.width / 2.0, r.y + r.height / 2.0));

                let mut targets = self.targets.lock().unwrap();
                targets.file_item = file_item;
                targets.close_button = close_button;
                targets.search_box = search_box;
                // Between the 100-wide menu-bar rect and the
                // 160-starting command-centre rect — guaranteed clear of
                // every widget above regardless of real glyph metrics,
                // since both rects are fixed-width independent of what
                // text happened to measure inside them.
                targets.empty_band = (130.0, band_height / 2.0);
                targets.scale = viewport.scale;
            }

            fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                match event {
                    UiEvent::WindowClose => Reaction::Exit,
                    _ => Reaction::Continue,
                }
            }
        }

        /// DIP → screen-point conversion for `SendMessageW(WM_NCHITTEST)`:
        /// scales by the window's real DPI ratio (captured from the same
        /// `render` call the target point came from) and maps through
        /// `ClientToScreen` — the exact inverse of `wndproc`'s own
        /// `WM_NCHITTEST` arm (`ScreenToClient` then unscale).
        fn dip_to_screen_lparam(hwnd: HWND, dip: (f32, f32), scale: f32) -> LPARAM {
            let mut pt = POINT {
                x: (dip.0 * scale).round() as i32,
                y: (dip.1 * scale).round() as i32,
            };
            // SAFETY: `hwnd` is the live test window, still open for the
            // duration of this call; `pt` is stack-local.
            unsafe {
                let _ = ClientToScreen(hwnd, &mut pt);
            }
            LPARAM((((pt.y as u16 as u32) << 16) | (pt.x as u16 as u32)) as i32 as isize)
        }

        /// Self-guarding (stderr diagnostic + early return, same posture
        /// as `ctrl_v_delivers_real_clipboard_text_as_clipboard_paste`
        /// above) if the window never becomes findable/painted within
        /// the timeout — this test's contract is "a live interactive
        /// window station", not every CI sandbox.
        #[test]
        #[allow(clippy::print_stderr)]
        fn real_wm_nchittest_excludes_band_widgets_and_caps_the_empty_strip() {
            let targets = Arc::new(Mutex::new(ProbeTargets::default()));
            let app = LiveWindowApp {
                targets: targets.clone(),
            };
            let title = format!(
                "quadraui-nchittest-probe-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            );
            let config = crate::win::run::RunConfig::new(title.clone());

            let runner = std::thread::spawn(move || run(app, config));

            // Poll for the window (`FindWindowW`), bounded — an
            // environment with no interactive window station (window
            // creation fails) reports a diagnostic and returns instead of
            // hanging forever.
            let deadline = Instant::now() + Duration::from_secs(10);
            let class_name = window_class_name(&title);
            let hwnd = loop {
                // SAFETY: `class_name` is a live `Vec<u16>` for the
                // duration of this call.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                if let Ok(hwnd) = found {
                    break Some(hwnd);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(hwnd) = hwnd else {
                eprintln!(
                    "quadraui: skipping \
                     real_wm_nchittest_excludes_band_widgets_and_caps_the_empty_strip — \
                     the test window never became findable within 10s (no interactive \
                     window station on this host?)"
                );
                return;
            };

            // Poll for the first full paint — `ProbeTargets` populated by
            // `LiveWindowApp::render`, same bounded/self-guarding posture.
            let ready = loop {
                let snapshot = *targets.lock().unwrap();
                if snapshot.file_item.is_some()
                    && snapshot.close_button.is_some()
                    && snapshot.search_box.is_some()
                {
                    break Some(snapshot);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(snapshot) = ready else {
                eprintln!(
                    "quadraui: skipping \
                     real_wm_nchittest_excludes_band_widgets_and_caps_the_empty_strip — \
                     the window never painted a full frame within 10s"
                );
                // SAFETY: `hwnd` is still the live test window; `WM_CLOSE`
                // is this window's normal user-close path.
                unsafe {
                    SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
                }
                let _ = runner.join();
                return;
            };

            let assert_hit = |label: &str, dip: (f32, f32), expect_caption: bool| {
                let lparam = dip_to_screen_lparam(hwnd, dip, snapshot.scale);
                let result = {
                    // SAFETY: `hwnd` is still the live test window;
                    // `WM_NCHITTEST` is a pure query with no side effects
                    // to uphold beyond a live window.
                    unsafe { SendMessageW(hwnd, WM_NCHITTEST, Some(WPARAM(0)), Some(lparam)) }
                };
                let is_caption = result.0 as u32 == HTCAPTION;
                assert_eq!(
                    is_caption,
                    expect_caption,
                    "{label}: expected {} but WM_NCHITTEST returned {:#x}",
                    if expect_caption {
                        "HTCAPTION"
                    } else {
                        "not HTCAPTION (HTCLIENT)"
                    },
                    result.0
                );
            };

            // The real fix this issue is about: each widget excludes its
            // own footprint from the OS caption-drag gesture.
            assert_hit("File menu item", snapshot.file_item.unwrap(), false);
            assert_hit(
                "status-bar close segment",
                snapshot.close_button.unwrap(),
                false,
            );
            assert_hit(
                "command-centre search box",
                snapshot.search_box.unwrap(),
                false,
            );
            // The other half of the same acceptance scenario: empty band
            // space still drags/maximizes like a native titlebar.
            assert_hit("empty band strip", snapshot.empty_band, true);

            // SAFETY: `hwnd` is still the live test window; `WM_CLOSE` is
            // the normal user-close path this window's `wndproc` already
            // handles (the `WM_CLOSE` arm above) — `LiveWindowApp::handle`
            // always resolves it to `Reaction::Exit`, so this ends the
            // message loop `runner`'s thread is pumping.
            unsafe {
                SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
            }
            let _ = runner.join();
        }

        /// A real click at the File menu's position inside a combined
        /// title/menu band must reach the app as an ordinary `MouseDown`,
        /// not get swallowed as a title-bar drag. The test above proves
        /// `nc_hit_test`'s classification is right when the band and its
        /// widgets are hand-registered (`LiveWindowApp::render` calls
        /// `Backend::register_zone`/`draw_menu_bar` directly) — this one
        /// proves the same real `WM_NCHITTEST` round trip when the band
        /// comes from the actual consumer-shaped composition instead:
        /// `AppShell`'s title-bar band (`ShellConfig::with_title_bar`)
        /// hosting a `MenuSystem` menu bar, run through the real
        /// `win::shell_runner::run_with_shell` — the same path
        /// `examples/win_shell_menu.rs` exercises. A gap in how
        /// `AppShell::render`/`MenuSystem::render` register their own
        /// band-content zones (as opposed to a gap in `nc_hit_test`
        /// itself, which the test above already covers) would show up
        /// here even if that one still passed.
        struct ShellProbeTargets {
            file_item: Option<(f32, f32)>,
            scale: f32,
        }

        struct LiveShellMenuApp {
            menu_system: crate::MenuSystem,
            targets: Arc<Mutex<ShellProbeTargets>>,
        }

        impl crate::ShellApp for LiveShellMenuApp {
            fn render_content(&self, backend: &mut dyn Backend, layout: &crate::AppShellLayout) {
                let Some(bar_rect) = layout.title_bar_bounds else {
                    return;
                };
                self.menu_system.render(backend, bar_rect);

                let bar = self.menu_system.menu_bar();
                let menu_layout = backend.menu_bar_layout(bar_rect, &bar);
                let file_item = menu_layout
                    .visible_items
                    .iter()
                    .find(|v| v.clickable)
                    .map(|v| {
                        (
                            v.bounds.x + v.bounds.width / 2.0,
                            v.bounds.y + v.bounds.height / 2.0,
                        )
                    });

                let mut targets = self.targets.lock().unwrap();
                targets.file_item = file_item;
                targets.scale = backend.viewport().scale;
            }

            fn handle(
                &mut self,
                event: UiEvent,
                backend: &mut dyn Backend,
                ctx: &crate::ShellContext,
            ) -> Reaction {
                if let UiEvent::WindowClose = event {
                    return Reaction::Exit;
                }
                let Some(bar_rect) = ctx.title_bar_bounds() else {
                    return Reaction::Continue;
                };
                match self.menu_system.handle(&event, backend, bar_rect) {
                    crate::MenuEvent::Ignored => Reaction::Continue,
                    _ => Reaction::Redraw,
                }
            }
        }

        /// Self-guarding, same posture as
        /// `real_wm_nchittest_excludes_band_widgets_and_caps_the_empty_strip`
        /// above.
        #[test]
        #[allow(clippy::print_stderr)]
        fn real_wm_nchittest_reaches_the_file_menu_through_a_composed_shell() {
            let targets = Arc::new(Mutex::new(ShellProbeTargets {
                file_item: None,
                scale: 1.0,
            }));
            let app = LiveShellMenuApp {
                menu_system: crate::MenuSystem::new(vec![crate::MenuDef {
                    id: crate::types::WidgetId::new("probe:file"),
                    label: "&File".into(),
                    disabled: false,
                    items: vec![crate::ContextMenuItem {
                        id: Some(crate::types::WidgetId::new("probe:new")),
                        label: crate::StyledText::plain("New File"),
                        ..Default::default()
                    }],
                }]),
                targets: targets.clone(),
            };
            let title = format!(
                "quadraui-shell-nchittest-probe-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            );
            let config = crate::ShellConfig::new(
                title.clone(),
                vec![crate::PanelDefinition {
                    id: crate::types::WidgetId::new("probe:panel"),
                    icon: "E".into(),
                    tooltip: "Explorer".into(),
                    title: "EXPLORER".into(),
                }],
            )
            .with_title_bar(1.0);

            let runner =
                std::thread::spawn(move || crate::win::shell_runner::run_with_shell(app, config));

            let deadline = Instant::now() + Duration::from_secs(10);
            let class_name = window_class_name(&title);
            let hwnd = loop {
                // SAFETY: `class_name` is a live `Vec<u16>` for the
                // duration of this call.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                if let Ok(hwnd) = found {
                    break Some(hwnd);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(hwnd) = hwnd else {
                eprintln!(
                    "quadraui: skipping \
                     real_wm_nchittest_reaches_the_file_menu_through_a_composed_shell — \
                     the test window never became findable within 10s (no interactive \
                     window station on this host?)"
                );
                return;
            };

            let ready = loop {
                let snapshot_file = targets.lock().unwrap().file_item;
                if let Some(file_item) = snapshot_file {
                    break Some(file_item);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(file_item) = ready else {
                eprintln!(
                    "quadraui: skipping \
                     real_wm_nchittest_reaches_the_file_menu_through_a_composed_shell — \
                     the window never painted a full frame within 10s"
                );
                // SAFETY: `hwnd` is still the live test window; `WM_CLOSE`
                // is this window's normal user-close path.
                unsafe {
                    SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
                }
                let _ = runner.join();
                return;
            };
            let scale = targets.lock().unwrap().scale;

            let lparam = dip_to_screen_lparam(hwnd, file_item, scale);
            let result = {
                // SAFETY: `hwnd` is still the live test window;
                // `WM_NCHITTEST` is a pure query with no side effects to
                // uphold beyond a live window.
                unsafe { SendMessageW(hwnd, WM_NCHITTEST, Some(WPARAM(0)), Some(lparam)) }
            };
            let is_caption = result.0 as u32 == HTCAPTION;

            // SAFETY: `hwnd` is still the live test window; `WM_CLOSE` is
            // the normal user-close path `LiveShellMenuApp::handle` always
            // resolves to `Reaction::Exit`.
            unsafe {
                SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
            }
            let _ = runner.join();

            assert!(
                !is_caption,
                "File menu item (through AppShell + MenuSystem): expected \
                 not HTCAPTION (HTCLIENT) but WM_NCHITTEST returned {:#x} — \
                 a real click here would be swallowed as a title-bar drag \
                 instead of opening the dropdown (quadraui#1307)",
                result.0
            );
        }
    }

    /// Proves the `IDLE_POLL_CEILING` safety net on a real `WM_TIMER`
    /// round-trip through a real message loop: an app whose `tick` only
    /// marks state dirty with no `Reaction::RedrawAfter`/
    /// `request_frame_in` of its own still gets picked up. `WinDriver::tick`
    /// alone can't cover this — it calls `AppLogic::tick` directly and
    /// proves nothing about whether a live `SetTimer` would ever have
    /// fired it; see that method's doc.
    #[cfg(test)]
    mod idle_poll_fallback_tests {
        use super::*;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;
        use std::time::{Duration, Instant};

        /// Counts `tick` calls and deliberately never returns
        /// `Reaction::RedrawAfter` and never calls `request_frame_in` —
        /// the "deferred work with no explicit re-arm" shape that is
        /// otherwise stranded forever with no idle-poll fallback.
        struct IdlePollApp {
            tick_count: Arc<AtomicUsize>,
        }

        impl AppLogic for IdlePollApp {
            type AreaId = ();

            fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

            fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                match event {
                    UiEvent::WindowClose => Reaction::Exit,
                    _ => Reaction::Continue,
                }
            }

            fn tick(&mut self, _backend: &mut dyn Backend) -> Reaction {
                self.tick_count.fetch_add(1, Ordering::SeqCst);
                Reaction::Continue
            }
        }

        /// Self-guarding (stderr diagnostic + early return, same posture
        /// as `real_wm_nchittest_excludes_band_widgets_and_caps_the_empty_strip`
        /// above) if the window never becomes findable within the
        /// timeout — this test's contract is "a live interactive window
        /// station", not every CI sandbox.
        #[test]
        #[allow(clippy::print_stderr)]
        fn idle_poll_ceiling_fires_tick_with_no_explicit_rearm() {
            let tick_count = Arc::new(AtomicUsize::new(0));
            let app = IdlePollApp {
                tick_count: tick_count.clone(),
            };
            let title = format!(
                "quadraui-idle-poll-probe-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            );
            let config = crate::win::run::RunConfig::new(title.clone());

            let runner = std::thread::spawn(move || run(app, config));

            let deadline = Instant::now() + Duration::from_secs(10);
            let class_name = window_class_name(&title);
            let hwnd = loop {
                // SAFETY: `class_name` is a live `Vec<u16>` for the
                // duration of this call.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                if let Ok(hwnd) = found {
                    break Some(hwnd);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(hwnd) = hwnd else {
                eprintln!(
                    "quadraui: skipping \
                     idle_poll_ceiling_fires_tick_with_no_explicit_rearm — \
                     the test window never became findable within 10s (no \
                     interactive window station on this host?)"
                );
                return;
            };

            // Bounded well above `IDLE_POLL_CEILING` (250ms) so this isn't
            // a hair-trigger race against scheduler jitter, but still far
            // short of the 10s self-guard above — a regression back to
            // "no fallback at all" would never satisfy this within the
            // deadline, not merely arrive a little late.
            let tick_deadline = Instant::now() + Duration::from_secs(5);
            let fired = loop {
                if tick_count.load(Ordering::SeqCst) > 0 {
                    break true;
                }
                if Instant::now() >= tick_deadline {
                    break false;
                }
                std::thread::sleep(Duration::from_millis(20));
            };

            // SAFETY: `hwnd` is still the live test window; `WM_CLOSE` is
            // the normal user-close path this window's `wndproc` already
            // handles (the `WM_CLOSE` arm above) — `IdlePollApp::handle`
            // always resolves it to `Reaction::Exit`, so this ends the
            // message loop `runner`'s thread is pumping.
            unsafe {
                SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
            }
            let _ = runner.join();

            assert!(
                fired,
                "AppLogic::tick was never called within 5s of the window \
                 appearing, with no explicit RedrawAfter/request_frame_in — \
                 the IDLE_POLL_TIMER_ID safety net (quadraui#1265) isn't \
                 firing"
            );
        }
    }

    /// Proves `dispatch_with`'s `Reaction::Exit` handling is reached from
    /// a real mouse-up and a real key-down, not just `WM_CLOSE`/the
    /// exit-timer arms this file already checks: an app returning `Exit`
    /// from either path (e.g. a drawn-menu "Quit" click, or `:q`) must
    /// tear the window down, not leave it alive with a "frozen window"
    /// symptom. `WinDriver` can't cover this: it calls
    /// `dispatch_event`/`route_mouse_*` directly and latches `exited`
    /// itself, never going through `wndproc`'s own `dispatch`/
    /// `dispatch_with` call sites — so this needs a real message loop,
    /// same posture as `live_window_nchittest_tests` and
    /// `idle_poll_fallback_tests` above.
    #[cfg(test)]
    mod mouse_and_key_exit_tests {
        use super::*;
        use std::time::{Duration, Instant};

        /// Exits on `MouseUp`/`KeyPressed`, continues on everything else —
        /// the two event families whose `Reaction::Exit` `wndproc` must
        /// not silently drop.
        struct ExitOnInputApp;

        impl AppLogic for ExitOnInputApp {
            type AreaId = ();

            fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

            fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                match event {
                    // `WindowClose` is included only so a failing test's
                    // own `WM_CLOSE` cleanup (see
                    // `assert_exit_reaction_destroys_window`'s `else`
                    // branch) can still tear the window down — it isn't
                    // part of the `MouseUp`/`KeyPressed` behaviour under
                    // test here.
                    UiEvent::MouseUp { .. } | UiEvent::KeyPressed { .. } | UiEvent::WindowClose => {
                        Reaction::Exit
                    }
                    _ => Reaction::Continue,
                }
            }
        }

        /// Spins up a real window running `ExitOnInputApp`, waits for it
        /// to become findable (self-guarding — stderr diagnostic + early
        /// return, same posture as this module's siblings above — if
        /// there's no interactive window station on this host), calls
        /// `trigger` with the live `HWND`, then asserts the window is
        /// actually torn down within a bound well above any plausible
        /// dispatch latency: a regression back to "Exit is dropped"
        /// leaves the window sitting there indefinitely, not merely
        /// destroys it a little late.
        #[allow(clippy::print_stderr)]
        fn assert_exit_reaction_destroys_window(test_name: &str, trigger: impl FnOnce(HWND)) {
            let title = format!(
                "quadraui-exit-reaction-probe-{test_name}-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            );
            let config = crate::win::run::RunConfig::new(title.clone());

            let runner = std::thread::spawn(move || run(ExitOnInputApp, config));

            let deadline = Instant::now() + Duration::from_secs(10);
            let class_name = window_class_name(&title);
            let hwnd = loop {
                // SAFETY: `class_name` is a live `Vec<u16>` for the
                // duration of this call.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                if let Ok(hwnd) = found {
                    break Some(hwnd);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(hwnd) = hwnd else {
                eprintln!(
                    "quadraui: skipping {test_name} — the test window never \
                     became findable within 10s (no interactive window \
                     station on this host?)"
                );
                return;
            };

            trigger(hwnd);

            let exit_deadline = Instant::now() + Duration::from_secs(5);
            let destroyed = loop {
                // SAFETY: `class_name` is still the live `Vec<u16>` from
                // above.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                let still_there = found.is_ok();
                if !still_there {
                    break true;
                }
                if Instant::now() >= exit_deadline {
                    break false;
                }
                std::thread::sleep(Duration::from_millis(20));
            };

            if destroyed {
                // `WM_DESTROY`'s `PostQuitMessage` already ended
                // `run_inner`'s loop by this point, so this returns
                // promptly rather than hanging the test process.
                let _ = runner.join();
            } else {
                // SAFETY: `hwnd` is still the live (never-destroyed, per
                // `destroyed == false` above) test window; `WM_CLOSE` is
                // its normal user-close path (`ExitOnInputApp::handle`
                // exits on it too, specifically so this cleanup still
                // works when the real `MouseUp`/`KeyPressed` assertion
                // below is about to fail) — used here only to tear the
                // window down after an already-failing test rather than
                // leak a window and a blocked thread past this test's own
                // scope.
                unsafe {
                    SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
                }
                let _ = runner.join();
            }

            assert!(
                destroyed,
                "{test_name}: window was never destroyed within 5s of an \
                 app `handle` returning Reaction::Exit — the reaction was \
                 dropped (quadraui#1278)"
            );
        }

        #[test]
        fn mouse_up_exit_reaction_destroys_window() {
            assert_exit_reaction_destroys_window(
                "mouse_up_exit_reaction_destroys_window",
                |hwnd| {
                    // A plain left click: down then up at an arbitrary client
                    // point. `ExitOnInputApp::handle` exits on the `MouseUp`
                    // this produces via `route_mouse_up` -> `dispatch_event`
                    // (no scrollbar/text-selection drag state to intercept
                    // it).
                    let lparam = LPARAM((20i32 << 16 | 20i32) as isize);
                    // SAFETY: `hwnd` is the live test window from the caller's
                    // `FindWindowW` poll; `SendMessageW` blocks until
                    // `wndproc` returns, so there's no re-entrancy/lifetime
                    // hazard beyond the ones `wndproc` itself already
                    // documents.
                    unsafe {
                        SendMessageW(hwnd, WM_LBUTTONDOWN, Some(WPARAM(0)), Some(lparam));
                        SendMessageW(hwnd, WM_LBUTTONUP, Some(WPARAM(0)), Some(lparam));
                    }
                },
            );
        }

        #[test]
        fn key_down_exit_reaction_destroys_window() {
            assert_exit_reaction_destroys_window(
                "key_down_exit_reaction_destroys_window",
                |hwnd| {
                    // `VK_ESCAPE` (0x1B) is one of `wm_keydown_to_uievent`'s
                    // named-key cases, so it reaches `ExitOnInputApp::handle`
                    // as `KeyPressed` directly off `WM_KEYDOWN` — no
                    // `WM_CHAR`/keyboard-layout resolution needed, unlike a
                    // printable key.
                    const VK_ESCAPE: usize = 0x1B;
                    // SAFETY: same as the mouse case above.
                    unsafe {
                        SendMessageW(hwnd, WM_KEYDOWN, Some(WPARAM(VK_ESCAPE)), Some(LPARAM(0)));
                    }
                },
            );
        }
    }

    /// A real window must never report itself visible (`IsWindowVisible`)
    /// before its first real frame has actually painted. This proves the
    /// *ordering* directly by racing a tight polling thread against
    /// `IsWindowVisible` — rather than reading back composited pixel
    /// colour, which `ID2D1HwndRenderTarget`'s own presentation path
    /// makes unreliable to sample through plain GDI `GetPixel`.
    #[cfg(test)]
    mod first_paint_before_show_tests {
        use super::*;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;
        use std::time::{Duration, Instant};
        use windows::Win32::UI::WindowsAndMessaging::IsWindowVisible;

        struct PaintFlagApp {
            painted: Arc<AtomicBool>,
        }

        impl AppLogic for PaintFlagApp {
            type AreaId = ();

            fn render(&self, _backend: &mut dyn Backend, _area: ()) {
                self.painted.store(true, Ordering::SeqCst);
            }

            fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                match event {
                    UiEvent::WindowClose => Reaction::Exit,
                    _ => Reaction::Continue,
                }
            }
        }

        /// Self-guarding (stderr diagnostic + early return, same posture
        /// as `live_window_nchittest_tests` above) if the window never
        /// becomes visible within the timeout — this test's contract is
        /// "a live interactive window station", not every CI sandbox.
        #[test]
        #[allow(clippy::print_stderr)]
        fn window_is_never_visible_before_its_first_frame_has_painted() {
            let painted = Arc::new(AtomicBool::new(false));
            let app = PaintFlagApp {
                painted: painted.clone(),
            };
            let title = format!(
                "quadraui-first-paint-probe-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            );
            let config = crate::win::run::RunConfig::new(title.clone());

            let runner = std::thread::spawn(move || run(app, config));

            // Tight, unslept poll — this must catch `IsWindowVisible`
            // flipping true as close to the instant it happens as
            // possible; sleeping between checks (the other live-window
            // tests' usual posture) would give `render` ample time to
            // run regardless of which order the real code uses, erasing
            // exactly the signal this test exists to catch.
            let deadline = Instant::now() + Duration::from_secs(10);
            let class_name = window_class_name(&title);
            let mut observed: Option<(HWND, bool)> = None;
            loop {
                // SAFETY: `class_name` is a live `Vec<u16>` for the
                // duration of this call.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                if let Ok(hwnd) = found {
                    // SAFETY: `hwnd` is the handle `FindWindowW` just
                    // returned as live.
                    if unsafe { IsWindowVisible(hwnd) }.as_bool() {
                        observed = Some((hwnd, painted.load(Ordering::SeqCst)));
                        break;
                    }
                }
                if Instant::now() >= deadline {
                    break;
                }
            }

            let Some((hwnd, painted_before_visible)) = observed else {
                eprintln!(
                    "quadraui: skipping \
                     window_is_never_visible_before_its_first_frame_has_painted — \
                     the test window never became visible within 10s (no \
                     interactive window station on this host?)"
                );
                return;
            };

            assert!(
                painted_before_visible,
                "the window reported `IsWindowVisible` before \
                 `AppLogic::render` ever ran — the swap chain's backbuffer \
                 had nothing real painted into it the instant DWM could \
                 first composite it, reopening issue #1263's white-flash \
                 gap"
            );

            // SAFETY: `hwnd` is still the live test window; `WM_CLOSE` is
            // its normal user-close path.
            unsafe {
                SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
            }
            let _ = runner.join();
        }
    }

    /// [`WinRunner::step`] / [`WinRunner::pump`] drive an app from a
    /// thread that never calls [`run`] / [`run_with`] at all — the whole
    /// point of exposing the runner separately. This constructs a
    /// [`WinRunner`] directly, calls `step()` once (must return
    /// immediately with nothing queued), then loops `pump()` until
    /// `WM_CLOSE` surfaces as `StepOutcome::Exited`.
    #[cfg(test)]
    mod winrunner_step_pump_tests {
        use super::*;
        use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
        use std::sync::Arc;
        use std::time::{Duration, Instant};

        struct StepPumpApp {
            painted: Arc<AtomicBool>,
            closed: Arc<AtomicBool>,
        }

        impl AppLogic for StepPumpApp {
            type AreaId = ();

            fn render(&self, _backend: &mut dyn Backend, _area: ()) {
                self.painted.store(true, Ordering::SeqCst);
            }

            fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                if matches!(event, UiEvent::WindowClose) {
                    self.closed.store(true, Ordering::SeqCst);
                    return Reaction::Exit;
                }
                Reaction::Continue
            }
        }

        /// Self-guarding (stderr diagnostic + early return) if the window
        /// never becomes findable — same posture as the other live-window
        /// tests in this file.
        #[test]
        #[allow(clippy::print_stderr)]
        fn step_then_pump_drive_app_without_run() {
            let painted = Arc::new(AtomicBool::new(false));
            let closed = Arc::new(AtomicBool::new(false));
            let first_step_elapsed_ms = Arc::new(AtomicU64::new(u64::MAX));

            let title = format!(
                "quadraui-step-pump-probe-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            );

            let painted_for_thread = painted.clone();
            let closed_for_thread = closed.clone();
            let first_step_elapsed_for_thread = first_step_elapsed_ms.clone();
            let title_for_thread = title.clone();

            let runner_thread = std::thread::spawn(move || {
                let config = RunConfig::new(title_for_thread);
                let app = StepPumpApp {
                    painted: painted_for_thread,
                    closed: closed_for_thread,
                };
                // SAFETY: constructed and stepped entirely within this
                // one thread, matching `WinRunner::new_with`'s `# Safety`
                // contract.
                let mut runner = unsafe { WinRunner::new_with(app, &config) }
                    .expect("WinRunner::new_with failed");

                let step_start = Instant::now();
                let outcome = runner.step().expect("step() failed");
                first_step_elapsed_for_thread
                    .store(step_start.elapsed().as_millis() as u64, Ordering::SeqCst);
                debug_assert!(matches!(
                    outcome,
                    StepOutcome::Continue | StepOutcome::Exited
                ));

                loop {
                    match runner
                        .pump(Duration::from_millis(50))
                        .expect("pump() failed")
                    {
                        StepOutcome::Continue => {}
                        StepOutcome::Exited => break,
                    }
                }
            });

            let deadline = Instant::now() + Duration::from_secs(10);
            let class_name = window_class_name(&title);
            let hwnd = loop {
                // SAFETY: `class_name` is a live `Vec<u16>` for this call.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                if let Ok(hwnd) = found {
                    break Some(hwnd);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(hwnd) = hwnd else {
                eprintln!(
                    "quadraui: skipping step_then_pump_drive_app_without_run — \
                     the test window never became findable within 10s (no \
                     interactive window station on this host?)"
                );
                return;
            };

            let paint_deadline = Instant::now() + Duration::from_secs(5);
            let saw_paint = loop {
                if painted.load(Ordering::SeqCst) {
                    break true;
                }
                if Instant::now() >= paint_deadline {
                    break false;
                }
                std::thread::sleep(Duration::from_millis(20));
            };

            // SAFETY: `hwnd` is still the live test window; `WM_CLOSE` is
            // its normal user-close path.
            unsafe {
                SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
            }
            let _ = runner_thread.join();

            assert!(
                saw_paint,
                "AppLogic::render never ran within 5s of a WinRunner stepped \
                 directly (not via run()) becoming findable"
            );
            assert!(
                closed.load(Ordering::SeqCst),
                "WM_CLOSE never reached AppLogic::handle as a dispatched \
                 UiEvent::WindowClose through a directly-stepped WinRunner"
            );
            let first_step_elapsed = first_step_elapsed_ms.load(Ordering::SeqCst);
            assert!(
                first_step_elapsed < 1000,
                "WinRunner::step() took {first_step_elapsed}ms on its very \
                 first call with nothing queued — it must never block"
            );
        }
    }

    /// [`Backend::waker`] must be callable from any thread and must wake
    /// a [`WinRunner::pump`] that is currently blocked waiting on
    /// `MsgWaitForMultipleObjects`, without the caller having to wait out
    /// `pump`'s own timeout — that round trip is what lets a background
    /// thread nudge processing of a [`UiEvent::User`] instead of the app
    /// busy-polling for it.
    #[cfg(test)]
    mod winrunner_waker_tests {
        use super::*;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::{Arc, Mutex};
        use std::time::{Duration, Instant};

        struct Ping(u32);

        struct WakerApp {
            waker_slot: Arc<Mutex<Option<Arc<dyn Fn(crate::UserPayload) + Send + Sync>>>>,
            got_ping: Arc<AtomicBool>,
        }

        impl AppLogic for WakerApp {
            type AreaId = ();

            fn setup(&mut self, backend: &mut dyn Backend) {
                *self.waker_slot.lock().unwrap() = Some(backend.waker());
            }

            fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

            fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                match event {
                    UiEvent::User(payload) => {
                        if let Some(ping) = payload.downcast_ref::<Ping>() {
                            if ping.0 == 42 {
                                self.got_ping.store(true, Ordering::SeqCst);
                            }
                        }
                        Reaction::Continue
                    }
                    UiEvent::WindowClose => Reaction::Exit,
                    _ => Reaction::Continue,
                }
            }
        }

        /// Uses a long (5s) `pump` timeout on the runner thread — if the
        /// waker round trip is broken and the event only ever arrives via
        /// the independent idle-poll fallback or sheer luck, this test's
        /// own much shorter (3s) assertion deadline below fails reliably
        /// instead of passing by accident.
        #[test]
        #[allow(clippy::print_stderr)]
        fn waker_wakes_a_blocked_pump_without_waiting_out_the_timeout() {
            let waker_slot: Arc<Mutex<Option<Arc<dyn Fn(crate::UserPayload) + Send + Sync>>>> =
                Arc::new(Mutex::new(None));
            let got_ping = Arc::new(AtomicBool::new(false));

            let title = format!(
                "quadraui-waker-probe-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            );

            let waker_slot_for_thread = waker_slot.clone();
            let got_ping_for_thread = got_ping.clone();
            let title_for_thread = title.clone();

            let runner_thread = std::thread::spawn(move || {
                let config = RunConfig::new(title_for_thread);
                let app = WakerApp {
                    waker_slot: waker_slot_for_thread,
                    got_ping: got_ping_for_thread,
                };
                // SAFETY: constructed and pumped entirely within this one
                // thread.
                let mut runner = unsafe { WinRunner::new_with(app, &config) }
                    .expect("WinRunner::new_with failed");

                loop {
                    match runner.pump(Duration::from_secs(5)).expect("pump() failed") {
                        StepOutcome::Continue => {}
                        StepOutcome::Exited => break,
                    }
                }
            });

            let deadline = Instant::now() + Duration::from_secs(10);
            let class_name = window_class_name(&title);
            let hwnd = loop {
                // SAFETY: `class_name` is a live `Vec<u16>` for this call.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                if let Ok(hwnd) = found {
                    break Some(hwnd);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(hwnd) = hwnd else {
                eprintln!(
                    "quadraui: skipping \
                     waker_wakes_a_blocked_pump_without_waiting_out_the_timeout — \
                     the test window never became findable within 10s (no \
                     interactive window station on this host?)"
                );
                return;
            };

            let waker_deadline = Instant::now() + Duration::from_secs(5);
            let waker = loop {
                if let Some(w) = waker_slot.lock().unwrap().clone() {
                    break Some(w);
                }
                if Instant::now() >= waker_deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(10));
            };
            let Some(waker) = waker else {
                // SAFETY: `hwnd` is still the live test window.
                unsafe {
                    SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
                }
                let _ = runner_thread.join();
                panic!(
                    "AppLogic::setup never captured backend.waker() within 5s \
                     of the window becoming findable"
                );
            };

            (waker)(crate::UserPayload::new(Ping(42)));

            let ping_deadline = Instant::now() + Duration::from_secs(3);
            let saw_ping = loop {
                if got_ping.load(Ordering::SeqCst) {
                    break true;
                }
                if Instant::now() >= ping_deadline {
                    break false;
                }
                std::thread::sleep(Duration::from_millis(10));
            };

            // SAFETY: `hwnd` is still the live test window; `WM_CLOSE` is
            // its normal user-close path.
            unsafe {
                SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
            }
            let _ = runner_thread.join();

            assert!(
                saw_ping,
                "UiEvent::User(Ping(42)) from Backend::waker() never reached \
                 AppLogic::handle within 3s of the waker being called from \
                 another thread — the waker's wake round trip isn't waking a \
                 blocked WinRunner::pump()"
            );
        }
    }

    /// `Reaction::RedrawAfter(delay)` returned from `AppLogic::handle`
    /// must schedule exactly one wake at `delay`, not zero (dropped) and
    /// not more than one (double-fired or confused with the independent
    /// `IDLE_POLL_TIMER_ID` safety-net timer). The arm is triggered by a
    /// real `WM_MOUSEMOVE` dispatch rather than relying on the idle-poll
    /// timer's own uncontrolled phase, so the test has a precisely known
    /// instant to measure the wake against.
    #[cfg(test)]
    mod winrunner_redraw_after_tests {
        use super::*;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::{Arc, Mutex};
        use std::time::{Duration, Instant};

        struct RedrawAfterApp {
            delay: Duration,
            armed: Arc<AtomicBool>,
            arm_instant: Arc<Mutex<Option<Instant>>>,
            tick_instants: Arc<Mutex<Vec<Instant>>>,
        }

        impl AppLogic for RedrawAfterApp {
            type AreaId = ();

            fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

            fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                match event {
                    UiEvent::WindowClose => Reaction::Exit,
                    UiEvent::MouseMoved { .. } => {
                        if self.armed.swap(true, Ordering::SeqCst) {
                            Reaction::Continue
                        } else {
                            *self.arm_instant.lock().unwrap() = Some(Instant::now());
                            Reaction::RedrawAfter(self.delay)
                        }
                    }
                    _ => Reaction::Continue,
                }
            }

            fn tick(&mut self, _backend: &mut dyn Backend) -> Reaction {
                self.tick_instants.lock().unwrap().push(Instant::now());
                Reaction::Continue
            }
        }

        /// The 230ms window below is comfortably under the independent
        /// `IDLE_POLL_TIMER_ID`'s 250ms period, so a tick from that
        /// unrelated safety-net timer firing at its own uncontrolled
        /// phase is unlikely to land inside this specific post-arm
        /// window and be miscounted as a second `RedrawAfter`-caused
        /// tick.
        #[test]
        #[allow(clippy::print_stderr)]
        fn redraw_after_wakes_exactly_once_near_its_deadline() {
            let delay = Duration::from_millis(60);
            let armed = Arc::new(AtomicBool::new(false));
            let arm_instant: Arc<Mutex<Option<Instant>>> = Arc::new(Mutex::new(None));
            let tick_instants: Arc<Mutex<Vec<Instant>>> = Arc::new(Mutex::new(Vec::new()));

            let title = format!(
                "quadraui-redraw-after-probe-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            );

            let armed_for_thread = armed.clone();
            let arm_instant_for_thread = arm_instant.clone();
            let tick_instants_for_thread = tick_instants.clone();
            let title_for_thread = title.clone();

            let runner_thread = std::thread::spawn(move || {
                let config = RunConfig::new(title_for_thread);
                let app = RedrawAfterApp {
                    delay,
                    armed: armed_for_thread,
                    arm_instant: arm_instant_for_thread,
                    tick_instants: tick_instants_for_thread,
                };
                // SAFETY: constructed and pumped entirely within this one
                // thread.
                let mut runner = unsafe { WinRunner::new_with(app, &config) }
                    .expect("WinRunner::new_with failed");
                loop {
                    match runner
                        .pump(Duration::from_millis(50))
                        .expect("pump() failed")
                    {
                        StepOutcome::Continue => {}
                        StepOutcome::Exited => break,
                    }
                }
            });

            let deadline = Instant::now() + Duration::from_secs(10);
            let class_name = window_class_name(&title);
            let hwnd = loop {
                // SAFETY: `class_name` is a live `Vec<u16>` for this call.
                let found = unsafe { FindWindowW(PCWSTR(class_name.as_ptr()), PCWSTR::null()) };
                if let Ok(hwnd) = found {
                    break Some(hwnd);
                }
                if Instant::now() >= deadline {
                    break None;
                }
                std::thread::sleep(Duration::from_millis(20));
            };
            let Some(hwnd) = hwnd else {
                eprintln!(
                    "quadraui: skipping \
                     redraw_after_wakes_exactly_once_near_its_deadline — the \
                     test window never became findable within 10s (no \
                     interactive window station on this host?)"
                );
                return;
            };

            // `WM_MOUSEMOVE`'s `lParam` packs the client-area point as
            // (y << 16 | x), the same idiom `mouse_and_key_exit_tests`
            // uses above.
            let lparam = LPARAM((30i32 << 16 | 30i32) as isize);
            // SAFETY: `hwnd` is still the live test window.
            unsafe {
                SendMessageW(hwnd, WM_MOUSEMOVE, Some(WPARAM(0)), Some(lparam));
            }

            std::thread::sleep(Duration::from_millis(180));

            // SAFETY: `hwnd` is still the live test window; `WM_CLOSE` is
            // its normal user-close path.
            unsafe {
                SendMessageW(hwnd, WM_CLOSE, Some(WPARAM(0)), Some(LPARAM(0)));
            }
            let _ = runner_thread.join();

            let armed_at = arm_instant
                .lock()
                .unwrap()
                .expect("RedrawAfterApp::handle never saw the WM_MOUSEMOVE as MouseMoved");
            let ticks = tick_instants.lock().unwrap();
            let near_deadline: Vec<Duration> = ticks
                .iter()
                .filter(|t| **t >= armed_at)
                .map(|t| t.duration_since(armed_at))
                .filter(|elapsed| *elapsed < Duration::from_millis(230))
                .collect();

            assert_eq!(
                near_deadline.len(),
                1,
                "expected exactly one AppLogic::tick within 230ms of arming \
                 Reaction::RedrawAfter({delay:?}), saw {near_deadline:?} — \
                 RedrawAfter is either dropping the wake entirely or firing \
                 it more than once"
            );
            assert!(
                near_deadline[0] >= delay.saturating_sub(Duration::from_millis(20)),
                "RedrawAfter's wake fired after only {:?}, well before its \
                 {delay:?} deadline",
                near_deadline[0]
            );
        }
    }
}

// `WinRunner` exists only when `mod win32` compiles — it needs a real
// `HWND`/`WindowState<A>`, unlike `RunConfig`/`run`/`run_with`, which have
// off-Windows fallback stubs below — so, unlike `StepOutcome`'s
// unconditional re-export above, this one is necessarily
// `target_os = "windows"`-gated. `pub` (not `pub(super)`) because this
// re-export chain is what lets anything outside the crate reach
// `crate::win::WinRunner` directly, mirroring
// `crate::tui::run::TuiRunner` and `crate::gtk::run::GtkRunner`'s
// embedding-friendly, non-blocking shape
// (`new`/`new_with`/`step`/`pump`/`StepOutcome`) rather than only the
// blocking `run`/`run_with` convenience loop.
#[cfg(target_os = "windows")]
pub use win32::WinRunner;

#[cfg(target_os = "windows")]
pub fn run<A: AppLogic + 'static>(app: A) -> std::process::ExitCode {
    win32::run(app, RunConfig::default())
}

/// Like [`run`], but with a custom window title via [`RunConfig`] instead
/// of the hardcoded `"quadraui"` default. `run(app)` is equivalent to
/// `run_with(app, RunConfig::default())`.
#[cfg(target_os = "windows")]
pub fn run_with<A: AppLogic + 'static>(app: A, config: RunConfig) -> std::process::ExitCode {
    win32::run(app, config)
}

#[cfg(not(target_os = "windows"))]
pub fn run<A: AppLogic + 'static>(_app: A) -> std::process::ExitCode {
    todo!(
        "Win32 message loop: RegisterClassEx, CreateWindowEx, \
         Direct2D render target, translate WM_* → UiEvent, \
         dispatch to app.handle(), redraw via app.render()"
    )
}

/// Like [`run`], but with a custom window title via [`RunConfig`] — see
/// [`run`]'s non-Windows stub for why this is `todo!()` off Windows too.
#[cfg(not(target_os = "windows"))]
pub fn run_with<A: AppLogic + 'static>(_app: A, _config: RunConfig) -> std::process::ExitCode {
    todo!(
        "Win32 message loop: RegisterClassEx, CreateWindowEx, \
         Direct2D render target, translate WM_* → UiEvent, \
         dispatch to app.handle(), redraw via app.render() — with a \
         custom window title from RunConfig"
    )
}

// `RunConfig` itself is deliberately not `target_os = "windows"`-gated
// (see its doc comment), so these run on every host — including plain
// `cargo test -p quadraui --features win` on Linux, same as the rest of
// this crate's `win` compile/test gate. Mirrors `gtk::run`'s
// `run_config_tests` module.
#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;

    /// The 2026-09-26 framework audit flagged "6 non-test
    /// `todo!()` in `win/run.rs`" as unverified. Re-measured at this
    /// commit there are 2 (the count has moved since the audit's
    /// snapshot, not grown) — [`run`] and [`run_with`]'s
    /// `#[cfg(not(target_os = "windows"))]` stand-ins a few lines above
    /// this module, never reachable on an actual Windows build. This
    /// source scan (same technique `tests/conformance/caps.rs` uses for
    /// backend-honesty checks) pins both claims as a regression guard: a
    /// future `todo!()` added to this file outside a `#[cfg(test)]`
    /// module, with no `cfg(not(target_os = "windows"))` guard directly
    /// above its function, fails this test instead of silently shipping
    /// a reachable panic on Windows.
    #[test]
    fn every_non_test_todo_in_this_file_is_a_cfg_not_windows_stand_in() {
        let src = include_str!("run.rs");
        // Everything from the first `#[cfg(test)]` module onward is test
        // code (verified by eye above: `mod tests`, `paste_dispatch_tests`,
        // `text_selection_dispatch_tests`, `panic_guard_tests` are the
        // only things left in the file after this point). Scanning only
        // the prefix before it is what "non-test" means here.
        let test_mod_start = src
            .find("\n#[cfg(test)]\nmod tests {")
            .expect("this file must still have its `mod tests` block");
        let non_test_src = &src[..test_mod_start];

        let lines: Vec<&str> = non_test_src.lines().collect();
        let mut todo_count = 0;
        for (idx, line) in lines.iter().enumerate() {
            if !line.trim_start().starts_with("todo!(") {
                continue;
            }
            todo_count += 1;
            // Walk back from the `todo!(` call to the nearest preceding
            // `#[cfg(...)]` line (skipping the `fn` signature line and any
            // doc comments in between) and require it to be the
            // non-Windows guard.
            let guard = lines[..idx]
                .iter()
                .rev()
                .find(|l| l.trim_start().starts_with("#[cfg("))
                .unwrap_or_else(|| {
                    panic!(
                        "todo!() at non-test line {} has no preceding #[cfg(...)] guard at all",
                        idx + 1
                    )
                });
            assert_eq!(
                guard.trim(),
                r#"#[cfg(not(target_os = "windows"))]"#,
                "todo!() at non-test line {} must be guarded by \
                 #[cfg(not(target_os = \"windows\"))], found {:?} instead — \
                 a todo!() reachable on a real Windows build must become a \
                 real BackendError::Unsupported instead (#1131)",
                idx + 1,
                guard.trim()
            );
        }
        assert_eq!(
            todo_count, 2,
            "expected exactly 2 non-test todo!() call sites in win/run.rs \
             (run/run_with's non-Windows stand-ins) — if this changed, \
             re-verify #1131's claim and update this test's expectation"
        );
    }

    #[test]
    fn new_sets_the_title() {
        let config = RunConfig::new("kubeui");
        assert_eq!(config.title, "kubeui");
        assert!(
            !config.single_instance,
            "single-instance forwarding defaults off — see RunConfig::single_instance's doc"
        );
    }

    #[test]
    fn new_accepts_owned_and_borrowed_strings() {
        assert_eq!(RunConfig::new("borrowed").title, "borrowed");
        assert_eq!(RunConfig::new(String::from("owned")).title, "owned");
    }

    #[test]
    fn default_matches_runs_previously_hardcoded_title() {
        // `run(app)` used to always show a `"quadraui\0"`-derived
        // window title; `RunConfig::default()` must reproduce that exact
        // value so `run(app)` staying `run_with(app, RunConfig::default())`
        // doesn't change existing behaviour.
        assert_eq!(RunConfig::default().title, "quadraui");
        assert!(!RunConfig::default().single_instance);
    }

    /// `with_single_instance(true)` is how an app opts into
    /// `CreateMutexW` + `WM_COPYDATA` single-instance forwarding.
    #[test]
    fn with_single_instance_overrides_the_default() {
        let config = RunConfig::new("kubeui").with_single_instance(true);
        assert!(config.single_instance);
    }

    /// A fresh `RunConfig` sets no app icon — every existing consumer
    /// keeps the pre-single-instance behaviour (no `WM_SETICON` call).
    #[test]
    fn new_and_default_set_no_app_icon() {
        assert_eq!(RunConfig::new("kubeui").app_icon, None);
        assert_eq!(RunConfig::default().app_icon, None);
    }

    /// `with_app_icon` stores the source verbatim for
    /// `create_window`'s `WM_SETICON` call site to decode via
    /// `win::tray::decode_hicon`.
    #[test]
    fn with_app_icon_sets_the_source() {
        let config = RunConfig::new("kubeui").with_app_icon(ImageSource::Bytes(vec![0xde, 0xad]));
        assert_eq!(config.app_icon, Some(ImageSource::Bytes(vec![0xde, 0xad])));
    }

    /// Round-tripping an ordinary
    /// argv through the `WM_COPYDATA` wire encoding must reproduce it
    /// exactly.
    #[test]
    fn copydata_argv_round_trips() {
        let args = vec!["file.txt".to_string(), "--flag".to_string()];
        let payload = encode_copydata_argv(&args);
        assert_eq!(decode_copydata_argv(&payload), args);
    }

    /// The bug this replaced a `'\n'`-joined payload to fix: an argv
    /// entry containing a literal newline (an unusual but legal path
    /// character on both Windows and POSIX) must not be split into two
    /// bogus entries.
    #[test]
    fn copydata_argv_survives_embedded_newline() {
        let args = vec!["weird\npath.txt".to_string(), "second.txt".to_string()];
        let payload = encode_copydata_argv(&args);
        assert_eq!(decode_copydata_argv(&payload), args);
    }

    /// `forward_argv_to_existing_instance` appends a defensive trailing
    /// `'\0'` terminator on top of whatever `encode_copydata_argv`
    /// produced — decoding must still land on the original entries, not
    /// a bogus trailing empty one.
    #[test]
    fn decode_copydata_argv_ignores_trailing_terminator() {
        let payload = format!("{}\0", encode_copydata_argv(&["a.txt".to_string()]));
        assert_eq!(decode_copydata_argv(&payload), vec!["a.txt".to_string()]);
    }

    /// A bare relaunch (no argv beyond the executable path, which callers
    /// already skip before encoding) must decode to an empty list, not a
    /// list containing one bogus empty string.
    #[test]
    fn decode_copydata_argv_of_empty_payload_is_empty() {
        assert!(decode_copydata_argv("").is_empty());
        assert!(decode_copydata_argv("\0").is_empty());
    }

    /// The core scoping guarantee this
    /// fix exists for — two different `RunConfig::title`s must never
    /// collide on [`instance_identity`], since that's what the
    /// single-instance mutex name and the window class name are both
    /// keyed off. Before the fix, the window class name was one literal
    /// shared by every title, which is exactly the bug this asserts
    /// against.
    #[test]
    fn instance_identity_differs_across_titles() {
        assert_ne!(instance_identity("kubeui"), instance_identity("vimcode"));
    }

    /// [`instance_identity`] must be a pure function of `title` — the two
    /// separate process launches that need to agree on it (the one
    /// holding the mutex, and the one calling
    /// `forward_argv_to_existing_instance`) call it independently, with
    /// no shared state between them.
    #[test]
    fn instance_identity_is_deterministic() {
        assert_eq!(instance_identity("kubeui"), instance_identity("kubeui"));
    }

    /// [`window_class_name_string`] must embed [`instance_identity`]
    /// verbatim (as lowercase hex) so `win32::create_window`'s
    /// `RegisterClassExW` and `win32::forward_argv_to_existing_instance`'s
    /// `FindWindowW` — which both build their class name from this same
    /// function — always agree for the same `title`.
    #[test]
    fn window_class_name_string_embeds_instance_identity() {
        let title = "kubeui";
        let expected = format!("{CLASS_NAME_PREFIX}-{:016x}", instance_identity(title));
        assert_eq!(window_class_name_string(title), expected);
    }

    /// The other half of the blocking finding: two different titles must
    /// produce two different window class names, or `FindWindowW` in
    /// `forward_argv_to_existing_instance` can still find a different
    /// app's window.
    #[test]
    fn window_class_name_string_differs_across_titles() {
        assert_ne!(
            window_class_name_string("kubeui"),
            window_class_name_string("vimcode")
        );
    }

    /// Reproduces the exact hazard `guarded_call` guards against: a
    /// synchronous reentrant call while the outer call's
    /// `state.borrow_mut()` is still live. Without the
    /// `pump_depth.is_pumping()` check, the inner `state.borrow_mut()`
    /// would panic ("already mutably borrowed"); with it, the inner
    /// call is skipped and the outer one completes normally.
    #[test]
    fn reentrant_call_is_skipped_not_double_borrowed() {
        let state = RefCell::new(0i32);
        let depth = ModalPumpDepth::new();
        let outer = guarded_call(&state, &depth, |v| {
            *v += 1;
            // Simulate `wndproc` re-entering while this closure — the
            // stand-in for `app.handle`/`app.render` — is still running
            // with `state`'s `RefCell` mutably borrowed.
            let inner = guarded_call(&state, &depth, |v2| {
                *v2 += 100;
                *v2
            });
            assert_eq!(
                inner, None,
                "a reentrant guarded_call must be skipped, not run"
            );
            *v
        });
        assert_eq!(
            outer,
            Some(1),
            "the outer call must still complete normally"
        );
        assert_eq!(
            *state.borrow(),
            1,
            "the skipped reentrant call must not have mutated state"
        );
    }

    /// Models a reentrancy hazard in `wndproc`: a synchronous nested
    /// message arriving while a direct `borrow_mut()` of `ws.state` is
    /// live. Without a `ModalPumpGuard` around the outer borrow,
    /// `wndproc`'s `WM_SIZE` arm (which borrows `ws.state` directly)
    /// can attempt a second `borrow_mut()` on the same `RefCell` while
    /// the outer one is still live, panicking with "already mutably
    /// borrowed". `ModalPumpGuard` arms `pump_depth.is_pumping()`,
    /// which `wndproc`'s top-of-function check bounces to
    /// `DefWindowProcW` instead, avoiding the double borrow.
    #[test]
    fn reentrant_message_during_a_direct_borrow_is_deferred_not_double_borrowed() {
        let state = RefCell::new(0i32);
        let depth = ModalPumpDepth::new();

        // A closure standing in for `wndproc`'s `WM_SIZE` arm: it must
        // check `is_pumping()` (the same check `wndproc` runs before
        // ever matching on `msg`) and defer to `DefWindowProcW` (`None`
        // here) instead of touching `state` when a pump is already in
        // flight on this thread.
        let fake_wndproc_arm = |state: &RefCell<i32>, depth: &ModalPumpDepth| -> Option<i32> {
            if depth.is_pumping() {
                return None;
            }
            let mut v = state.borrow_mut();
            *v += 100;
            Some(*v)
        };

        // Mirrors `create_window`'s
        // `let _guard = ModalPumpGuard::new(&ws.pump_depth); ws.state.borrow_mut().backend.attach_surface(hwnd)` —
        // a direct borrow, not routed through `guarded_call`, wrapped in
        // its own `ModalPumpGuard`.
        let outer_result = {
            let _guard = ModalPumpGuard::new(&depth);
            let mut s = state.borrow_mut();
            *s += 1;

            // Mirrors `SetMenu` synchronously re-entering `wndproc` with
            // a nested `WM_SIZE` while the borrow above (`attach_surface`'s
            // `&mut self`) is still live.
            let nested = fake_wndproc_arm(&state, &depth);
            assert_eq!(
                nested, None,
                "a nested message arriving while the outer direct borrow is \
                 live must be deferred, never touch `state` a second time"
            );

            *s
        };
        assert_eq!(
            outer_result, 1,
            "the outer direct-borrow call must still complete normally"
        );
        assert!(
            !depth.is_pumping(),
            "depth must return to 0 once the guard around the outer call drops"
        );

        // Once the guard is gone, the same fake `wndproc` arm behaves
        // like an ordinary, non-reentrant message and runs normally.
        assert_eq!(fake_wndproc_arm(&state, &depth), Some(101));
    }

    /// The ceded-but-lossless-resync contract.
    /// Before the fix, `wndproc`'s top-of-function `is_pumping()` check
    /// (reproduced above by `fake_wndproc_arm`/the two tests just above
    /// this one) ceded a reentrant `WM_SIZE` to `DefWindowProcW` and
    /// forgot it ever happened — fine for input, which arrives again,
    /// but `WM_SIZE` is a one-shot state notification: dropping it left
    /// the render target at the old pixel size after a drawn maximize
    /// button's synchronous `ShowWindow(SW_MAXIMIZE)` sent `WM_SIZE`
    /// re-entrantly from inside `app.handle`.
    ///
    /// Models the fix's two halves at the same pure-logic seam the tests
    /// above use (no real `wndproc`/`WinBackend`, both Windows-only):
    /// `pending_resize_resync` stands in for `WindowState`'s new
    /// `Cell<bool>` field, and `fake_wndproc` stands in for `wndproc`'s
    /// new shape — set the flag instead of silently dropping a ceded
    /// `WM_SIZE`, then replay it (against the *current* size, like
    /// `resync_pending_resize`'s `GetClientRect` read) from the next
    /// non-reentrant call, before that call does its own work. Fails
    /// before the fix: the old shape never remembered the ceded message,
    /// so the final `surface_size`/`resized_dispatched` assertions below
    /// would see the stale 800×600 size and no resize reaching the app.
    #[test]
    fn ceded_resize_is_replayed_once_the_guard_releases() {
        let depth = ModalPumpDepth::new();
        let pending_resize_resync = Cell::new(false);
        // Stand-ins for `WinBackend`'s surface size and whether
        // `UiEvent::WindowResized` reached the app — plain `Cell`s, not a
        // real backend/app, because this test is proving the *replay
        // contract* `wndproc` must uphold, not re-exercising
        // `apply_resize`'s WinAPI calls (those only compile and run on
        // real Windows; see this issue's "Acceptance" section for that
        // coverage).
        let surface_size = Cell::new((800, 600));
        let resized_dispatched = Cell::new(false);

        // Mirrors `wndproc`'s shape end to end: cede-and-remember while a
        // guard is held (the top-of-function `is_pumping()` check,
        // extended to remember size notifications); otherwise replay any
        // pending resync first (`resync_pending_resize`), then handle `msg`
        // itself.
        let fake_wndproc = |is_size: bool, current_size: (i32, i32)| {
            if depth.is_pumping() {
                if is_size {
                    pending_resize_resync.set(true);
                }
                return; // DefWindowProcW stand-in: never touches `surface_size`.
            }
            if pending_resize_resync.replace(false) {
                surface_size.set(current_size);
                resized_dispatched.set(true);
            }
            if is_size {
                surface_size.set(current_size);
                resized_dispatched.set(true);
            }
        };

        // The maximize-button click handler (`app.handle` →
        // `toggle_window_maximize`) holds the guard and, from inside it,
        // synchronously triggers `WM_SIZE` — `ShowWindow(SW_MAXIMIZE)`'s
        // real reentrancy, per this issue's root-cause trace.
        {
            let _guard = ModalPumpGuard::new(&depth);
            fake_wndproc(true, (1920, 1080));
            assert_eq!(
                surface_size.get(),
                (800, 600),
                "a WM_SIZE arriving while the guard is held must not touch \
                 the surface yet — only the next non-reentrant call may"
            );
            assert!(
                !resized_dispatched.get(),
                "must not dispatch WindowResized while the guard is held"
            );
        }
        assert!(
            !depth.is_pumping(),
            "depth must return to 0 once the guard around the click handler drops"
        );

        // The next message — a mouse move, `WM_PAINT`, anything — must
        // replay the deferred resize before doing its own work, not lose
        // it.
        fake_wndproc(false, (1920, 1080));
        assert_eq!(
            surface_size.get(),
            (1920, 1080),
            "the resize ceded during the guarded call must be replayed, \
             not dropped, once the guard releases"
        );
        assert!(
            resized_dispatched.get(),
            "the app must still learn the window was resized"
        );
    }

    #[test]
    fn sequential_non_reentrant_calls_both_run() {
        let state = RefCell::new(0i32);
        let depth = ModalPumpDepth::new();
        assert_eq!(
            guarded_call(&state, &depth, |v| {
                *v += 1;
                *v
            }),
            Some(1)
        );
        assert_eq!(
            guarded_call(&state, &depth, |v| {
                *v += 1;
                *v
            }),
            Some(2)
        );
        assert!(
            !depth.is_pumping(),
            "depth must return to 0 once each guarded call completes"
        );
    }
}

/// Coverage for clipboard-paste interception in [`dispatch_event`].
/// `dispatch_event` itself is deliberately not `target_os`-gated
/// (see its doc comment), so this runs on every host.
///
/// **Which assertions are host-independent, and why that matters here.**
/// `WinPlatformServices::clipboard()` has no test seam: `read_text()`
/// is an unconditional `None` off Windows and a *real, uncontrolled*
/// Win32 `CF_UNICODETEXT` read on Windows — the machine's live
/// systemwide clipboard. So "the app received nothing at all" is a
/// claim only non-Windows hosts can make. The tests below are split
/// accordingly:
///
/// - `ctrl_v_is_never_forwarded_to_the_app_as_a_raw_keypress` runs on
///   every host and asserts the invariant that holds for both branches:
///   once `is_paste_keypress` recognises the chord, the raw `KeyPressed`
///   is consumed.
/// - `ctrl_v_with_nothing_to_paste_is_consumed_not_forwarded` is gated
///   to non-Windows, where "nothing to paste" is a property of
///   `WinClipboard::read_text`.
/// - `ctrl_v_delivers_real_clipboard_text_as_clipboard_paste` is gated
///   to Windows and seeds the clipboard first, covering the "reads real
///   clipboard text" branch on the CI leg that can.
#[cfg(test)]
mod paste_dispatch_tests {
    use super::*;
    use crate::runner::Reaction;
    use crate::{Key, Modifiers, UiEvent};

    /// Payload for the Windows-only round-trip below. Distinctive enough
    /// that a stale clipboard entry can't be mistaken for it.
    #[cfg(target_os = "windows")]
    const PASTE_PAYLOAD: &str = "quadraui#728 ctrl-v round trip";

    /// Records every event `handle` receives, so tests can assert an
    /// intercepted paste trigger does NOT also forward the raw key event
    /// underneath it — mirrors `gtk::run::paste_tests::RecordingApp`.
    #[derive(Default)]
    struct RecordingApp {
        events: Vec<UiEvent>,
    }

    impl AppLogic for RecordingApp {
        type AreaId = ();

        fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

        fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            self.events.push(event);
            Reaction::Continue
        }
    }

    fn ctrl_v() -> UiEvent {
        UiEvent::KeyPressed {
            key: Key::Char('v'),
            modifiers: Modifiers {
                ctrl: true,
                shift: false,
                alt: false,
                cmd: false,
            },
            repeat: false,
        }
    }

    /// The one paste-interception claim that is true on every host, with
    /// any clipboard contents: `dispatch_event` swallows the recognised
    /// chord. Whether the clipboard had text (Windows, maybe) or not
    /// (everywhere else, always) only changes *what else* the app sees —
    /// a `ClipboardPaste`, or nothing — never whether the raw key event
    /// leaks through underneath it.
    ///
    /// Takes [`crate::win::lock_real_clipboard`] even though its own
    /// assertion tolerates any clipboard contents: on Windows the Ctrl-V
    /// interception *reads* the real clipboard, and a read that lands
    /// while another test holds the clipboard open fails rather than
    /// blocking — see that function's doc for the whole invariant.
    #[test]
    fn ctrl_v_is_never_forwarded_to_the_app_as_a_raw_keypress() {
        let _clipboard = crate::win::lock_real_clipboard();
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        let _ = dispatch_event(ctrl_v(), &mut backend, &mut app);
        assert!(
            app.events
                .iter()
                .all(|e| matches!(e, UiEvent::ClipboardPaste(_))),
            "once is_paste_keypress recognises the chord, the raw Ctrl-V \
             KeyPressed must never reach the app — the only thing that may \
             is a ClipboardPaste; got {:?}",
            app.events
        );
    }

    /// The "nothing to paste" branch, asserted only where it is a
    /// compile-time property rather than a guess about the host:
    /// `WinClipboard::read_text` is an unconditional `None` off Windows
    /// (`win::services`'s `Clipboard` impl), so the app must see nothing
    /// at all and the outcome must be `Continue`.
    #[cfg(not(target_os = "windows"))]
    #[test]
    fn ctrl_v_with_nothing_to_paste_is_consumed_not_forwarded() {
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        let outcome = dispatch_event(ctrl_v(), &mut backend, &mut app);
        assert!(
            matches!(outcome, EventOutcome::Continue),
            "an intercepted paste keypress with an empty clipboard must \
             resolve to Continue, not fall through to app.handle"
        );
        assert!(
            app.events.is_empty(),
            "the raw Ctrl-V KeyPressed must never reach the app once \
             is_paste_keypress recognises it — got {:?}",
            app.events
        );
    }

    /// The branch that only a live Windows host can reach: a real
    /// `CF_UNICODETEXT` clipboard read feeding `UiEvent::ClipboardPaste`.
    /// Seeds the clipboard itself rather than assuming what is on it.
    ///
    /// Self-guarding: if the round-trip write→read doesn't come back
    /// intact, this host's clipboard is unavailable to the process
    /// (`OpenClipboard` fails on a non-interactive window station, for
    /// one), which is a property of the environment and not of
    /// `dispatch_event`. The `ctrl_v_is_never_forwarded_to_the_app_as_a_raw_keypress`
    /// test above still covers the interception path unconditionally on this
    /// same host.
    ///
    /// The seed → read-back → `dispatch_event` sequence is only sound while
    /// nothing else writes the systemwide clipboard in between, so it runs
    /// under [`crate::win::lock_real_clipboard`] to avoid races with other
    /// tests that write the clipboard.
    ///
    /// `#[allow(clippy::print_stderr)]`: this is test-harness diagnostic
    /// output, never reached by a host embedding a live quadraui backend.
    #[cfg(target_os = "windows")]
    #[test]
    #[allow(clippy::print_stderr)]
    fn ctrl_v_delivers_real_clipboard_text_as_clipboard_paste() {
        let _clipboard = crate::win::lock_real_clipboard();
        let mut backend = WinBackend::new();
        backend.services().clipboard().write_text(PASTE_PAYLOAD);
        let seeded = backend.services().clipboard().read_text();
        if seeded.as_deref() != Some(PASTE_PAYLOAD) {
            eprintln!(
                "quadraui: skipping ctrl_v_delivers_real_clipboard_text_as_clipboard_paste — \
                 this host's clipboard is not usable from the test process (wrote \
                 {PASTE_PAYLOAD:?}, read back {seeded:?})"
            );
            return;
        }

        let mut app = RecordingApp::default();
        let _ = dispatch_event(ctrl_v(), &mut backend, &mut app);
        assert_eq!(
            app.events,
            vec![UiEvent::ClipboardPaste(PASTE_PAYLOAD.to_string())],
            "Ctrl-V with text on the clipboard must deliver exactly one \
             ClipboardPaste carrying that text, and no raw KeyPressed"
        );
    }

    #[test]
    fn non_paste_keypress_still_reaches_the_app() {
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        let ev = UiEvent::KeyPressed {
            key: Key::Char('x'),
            modifiers: Modifiers::default(),
            repeat: false,
        };
        let _ = dispatch_event(ev.clone(), &mut backend, &mut app);
        assert_eq!(
            app.events,
            vec![ev],
            "a non-paste keypress must fall through to app.handle unchanged"
        );
    }
}

/// Coverage for Ctrl-chord accelerator dispatch: does a registered
/// accelerator actually reach the app once the *translated* `WM_CHAR`
/// payload Windows delivers for each chord is fed through the real,
/// shared `dispatch_event` → `crate::runtime::preprocess_event` →
/// `BackendCore::match_keypress` pipeline?
///
/// Unlike `win::testing::WinDriver` (which builds an already-decoded
/// `UiEvent::KeyPressed` directly, bypassing `events.rs`'s `WM_CHAR`
/// translation by design), this module chains the translation step
/// genuinely: it builds the raw `char` + modifiers payload a real
/// `wndproc` would hand [`crate::win::events::wm_char_to_uievent`] for
/// each chord, translates it through that function, and only then feeds
/// the result to [`dispatch_event`]. `dispatch_event` is deliberately
/// not `target_os`-gated (see its doc comment), so this one **genuinely
/// executes**, including on plain `cargo test --features win` on Linux.
#[cfg(test)]
mod ctrl_accelerator_dispatch_tests_1674 {
    use super::*;
    use crate::runner::Reaction;
    use crate::{Accelerator, AcceleratorId, AcceleratorScope, KeyBinding, Modifiers, UiEvent};

    /// Records every event `handle` receives — same shape as
    /// `paste_dispatch_tests::RecordingApp` above.
    #[derive(Default)]
    struct RecordingApp {
        events: Vec<UiEvent>,
    }

    impl AppLogic for RecordingApp {
        type AreaId = ();

        fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

        fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            self.events.push(event);
            Reaction::Continue
        }
    }

    fn global_accelerator(id: &str, binding: &str) -> Accelerator {
        Accelerator {
            id: AcceleratorId::new(id),
            binding: KeyBinding::Literal(binding.to_string()),
            scope: AcceleratorScope::Global,
            label: None,
        }
    }

    /// Ctrl+B: Windows' keyboard driver converts Ctrl+letter to its C0
    /// control code (`0x02` for B) via `TranslateMessage` before
    /// `WM_CHAR` delivers it — `events::tests::char_ctrl_letter_recovers_base_letter`
    /// already proves the translator recovers `Key::Char('b')` with
    /// `ctrl == true` from that payload; this test carries the recovered
    /// event one step further,
    /// through a registered `<C-b>` accelerator, and asserts the app
    /// sees `UiEvent::Accelerator`, not the raw keypress.
    #[test]
    fn ctrl_b_accelerator_reaches_the_app_via_dispatch_event() {
        let mut backend = WinBackend::new();
        backend.register_accelerator(&global_accelerator("toggle-sidebar", "<C-b>"));

        let modifiers = Modifiers {
            ctrl: true,
            ..Default::default()
        };
        let event = crate::win::events::wm_char_to_uievent('\u{0002}', modifiers, false)
            .expect("Ctrl+B's WM_CHAR payload must translate to a KeyPressed event");

        let mut app = RecordingApp::default();
        let _ = dispatch_event(event, &mut backend, &mut app);
        assert_eq!(
            app.events,
            vec![UiEvent::Accelerator(
                AcceleratorId::new("toggle-sidebar"),
                modifiers
            )],
            "a registered Ctrl+B accelerator must reach the app as \
             UiEvent::Accelerator once WM_CHAR's '\\x02' payload is \
             translated — got {:?}",
            app.events
        );
    }

    /// Ctrl+`: backtick is not a control character, so
    /// `wm_char_to_uievent` never reaches its Ctrl-recovery branch — it
    /// passes the literal backtick straight through with `ctrl` still
    /// set on `modifiers`. That is already exactly the event a
    /// registered `<C-`>` accelerator matches, so this chord needs no
    /// special-case recovery at all once Windows delivers the `WM_CHAR`.
    #[test]
    fn ctrl_backtick_accelerator_reaches_the_app_via_dispatch_event() {
        let mut backend = WinBackend::new();
        backend.register_accelerator(&global_accelerator("toggle-terminal", "<C-`>"));

        let modifiers = Modifiers {
            ctrl: true,
            ..Default::default()
        };
        let event = crate::win::events::wm_char_to_uievent('`', modifiers, false)
            .expect("Ctrl+`'s WM_CHAR payload must translate to a KeyPressed event");

        let mut app = RecordingApp::default();
        let _ = dispatch_event(event, &mut backend, &mut app);
        assert_eq!(
            app.events,
            vec![UiEvent::Accelerator(
                AcceleratorId::new("toggle-terminal"),
                modifiers
            )],
            "a registered Ctrl+` accelerator must reach the app as \
             UiEvent::Accelerator once WM_CHAR's literal backtick payload \
             is translated with ctrl held — got {:?}",
            app.events
        );
    }
}

/// Coverage for text-selection pre-processing in `dispatch_event`, plus
/// [`route_mouse_down`]/[`route_mouse_move`]/[`route_mouse_up`]'s routing.
/// None of this depends on a live Direct2D surface or `target_os =
/// "windows"` — the state machine, `dispatch_event`, and the three
/// `route_mouse_*` helpers are all plain `WinBackend`/`crate::dispatch`
/// logic — so this runs and is asserted on every host.
#[cfg(test)]
mod text_selection_dispatch_tests {
    use super::*;
    use crate::dispatch::TextRegion;
    use crate::runner::Reaction;
    use crate::types::WidgetId;
    use crate::{ButtonMask, Key, Modifiers, MouseButton, UiEvent};

    #[derive(Default)]
    struct RecordingApp {
        events: Vec<UiEvent>,
    }

    impl AppLogic for RecordingApp {
        type AreaId = ();

        fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

        fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            self.events.push(event);
            Reaction::Continue
        }
    }

    fn region(id: &str, x: f32, y: f32, w: f32, h: f32, lines: &[&str]) -> TextRegion {
        TextRegion {
            id: WidgetId::new(id),
            bounds: crate::event::Rect::new(x, y, w, h),
            lines: lines.iter().map(|s| s.to_string()).collect(),
        }
    }

    fn ctrl_char(c: char) -> UiEvent {
        UiEvent::KeyPressed {
            key: Key::Char(c),
            modifiers: Modifiers {
                ctrl: true,
                shift: false,
                alt: false,
                cmd: false,
            },
            repeat: false,
        }
    }

    /// End-to-end round trip: click-drag across a registered `TextRegion`,
    /// then Ctrl-C. `WinBackend::new()`'s default metrics (16.0 line
    /// height, 8.0 char width) make the pixel math easy: a region one line
    /// tall and 88 DIPs wide covers exactly 11 columns.
    ///
    /// The Ctrl-C at the end writes to the **real** systemwide clipboard on
    /// Windows, so this takes [`crate::win::lock_real_clipboard`] for its
    /// whole body to avoid races with other tests that access the clipboard.
    #[test]
    fn drag_select_then_ctrl_c_copies_the_selection() {
        let _clipboard = crate::win::lock_real_clipboard();
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        backend.register_text_region(region("body", 0.0, 0.0, 88.0, 16.0, &["hello world"]));

        // Press inside the region (row 0, col 0).
        let outcome = route_mouse_down(
            &mut backend,
            &mut app,
            crate::event::Point::new(0.0, 4.0),
            MouseButton::Left,
            Modifiers::default(),
        );
        assert!(matches!(
            outcome,
            EventOutcome::Continue | EventOutcome::Redraw
        ));

        // Drag to the far right of the region (row 0, col 11 — "hello world" in full).
        let outcome = route_mouse_move(
            &mut backend,
            &mut app,
            crate::event::Point::new(88.0, 4.0),
            ButtonMask {
                left: true,
                ..ButtonMask::default()
            },
        );
        assert!(
            matches!(outcome, EventOutcome::Redraw),
            "a TextSelectionChanged event must force a redraw"
        );
        assert!(
            backend.active_text_selection().is_some(),
            "dragging across a registered TextRegion must produce an active selection"
        );

        // Release — ends the drag, does not clear the selection.
        let _ = route_mouse_up(
            &mut backend,
            &mut app,
            crate::event::Point::new(88.0, 4.0),
            MouseButton::Left,
        );
        assert!(
            backend.active_text_selection().is_some(),
            "MouseUp must not clear the finalised selection"
        );

        // Ctrl-C copies it, clears it, and delivers TextCopied.
        let outcome = dispatch_event(ctrl_char('c'), &mut backend, &mut app);
        assert!(matches!(
            outcome,
            EventOutcome::Redraw | EventOutcome::Continue
        ));
        assert!(
            backend.active_text_selection().is_none(),
            "Ctrl-C must clear the selection after copying it"
        );
        assert!(
            app.events
                .iter()
                .any(|e| matches!(e, UiEvent::TextCopied(text) if text == "hello world")),
            "Ctrl-C over a full-region selection must deliver TextCopied(\"hello world\"); \
             got {:?}",
            app.events
        );
    }

    #[test]
    fn ctrl_c_without_a_selection_falls_through_to_the_app() {
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        let ev = ctrl_char('c');
        let _ = dispatch_event(ev.clone(), &mut backend, &mut app);
        assert_eq!(
            app.events,
            vec![ev],
            "Ctrl-C with no active selection must fall through to app.handle unchanged, \
             matching gtk::run::dispatch_event/TuiBackend::apply_dispatch"
        );
    }

    #[test]
    fn ctrl_a_selects_the_sole_registered_region() {
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        backend.register_text_region(region("body", 0.0, 0.0, 40.0, 16.0, &["hi"]));
        let outcome = dispatch_event(ctrl_char('a'), &mut backend, &mut app);
        assert!(matches!(outcome, EventOutcome::Redraw));
        assert!(
            backend.active_text_selection().is_some(),
            "Ctrl-A must select the sole registered TextRegion"
        );
        assert!(
            app.events.is_empty(),
            "a recognised Ctrl-A must not also forward the raw KeyPressed to the app"
        );
    }

    #[test]
    fn ctrl_a_with_no_regions_falls_through_to_the_app() {
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        let ev = ctrl_char('a');
        let _ = dispatch_event(ev.clone(), &mut backend, &mut app);
        assert_eq!(
            app.events,
            vec![ev],
            "Ctrl-A with no registered TextRegion must fall through to app.handle unchanged"
        );
    }

    #[test]
    fn mouse_down_clears_the_displayed_selection() {
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        backend.set_active_text_selection(
            WidgetId::new("r"),
            crate::event::Point::new(0.0, 0.0),
            crate::event::Point::new(10.0, 0.0),
        );
        assert!(backend.active_text_selection().is_some());
        let ev = UiEvent::MouseDown {
            widget: None,
            button: MouseButton::Left,
            position: crate::event::Point::new(0.0, 0.0),
            modifiers: Modifiers::default(),
        };
        let _ = dispatch_event(ev, &mut backend, &mut app);
        assert!(
            backend.active_text_selection().is_none(),
            "a MouseDown reaching dispatch_event must clear the displayed selection"
        );
    }

    #[test]
    fn text_selection_changed_updates_active_selection_and_forces_redraw() {
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        backend.register_text_region(region("body", 0.0, 0.0, 40.0, 16.0, &["hi there"]));
        let ev = UiEvent::TextSelectionChanged {
            region: WidgetId::new("body"),
            anchor: crate::event::Point::new(0.0, 0.0),
            focus: crate::event::Point::new(40.0, 0.0),
        };
        let outcome = dispatch_event(ev, &mut backend, &mut app);
        assert!(matches!(outcome, EventOutcome::Redraw));
        assert!(backend.active_text_selection().is_some());
    }

    /// Before this, `win::run::dispatch_event` had no
    /// middle-click step at all — only GTK read the PRIMARY selection.
    /// `WinClipboard` never overrides
    /// [`crate::backend::Clipboard::read_primary_selection`] (Windows has
    /// no PRIMARY-selection concept), so the shared
    /// `preprocess_event` step this backend now runs is always the
    /// "nothing to paste" branch — the middle-click event must fall
    /// through unchanged, on *every* host including a real
    /// `windows-latest` run, not just off-Windows.
    #[test]
    fn middle_click_falls_through_to_the_app_no_primary_selection_on_windows() {
        let mut backend = WinBackend::new();
        let mut app = RecordingApp::default();
        let ev = UiEvent::MouseDown {
            widget: None,
            button: MouseButton::Middle,
            position: crate::event::Point::new(5.0, 5.0),
            modifiers: Modifiers::default(),
        };
        let _ = dispatch_event(ev.clone(), &mut backend, &mut app);
        assert_eq!(
            app.events,
            vec![ev],
            "middle-click must fall through to app.handle unchanged when there is no \
             PRIMARY selection to paste, matching gtk::run's identical fallthrough branch"
        );
    }
}

/// Coverage for panic safety in `dispatch_event`: it must catch a panic
/// from `app.handle` rather than let it propagate out to `wndproc`'s C
/// ABI boundary (see `dispatch_event`'s "Panic safety" doc). Runs on
/// every host: `dispatch_event` itself isn't `target_os`-gated (see its
/// doc), and this module proves the Rust-side half of the fix — the
/// shared funnel every `WM_*` message dispatches `app.handle` through.
#[cfg(test)]
mod panic_guard_tests {
    use super::*;
    use crate::runner::Reaction;
    use crate::{Key, Modifiers, UiEvent};

    struct PanicsOnHandle;

    impl AppLogic for PanicsOnHandle {
        type AreaId = ();

        fn render(&self, _backend: &mut dyn Backend, _area: ()) {}

        fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            panic!("PanicsOnHandle: deliberate panic for #922 coverage");
        }
    }

    fn some_key() -> UiEvent {
        UiEvent::KeyPressed {
            key: Key::Char('z'),
            modifiers: Modifiers::default(),
            repeat: false,
        }
    }

    #[test]
    fn a_panicking_handle_does_not_unwind_past_dispatch_event() {
        let mut backend = WinBackend::new();
        let mut app = PanicsOnHandle;
        // If `dispatch_event` didn't catch this, the panic would unwind
        // out of this call and fail the test with an uncaught panic
        // rather than a normal assertion failure — the test process
        // reaching the assertion below at all is part of what's proven.
        let outcome = dispatch_event(some_key(), &mut backend, &mut app);
        assert!(
            matches!(outcome, EventOutcome::Continue),
            "a caught panic in app.handle must resolve to Continue (no \
             redraw, no exit), matching wndproc's fallthrough for every \
             message it doesn't otherwise handle"
        );
    }

    #[test]
    fn a_panicking_handle_keeps_working_across_repeated_frames() {
        let mut backend = WinBackend::new();
        let mut app = PanicsOnHandle;
        // A reachable panic in app logic is re-entered on every repaint —
        // assert `dispatch_event` keeps degrading gracefully rather than
        // aborting or hanging on repeated occurrences.
        for _ in 0..5 {
            let outcome = dispatch_event(some_key(), &mut backend, &mut app);
            assert!(matches!(outcome, EventOutcome::Continue));
        }
    }

    #[test]
    fn a_non_panicking_handle_is_unaffected_by_the_guard() {
        struct RecordingApp {
            seen: bool,
        }
        impl AppLogic for RecordingApp {
            type AreaId = ();
            fn render(&self, _backend: &mut dyn Backend, _area: ()) {}
            fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                self.seen = true;
                Reaction::Continue
            }
        }
        let mut backend = WinBackend::new();
        let mut app = RecordingApp { seen: false };
        let _ = dispatch_event(some_key(), &mut backend, &mut app);
        assert!(
            app.seen,
            "catch_unwind must not swallow or alter a non-panicking call"
        );
    }
}